From 444bd62996673d95756eaa79827bebf4d7541b50 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:21:30 +0100 Subject: [PATCH 01/84] feat(app): add run foundation repository and models --- app/lib/features/runs/domain/run_events.dart | 24 ++++++++ app/lib/features/runs/domain/run_models.dart | 33 +++++++++++ app/notes/F3.md | 12 ++++ .../features/runs/runs_foundation_test.dart | 59 +++++++++++++++++++ 4 files changed, 128 insertions(+) create mode 100644 app/lib/features/runs/domain/run_events.dart create mode 100644 app/lib/features/runs/domain/run_models.dart create mode 100644 app/notes/F3.md create mode 100644 app/test/features/runs/runs_foundation_test.dart diff --git a/app/lib/features/runs/domain/run_events.dart b/app/lib/features/runs/domain/run_events.dart new file mode 100644 index 00000000..5462d217 --- /dev/null +++ b/app/lib/features/runs/domain/run_events.dart @@ -0,0 +1,24 @@ +import '../../../core/api_gateway.dart'; +const _terminal = {'succeeded','failed','canceled','interrupted'}; +int _rank(dynamic s) => s == 'queued' ? 0 : {'running','waiting'}.contains(s) ? 1 : _terminal.contains(s) ? 2 : -1; +int _stepRank(dynamic s) => {'running','waiting'}.contains(s) ? 1 : {'completed','failed','canceled','interrupted'}.contains(s) ? 2 : -1; +bool _stale(dynamic a, dynamic b, int Function(dynamic) rank) => '${b ?? ''}'.trim().isNotEmpty && rank(a) >= 0 && rank(b) >= 0 && (rank(b) < rank(a) || (rank(a) == 2 && rank(b) == 2 && a != b)); +String _advance(dynamic a, dynamic b, int Function(dynamic) rank) => '${b ?? ''}'.trim().isEmpty || rank(b) < rank(a) || (rank(a) == 2 && rank(b) == 2) ? '${a ?? ''}' : '${b ?? ''}'; +({List runs, bool needsResync}) foldRunEvent(List runs, JsonMap frame) { + final id = frame['run_id']; if (id is! num || id <= 0) return (runs:runs, needsResync:false); + final i = runs.indexWhere((r) => r['id'] == id); + if (i < 0) { final pid=frame['pipeline_id']; final name=frame['name']; if (pid is! num || '${name ?? ''}'.trim().isEmpty) return (runs:runs, needsResync:true); + return (runs:[{'id':id,'pipeline_id':pid,'name':name,'title':frame['title'],'version':frame['version'] ?? 0,'status':frame['status'] ?? '', 'executing':true,'completed_steps':frame['completed_steps'] ?? 0,'created_at':frame['created_at'] ?? '', 'finished_at':frame['finished_at'] ?? '', 'resource_wait':frame['resource_wait']}, ...runs], needsResync:false); } + final current=runs[i]; if (_stale(current['status'],frame['status'],_rank) && frame['resource_wait_set'] != true) return (runs:runs, needsResync:false); + final status=frame['resource_wait_set']==true && frame['status']=='queued' && !_terminal.contains(current['status']) ? 'queued' : _advance(current['status'],frame['status'],_rank); + final updated={...current,'status':status,'executing':status=='queued'||status=='running','completed_steps':(((current['completed_steps'] as num?)??0).toInt()).clamp(((frame['completed_steps'] as num?)??0).toInt(),0x7fffffff),'resource_wait':_terminal.contains(status)?null:frame['resource_wait_set']==true?frame['resource_wait']:current['resource_wait']}; + for(final k in ['outcome','current_stage','finished_at','created_at']) { if ('${frame[k]??''}'.trim().isNotEmpty) updated[k]=frame[k]; } + final next=[...runs]; next[i]=updated; return (runs:next,needsResync:false); +} +bool runDetailNeedsFullSync(JsonMap f) => _terminal.contains(f['status']) || f['status']=='waiting' || f['cancel_requested']==true || f['cleanup_unconfirmed']==true || f['step']?['status']=='waiting' || _stepRank(f['step']?['status'])==2; +JsonMap? foldRunEventDetail(JsonMap? detail, JsonMap frame) { + if(detail==null || detail['id']!=frame['run_id'] || (_stale(detail['status'],frame['status'],_rank)&&frame['resource_wait_set']!=true)) return detail; + final folded=foldRunEvent([detail],frame).runs.single; final delta=frame['step']; + if(delta is Map) { final steps=List.from(detail['steps']??[]); final i=steps.indexWhere((s)=>s['sequence']==delta['sequence']); if(i<0){steps.add(Map.from(delta));steps.sort((a,b)=>((a['sequence'] as num?)??0).compareTo((b['sequence'] as num?)??0));} else if(!_stale(steps[i]['status'],delta['status'],_stepRank)){steps[i]={...steps[i],...Map.from(delta)};} folded['steps']=steps; } + return folded; +} diff --git a/app/lib/features/runs/domain/run_models.dart b/app/lib/features/runs/domain/run_models.dart new file mode 100644 index 00000000..5fe96a56 --- /dev/null +++ b/app/lib/features/runs/domain/run_models.dart @@ -0,0 +1,33 @@ +import '../../../core/api_gateway.dart'; + +const runStates = ['queued', 'running', 'waiting', 'succeeded', 'failed', 'canceled', 'interrupted']; +({String label, String? pipeline}) runIdentity(dynamic title, dynamic name) { + final stored = '${title ?? ''}'.trim(); + return (label: stored.isNotEmpty ? stored : '${name ?? ''}', pipeline: stored.isNotEmpty ? '${name ?? ''}' : null); +} +String runStateOf(dynamic status) => switch ('${status ?? ''}'.trim().toLowerCase()) { + 'queued' || 'running' || 'waiting' || 'active' || 'blocked' || 'skipped' => '${status ?? ''}'.trim().toLowerCase(), + 'succeeded' || 'success' || 'completed' || 'done' => 'succeeded', + 'failed' || 'error' => 'failed', 'canceled' || 'cancelled' => 'canceled', 'interrupted' => 'interrupted', _ => 'unknown', +}; +List filterRuns(List runs, {Set statuses = const {}, int? pipelineId}) => runs.where((r) => (statuses.isEmpty || statuses.contains(runStateOf(r['status']))) && (pipelineId == null || r['pipeline_id'] == pipelineId)).toList(); +List sortRuns(List runs, {String sort = 'newest_first'}) { + int time(dynamic x) => DateTime.tryParse('${x ?? ''}')?.millisecondsSinceEpoch ?? -0x7fffffffffffffff; + final result = [...runs]; + result.sort((a,b) { + final c = switch (sort) { 'oldest_first' => time(a['created_at']).compareTo(time(b['created_at'])), 'pipeline_name' => '${a['name'] ?? ''}'.toLowerCase().compareTo('${b['name'] ?? ''}'.toLowerCase()), 'status' => '${a['status'] ?? ''}'.compareTo('${b['status'] ?? ''}'), _ => time(b['created_at']).compareTo(time(a['created_at'])) }; + return c == 0 ? ((b['id'] as num?) ?? 0).compareTo((a['id'] as num?) ?? 0) : c; + }); + return result; +} +/// Null usage means unsupported/unavailable, not zero. +class RunListResult { const RunListResult(this.runs, this.usage); final List runs; final JsonMap? usage; } +class DecisionOption { const DecisionOption(this.key, {this.target = ''}); final String key; final String target; } +class DecisionDraft { const DecisionDraft({this.selected, this.feedback = ''}); final String? selected; final String feedback; bool get canSubmit => selected != null && selected!.trim().isNotEmpty; } +String attentionKey(num runId, String kind) => '$runId:$kind'; +List orderAttention(List runs, {Set dismissed = const {}}) { + final result = runs.where((r) => ['waiting','failed'].contains(r['status']) && !dismissed.contains(attentionKey(r['id'] as num, r['status'] == 'waiting' ? 'Decision' : 'Failed'))).toList(); + int at(JsonMap r) => DateTime.tryParse('${r['finished_at'] ?? r['created_at'] ?? ''}')?.millisecondsSinceEpoch ?? 0; + result.sort((a,b) { final rank = (a['status'] == 'waiting' ? 0 : 1).compareTo(b['status'] == 'waiting' ? 0 : 1); if (rank != 0) return rank; final date = at(b).compareTo(at(a)); return date != 0 ? date : (b['id'] as num).compareTo(a['id'] as num); }); + return result; +} diff --git a/app/notes/F3.md b/app/notes/F3.md new file mode 100644 index 00000000..79954b60 --- /dev/null +++ b/app/notes/F3.md @@ -0,0 +1,12 @@ +# F3 run foundation + +Public API: `run_models.dart` provides run identity/state/filter/sort helpers, +`RunListResult`, decision draft/option values, and attention ordering/identity. +`run_events.dart` provides monotonic list/detail event folds and +`runDetailNeedsFullSync`. `data/runs_repository.dart` provides `RunsRepository` +for list/get/cancel/retry/decide/title/start calls through the shared gateway. + +Focused tests cover stale lifecycle deltas, explicit resource-wait clearing, +unknown usage versus zero, decision refusal, attention identity/order, and exact +retry/start fields. This is a nonvisual foundation; browser UI captures were not +applicable. Mobile targets are unverified. diff --git a/app/test/features/runs/runs_foundation_test.dart b/app/test/features/runs/runs_foundation_test.dart new file mode 100644 index 00000000..9ad8f833 --- /dev/null +++ b/app/test/features/runs/runs_foundation_test.dart @@ -0,0 +1,59 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/data/runs_repository.dart'; +import 'package:pipelines_app/features/runs/domain/run_events.dart'; +import 'package:pipelines_app/features/runs/domain/run_models.dart'; + +class FakeGateway implements ApiGateway { + String? type; + JsonMap fields = {}; + JsonMap reply = {}; + @override + Future call(String type, [JsonMap fields = const {}]) async { + this.type = type; + this.fields = Map.of(fields); + return reply; + } + @override + Stream get frames => const Stream.empty(); +} + +void main() { + test('filter/sort identities and unknown usage remain distinct', () { + expect(runIdentity(' Report ', 'Build').label, 'Report'); + final rows = [{'id': 1, 'pipeline_id': 2, 'status': 'failed', 'created_at': '2024-01-01'}, {'id': 2, 'pipeline_id': 2, 'status': 'running', 'created_at': '2025-01-01'}]; + expect(filterRuns(rows, statuses: {'failed'}).single['id'], 1); + expect(sortRuns(rows).first['id'], 2); + expect(RunListResult(const [], null).usage, isNull); + }); + + test('fold is monotonic and explicit resource wait clearing is honored', () { + final rows = [{'id': 1, 'status': 'running', 'completed_steps': 3, 'resource_wait': {'resource': 'gpu'}}]; + final stale = foldRunEvent(rows, {'run_id': 1, 'status': 'queued', 'completed_steps': 1}); + expect(stale.runs.single['status'], 'running'); + final cleared = foldRunEvent(rows, {'run_id': 1, 'status': 'queued', 'resource_wait_set': true, 'resource_wait': null}); + expect(cleared.runs.single['status'], 'queued'); + expect(cleared.runs.single['resource_wait'], isNull); + expect(cleared.runs.single['completed_steps'], 3); + expect(runDetailNeedsFullSync({'status': 'waiting'}), isTrue); + }); + + test('decision guard and attention dismissal identity', () { + expect(const DecisionDraft().canSubmit, isFalse); + expect(const DecisionDraft(selected: ' continue ').canSubmit, isTrue); + expect(attentionKey(7, 'Decision'), '7:Decision'); + final ordered = orderAttention([{'id': 8, 'status': 'failed'}, {'id': 7, 'status': 'waiting'}]); + expect(ordered.first['id'], 7); + }); + + test('repository emits exact action envelopes and requires idempotency key', () async { + final gateway = FakeGateway()..reply = {'run_detail': {'id': 3}}; + final repo = RunsRepository(gateway); + await repo.retryRun(3, requestKey: 'retry-1'); + expect(gateway.type, 'retry_run'); + expect(gateway.fields, {'run_id': 3, 'request_key': 'retry-1'}); + await repo.startRun(pipelineId: 4, version: 2, prompt: 'hello', workspace: ' /work ', requestKey: 'start-2'); + expect(gateway.fields, {'pipeline_id': 4, 'version': 2, 'request_key': 'start-2', 'workspace': '/work', 'input': {'prompt': 'hello'}}); + await expectLater(repo.decideRun(3, option: ' '), throwsA(isA())); + }); +} From cee5f72b144a4e217453e01e60d1e15d20cdf158 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:22:58 +0100 Subject: [PATCH 02/84] feat(app): add adaptive client shell --- app/lib/main.dart | 139 +++++++----------------------- app/lib/shell/adaptive_shell.dart | 99 +++++++++++++++++++++ app/lib/shell/destination.dart | 17 ++++ app/notes/F2.md | 18 ++++ app/test/widget_test.dart | 76 +++++++++++----- 5 files changed, 222 insertions(+), 127 deletions(-) create mode 100644 app/lib/shell/adaptive_shell.dart create mode 100644 app/lib/shell/destination.dart create mode 100644 app/notes/F2.md diff --git a/app/lib/main.dart b/app/lib/main.dart index 244a702c..0c08d900 100644 --- a/app/lib/main.dart +++ b/app/lib/main.dart @@ -1,122 +1,47 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; -void main() { - runApp(const MyApp()); -} +import 'shell/adaptive_shell.dart'; +import 'shell/destination.dart'; + +export 'shell/adaptive_shell.dart'; +export 'shell/destination.dart'; + +void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { - const MyApp({super.key}); + const MyApp({super.key, this.destinationBodies = const {}, this.cupertino}); + + final Map destinationBodies; + final bool? cupertino; - // This widget is the root of your application. @override Widget build(BuildContext context) { + final platform = defaultTargetPlatform; + if (cupertino ?? + (platform == TargetPlatform.iOS || platform == TargetPlatform.macOS)) { + return CupertinoApp( + title: 'Pipelines', + home: AdaptiveShell( + destinationBodies: destinationBodies, + cupertino: true, + ), + ); + } return MaterialApp( - title: 'Flutter Demo', + title: 'Pipelines', theme: ThemeData( - // This is the theme of your application. - // - // TRY THIS: Try running your application with "flutter run". You'll see - // the application has a purple toolbar. Then, without quitting the app, - // try changing the seedColor in the colorScheme below to Colors.green - // and then invoke "hot reload" (save your changes or press the "hot - // reload" button in a Flutter-supported IDE, or press "r" if you used - // the command line to start the app). - // - // Notice that the counter didn't reset back to zero; the application - // state is not lost during the reload. To reset the state, use hot - // restart instead. - // - // This works for code too, not just values: Most code changes can be - // tested with just a hot reload. - colorScheme: .fromSeed(seedColor: Colors.deepPurple), + colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue), ), - home: const MyHomePage(title: 'Flutter Demo Home Page'), - ); - } -} - -class MyHomePage extends StatefulWidget { - const MyHomePage({super.key, required this.title}); - - // This widget is the home page of your application. It is stateful, meaning - // that it has a State object (defined below) that contains fields that affect - // how it looks. - - // This class is the configuration for the state. It holds the values (in this - // case the title) provided by the parent (in this case the App widget) and - // used by the build method of the State. Fields in a Widget subclass are - // always marked "final". - - final String title; - - @override - State createState() => _MyHomePageState(); -} - -class _MyHomePageState extends State { - int _counter = 0; - - void _incrementCounter() { - setState(() { - // This call to setState tells the Flutter framework that something has - // changed in this State, which causes it to rerun the build method below - // so that the display can reflect the updated values. If we changed - // _counter without calling setState(), then the build method would not be - // called again, and so nothing would appear to happen. - _counter++; - }); - } - - @override - Widget build(BuildContext context) { - // This method is rerun every time setState is called, for instance as done - // by the _incrementCounter method above. - // - // The Flutter framework has been optimized to make rerunning build methods - // fast, so that you can just rebuild anything that needs updating rather - // than having to individually change instances of widgets. - return Scaffold( - appBar: AppBar( - // TRY THIS: Try changing the color here to a specific color (to - // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar - // change color while the other colors stay the same. - backgroundColor: Theme.of(context).colorScheme.inversePrimary, - // Here we take the value from the MyHomePage object that was created by - // the App.build method, and use it to set our appbar title. - title: Text(widget.title), - ), - body: Center( - // Center is a layout widget. It takes a single child and positions it - // in the middle of the parent. - child: Column( - // Column is also a layout widget. It takes a list of children and - // arranges them vertically. By default, it sizes itself to fit its - // children horizontally, and tries to be as tall as its parent. - // - // Column has various properties to control how it sizes itself and - // how it positions its children. Here we use mainAxisAlignment to - // center the children vertically; the main axis here is the vertical - // axis because Columns are vertical (the cross axis would be - // horizontal). - // - // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint" - // action in the IDE, or press "p" in the console), to see the - // wireframe for each widget. - mainAxisAlignment: .center, - children: [ - const Text('You have pushed the button this many times:'), - Text( - '$_counter', - style: Theme.of(context).textTheme.headlineMedium, - ), - ], + darkTheme: ThemeData( + colorScheme: ColorScheme.fromSeed( + seedColor: Colors.blue, + brightness: Brightness.dark, ), ), - floatingActionButton: FloatingActionButton( - onPressed: _incrementCounter, - tooltip: 'Increment', - child: const Icon(Icons.add), - ), + themeMode: ThemeMode.system, + home: AdaptiveShell(destinationBodies: destinationBodies), ); } } diff --git a/app/lib/shell/adaptive_shell.dart b/app/lib/shell/adaptive_shell.dart new file mode 100644 index 00000000..6964f4b0 --- /dev/null +++ b/app/lib/shell/adaptive_shell.dart @@ -0,0 +1,99 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'destination.dart'; + +class AdaptiveShell extends StatefulWidget { + const AdaptiveShell({ + super.key, + this.destinationBodies = const {}, + this.cupertino = false, + }); + + final Map destinationBodies; + final bool cupertino; + + @override + State createState() => _AdaptiveShellState(); +} + +class _AdaptiveShellState extends State { + AppDestination _selected = AppDestination.pipelines; + + void _select(AppDestination destination) => + setState(() => _selected = destination); + + List _items(T Function(AppDestination) build) => + AppDestination.values.map(build).toList(); + + @override + Widget build(BuildContext context) { + final index = AppDestination.values.indexOf(_selected); + final details = destinationDetails(_selected); + final content = + widget.destinationBodies[_selected]?.call(context) ?? + Center(child: Text('${details.label} — Not implemented')); + return LayoutBuilder( + builder: (context, constraints) { + final wide = constraints.maxWidth >= 600; + if (widget.cupertino) { + return CupertinoPageScaffold( + navigationBar: CupertinoNavigationBar(middle: Text(details.label)), + child: Column( + children: [ + Expanded(child: content), + CupertinoTabBar( + currentIndex: index, + onTap: (value) => _select(AppDestination.values[value]), + items: _items((destination) { + final item = destinationDetails(destination); + return BottomNavigationBarItem( + icon: Icon(item.icon), + label: item.label, + ); + }), + ), + ], + ), + ); + } + return Scaffold( + appBar: AppBar(title: Text(details.label)), + body: Row( + children: [ + if (wide) + NavigationRail( + selectedIndex: index, + onDestinationSelected: (value) => + _select(AppDestination.values[value]), + labelType: NavigationRailLabelType.all, + destinations: _items((destination) { + final item = destinationDetails(destination); + return NavigationRailDestination( + icon: Icon(item.icon), + label: Text(item.label), + ); + }), + ), + Expanded(child: content), + ], + ), + bottomNavigationBar: wide + ? null + : NavigationBar( + selectedIndex: index, + onDestinationSelected: (value) => + _select(AppDestination.values[value]), + destinations: _items((destination) { + final item = destinationDetails(destination); + return NavigationDestination( + icon: Icon(item.icon), + label: item.label, + ); + }), + ), + ); + }, + ); + } +} diff --git a/app/lib/shell/destination.dart b/app/lib/shell/destination.dart new file mode 100644 index 00000000..e8d0c373 --- /dev/null +++ b/app/lib/shell/destination.dart @@ -0,0 +1,17 @@ +import 'package:flutter/material.dart'; + +enum AppDestination { pipelines, runs, chat, settings } + +({String label, IconData icon}) destinationDetails(AppDestination value) => + switch (value) { + AppDestination.pipelines => ( + label: 'Pipelines', + icon: Icons.account_tree_outlined, + ), + AppDestination.runs => (label: 'Runs', icon: Icons.play_circle_outline), + AppDestination.chat => (label: 'Chat', icon: Icons.chat_bubble_outline), + AppDestination.settings => ( + label: 'Settings', + icon: Icons.settings_outlined, + ), + }; diff --git a/app/notes/F2.md b/app/notes/F2.md new file mode 100644 index 00000000..e70e653a --- /dev/null +++ b/app/notes/F2.md @@ -0,0 +1,18 @@ +# F2 — Adaptive shell + +Implemented standard adaptive navigation for Pipelines, Runs, Chat and Settings. +Material uses a bottom `NavigationBar` below 600 logical pixels and a labeled +`NavigationRail` at wider widths. Cupertino uses the native navigation bar and +tab bar. `MyApp` chooses Cupertino on iOS/macOS, leaves Material system light/dark +themes active elsewhere, and accepts injectable `WidgetBuilder` bodies through +`AdaptiveShell`; unregistered destinations are explicitly marked Not implemented. + +## Verification + +- `flutter test test/widget_test.dart`: passed (narrow/wide, 2x text scale, + Cupertino controls and injected destination body). +- `flutter analyze`: passed, no issues. +- Web build/browser interaction/capture: not run in this stage; no browser + automation/capture evidence available. Mobile targets are unverified. + +No API capabilities are asserted or mocked. No dependencies were added. diff --git a/app/test/widget_test.dart b/app/test/widget_test.dart index 41dc58b8..e10bf144 100644 --- a/app/test/widget_test.dart +++ b/app/test/widget_test.dart @@ -1,30 +1,66 @@ -// This is a basic Flutter widget test. -// -// To perform an interaction with a widget in your test, use the WidgetTester -// utility in the flutter_test package. For example, you can send tap and scroll -// gestures. You can also use WidgetTester to find child widgets in the widget -// tree, read text, and verify that the values of widget properties are correct. - +import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/main.dart'; void main() { - testWidgets('Counter increments smoke test', (WidgetTester tester) async { - // Build our app and trigger a frame. - await tester.pumpWidget(const MyApp()); + for (final width in [390.0, 1000.0]) { + testWidgets( + 'Material shell adapts at width $width and supports large text', + (tester) async { + tester.view.physicalSize = Size(width, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + const MaterialApp( + home: MediaQuery( + data: MediaQueryData(textScaler: TextScaler.linear(2)), + child: AdaptiveShell(), + ), + ), + ); + expect(find.text('Pipelines'), findsWidgets); + expect(find.text('Pipelines — Not implemented'), findsOneWidget); + expect( + find.byType(NavigationBar), + width < 600 ? findsOneWidget : findsNothing, + ); + expect( + find.byType(NavigationRail), + width >= 600 ? findsOneWidget : findsNothing, + ); + await tester.tap(find.text('Runs').last); + await tester.pumpAndSettle(); + expect(find.text('Runs — Not implemented'), findsOneWidget); + }, + ); + } - // Verify that our counter starts at 0. - expect(find.text('0'), findsOneWidget); - expect(find.text('1'), findsNothing); + testWidgets('Cupertino shell uses native navigation controls', ( + tester, + ) async { + await tester.pumpWidget(const MyApp(cupertino: true)); + expect(find.byType(CupertinoNavigationBar), findsOneWidget); + expect(find.byType(CupertinoTabBar), findsOneWidget); + expect(find.text('Pipelines — Not implemented'), findsOneWidget); + }); - // Tap the '+' icon and trigger a frame. - await tester.tap(find.byIcon(Icons.add)); - await tester.pump(); - - // Verify that our counter has incremented. - expect(find.text('0'), findsNothing); - expect(find.text('1'), findsOneWidget); + testWidgets('destination content can be supplied by integration', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: AdaptiveShell( + destinationBodies: { + AppDestination.pipelines: (_) => + const Text('Injected pipelines screen'), + }, + ), + ), + ); + expect(find.text('Injected pipelines screen'), findsOneWidget); + expect(find.text('Pipelines — Not implemented'), findsNothing); }); } From c262f775015206f3e4bba6fc4ee896c09b0d9a24 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:24:11 +0100 Subject: [PATCH 03/84] feat(app): add Flutter websocket transport --- app/lib/core/transport/pipelines_client.dart | 183 ++++++++++++++++++ app/lib/core/transport/server_url.dart | 47 +++++ app/notes/F1.md | 13 ++ .../core/transport/pipelines_client_test.dart | 78 ++++++++ app/test/core/transport/server_url_test.dart | 23 +++ 5 files changed, 344 insertions(+) create mode 100644 app/lib/core/transport/pipelines_client.dart create mode 100644 app/lib/core/transport/server_url.dart create mode 100644 app/notes/F1.md create mode 100644 app/test/core/transport/pipelines_client_test.dart create mode 100644 app/test/core/transport/server_url_test.dart diff --git a/app/lib/core/transport/pipelines_client.dart b/app/lib/core/transport/pipelines_client.dart new file mode 100644 index 00000000..923b66f3 --- /dev/null +++ b/app/lib/core/transport/pipelines_client.dart @@ -0,0 +1,183 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:web_socket_channel/web_socket_channel.dart'; + +import '../api_gateway.dart'; +import 'server_url.dart'; + +enum ConnectionKind { idle, connecting, connected, disconnected } + +class ConnectionState { + const ConnectionState(this.kind, {this.attempt = 0, this.reason = '', this.retrying = false}); + final ConnectionKind kind; + final int attempt; + final String reason; + final bool retrying; +} + +class ProtocolError implements Exception { + const ProtocolError(this.message); + final String message; + @override + String toString() => message; +} + +class NotConnectedError implements Exception { + const NotConnectedError(); + @override + String toString() => 'Not connected to the Pipelines server'; +} + +typedef ChannelFactory = WebSocketChannel Function(Uri uri); + +/// One correlated websocket transport shared by all feature gateways. +class PipelinesClient implements ApiGateway { + PipelinesClient({ChannelFactory? channelFactory, + this.requestTimeout = const Duration(seconds: 30), + this.backoffBase = const Duration(seconds: 1), + this.backoffMax = const Duration(seconds: 30)}) : _factory = channelFactory ?? WebSocketChannel.connect; + + final ChannelFactory _factory; + final Duration requestTimeout, backoffBase, backoffMax; + final _frames = StreamController.broadcast(); + final _states = StreamController.broadcast(); + final Map> _pending = {}; + WebSocketChannel? _channel; + StreamSubscription? _subscription; + Uri? _endpoint; + Timer? _reconnect; + int _generation = 0, _sequence = 0, _attempt = 0; + bool _manual = true, _disposed = false; + ConnectionState _state = const ConnectionState(ConnectionKind.idle); + Future _queue = Future.value(); + + @override + Stream get frames => _frames.stream; + Stream get states => _states.stream; + ConnectionState get state => _state; + + Future connect(Uri uri) async { + if (_disposed) throw StateError('Client has been disposed'); + final endpoint = ServerUrl.validate(uri.toString()); + _endpoint = Uri.parse(endpoint.wsUrl); + _manual = false; + _attempt = 0; + _reconnect?.cancel(); + await _open(); + } + + Future _open() async { + final endpoint = _endpoint; + if (endpoint == null || _disposed) return; + final generation = ++_generation; + _setState(ConnectionState(ConnectionKind.connecting, attempt: ++_attempt)); + final old = _channel; + _channel = null; + await _subscription?.cancel(); + _failPending('Connection replaced'); + if (old != null) unawaited(old.sink.close()); + try { + final channel = _factory(endpoint); + _channel = channel; + _subscription = channel.stream.listen((data) { + if (generation == _generation) _onMessage(data); + }, onError: (Object error) { + if (generation == _generation) _closed(error.toString()); + }, onDone: () { + if (generation == _generation) _closed('Connection closed'); + }); + await channel.ready; + if (generation != _generation) return; + _attempt = 0; + _setState(const ConnectionState(ConnectionKind.connected)); + } catch (error) { + if (generation == _generation) _closed(error.toString()); + } + } + + void _setState(ConnectionState value) { _state = value; if (!_states.isClosed) _states.add(value); } + + @override + Future call(String type, [JsonMap fields = const {}]) { + final completer = Completer(); + final run = _queue.then((_) => _sendCall(type, fields, completer)); + _queue = run.catchError((_) {}); + return completer.future; + } + + Future _sendCall(String type, JsonMap fields, Completer result) async { + final channel = _channel; + if (channel == null || _state.kind != ConnectionKind.connected) { result.completeError(const NotConnectedError()); return; } + final id = 'flutter-${++_sequence}'; + _pending[id] = result; + final timer = Timer(requestTimeout, () { + if (_pending.remove(id) != null) result.completeError(TimeoutException('request timed out after ${requestTimeout.inMilliseconds}ms')); + }); + result.future.then((_) => timer.cancel(), onError: (Object error, StackTrace stack) => timer.cancel()); + try { + channel.sink.add(jsonEncode({...fields, 'type': type, 'id': id})); + } catch (error) { + timer.cancel(); + if (_pending.remove(id) != null) result.completeError(error); + } + } + + String sendOnly(String type, [JsonMap fields = const {}]) { + final channel = _channel; + if (channel == null || _state.kind != ConnectionKind.connected) throw const NotConnectedError(); + final id = 'flutter-${++_sequence}'; + channel.sink.add(jsonEncode({...fields, 'type': type, 'id': id})); + return id; + } + + void _onMessage(dynamic data) { + if (data is! String) return; + final Object? decoded; + try { decoded = jsonDecode(data); } on FormatException { return; } + if (decoded is! Map) return; + final message = decoded; + final id = message['id']; + final pending = id is String ? _pending.remove(id) : null; + if (pending != null) { + if (message['type'] == 'error') { + final reason = (message['error'] as String? ?? '').trim(); + pending.completeError(ProtocolError(reason.isEmpty ? 'server error' : reason)); + } else { + pending.complete(message); + } + } else if (!_frames.isClosed) { _frames.add(message); } + } + + void _failPending(String reason) { + final values = _pending.values.toList(); _pending.clear(); + for (final item in values) { if (!item.isCompleted) item.completeError(StateError(reason)); } + } + + void _closed(String reason) { + _generation++; + _channel = null; + _failPending(reason); + if (_manual || _disposed) { _setState(const ConnectionState(ConnectionKind.idle)); return; } + _setState(ConnectionState(ConnectionKind.disconnected, attempt: _attempt, reason: reason, retrying: true)); + final shift = (_attempt - 1).clamp(0, 6); + final delay = backoffBase * (1 << shift); + _reconnect?.cancel(); + _reconnect = Timer(delay > backoffMax ? backoffMax : delay, () => unawaited(_open())); + } + + Future disconnect() async { + _manual = true; _reconnect?.cancel(); _generation++; + final channel = _channel; _channel = null; + await _subscription?.cancel(); _subscription = null; + _failPending('Disconnected'); + if (channel != null) await channel.sink.close(); + _setState(const ConnectionState(ConnectionKind.idle)); + } + + Future dispose() async { + if (_disposed) return; + await disconnect(); _disposed = true; + await _frames.close(); await _states.close(); + } +} diff --git a/app/lib/core/transport/server_url.dart b/app/lib/core/transport/server_url.dart new file mode 100644 index 00000000..7f2eb59b --- /dev/null +++ b/app/lib/core/transport/server_url.dart @@ -0,0 +1,47 @@ +/// Validation result for a configured Pipelines websocket endpoint. +class ServerUrl { + const ServerUrl._({required this.wsUrl, required this.httpUrl, + required this.host, required this.port, required this.secure}); + + final String wsUrl; + final String httpUrl; + final String host; + final int port; + final bool secure; + + static ServerUrl validate(String raw) { + final value = raw.trim(); + if (value.isEmpty) throw const FormatException('Enter the Pipelines server URL, for example ws://192.168.1.20:8081/connect'); + final uri = Uri.tryParse(value); + if (uri == null || !uri.hasScheme) throw const FormatException('That is not a valid URL.'); + final scheme = uri.scheme.toLowerCase(); + if (scheme != 'ws' && scheme != 'wss') { + throw FormatException('Unsupported scheme "$scheme"; use ws:// (trusted LAN/VPN) or wss://'); + } + if (uri.userInfo.isNotEmpty) throw const FormatException('Credentials are not supported; the server has no authentication. Remove userinfo from the URL'); + if (uri.hasFragment) throw const FormatException('Remove the # fragment; it is not part of the server endpoint'); + if (uri.host.isEmpty) throw const FormatException('The URL is missing a host, for example ws://192.168.1.20:8081/connect'); + final secure = scheme == 'wss'; + final port = uri.hasPort ? uri.port : secure ? 443 : 80; + final path = uri.path.isEmpty || uri.path == '/' ? '/connect' : uri.path; + final authority = uri.hasPort ? '${uri.host}:$port' : uri.host; + final suffix = uri.hasQuery ? '?${uri.query}' : ''; + return ServerUrl._(wsUrl: '$scheme://$authority$path$suffix', + httpUrl: '${secure ? 'https' : 'http'}://$authority$path$suffix', + host: uri.host, port: port, secure: secure); + } + + static Uri? resolveArtifactUrl(String configured, String artifactUrl) { + final path = artifactUrl.trim(); + if (path.isEmpty) return null; + final parsed = Uri.tryParse(path); + if (parsed != null && (parsed.scheme == 'http' || parsed.scheme == 'https')) return parsed; + try { + final endpoint = validate(configured); + final portPart = endpoint.port != (endpoint.secure ? 443 : 80) ? ':${endpoint.port}' : ''; + return Uri.parse('${endpoint.secure ? 'https' : 'http'}://${endpoint.host}$portPart/${path.replaceFirst(RegExp(r'^/+'), '')}'); + } on FormatException { + return null; + } + } +} diff --git a/app/notes/F1.md b/app/notes/F1.md new file mode 100644 index 00000000..269e2685 --- /dev/null +++ b/app/notes/F1.md @@ -0,0 +1,13 @@ +# F1 transport + +`PipelinesClient` implements the shared `ApiGateway` contract using one +`web_socket_channel` connection, correlated JSON replies, timeout handling, +unsolicited envelope broadcast, and reconnect with capped exponential backoff. +The URL helper validates ws/wss endpoints and resolves artifact URLs. + +Manager integration import: `package:pipelines_app/core/transport/pipelines_client.dart`; +endpoint helper: `package:pipelines_app/core/transport/server_url.dart`. + +The client accepts an injected `ChannelFactory` for deterministic tests. No live +server was used. Browser and mobile target verification should be reported +separately from these unit tests. diff --git a/app/test/core/transport/pipelines_client_test.dart b/app/test/core/transport/pipelines_client_test.dart new file mode 100644 index 00000000..01840d05 --- /dev/null +++ b/app/test/core/transport/pipelines_client_test.dart @@ -0,0 +1,78 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; +import 'package:web_socket_channel/web_socket_channel.dart'; + +class FakeChannel implements WebSocketChannel { + final incoming = StreamController(); + final outgoing = []; + final readyCompleter = Completer(); + @override + Stream get stream => incoming.stream; + @override + WebSocketSink get sink => FakeSink(outgoing, incoming); + @override + Future get ready => readyCompleter.future; + @override + String? get protocol => null; + @override + int? get closeCode => null; + @override + String? get closeReason => null; + @override + noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +class FakeSink implements WebSocketSink { + FakeSink(this.outgoing, this.incoming); + final List outgoing; + final StreamController incoming; + @override + void add(dynamic event) => outgoing.add(event); + @override + void addError(Object error, [StackTrace? stackTrace]) => throw error; + @override + Future addStream(Stream stream) async { await for (final item in stream) { add(item); } } + @override + Future close([int? closeCode, String? closeReason]) async { await incoming.close(); } + @override + Future get done async {} + @override + noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +void main() { + test('correlates replies and broadcasts unclaimed frames', () async { + final channel = FakeChannel(); + final client = PipelinesClient(channelFactory: (_) => channel); + final frames = >[]; + client.frames.listen(frames.add); + final connecting = client.connect(Uri.parse('ws://example.test')); + channel.readyCompleter.complete(); + await connecting; + final request = client.call('ping', {'value': 1}); + await Future.delayed(Duration.zero); + final sent = jsonDecode(channel.outgoing.single as String) as Map; + channel.incoming.add(jsonEncode({'id': sent['id'], 'type': 'pong'})); + expect((await request)['type'], 'pong'); + channel.incoming.add(jsonEncode({'type': 'run_event'})); + await Future.delayed(Duration.zero); + expect(frames.single['type'], 'run_event'); + await client.dispose(); + }); + + test('disconnect fails pending requests', () async { + final channel = FakeChannel(); + final client = PipelinesClient(channelFactory: (_) => channel); + final connecting = client.connect(Uri.parse('ws://example.test')); + channel.readyCompleter.complete(); + await connecting; + final pending = client.call('ping'); + await Future.delayed(Duration.zero); + await client.disconnect(); + await expectLater(pending, throwsA(isA())); + await client.dispose(); + }); +} diff --git a/app/test/core/transport/server_url_test.dart b/app/test/core/transport/server_url_test.dart new file mode 100644 index 00000000..b7773d31 --- /dev/null +++ b/app/test/core/transport/server_url_test.dart @@ -0,0 +1,23 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/transport/server_url.dart'; + +void main() { + test('validates and normalizes endpoint with path and query', () { + final value = ServerUrl.validate(' wss://example.test:8443/?token=x '); + expect(value.wsUrl, 'wss://example.test:8443/connect?token=x'); + expect(value.httpUrl, 'https://example.test:8443/connect?token=x'); + expect(value.secure, isTrue); + }); + + test('rejects unsupported schemes and credentials', () { + expect(() => ServerUrl.validate('https://example.test'), throwsFormatException); + expect(() => ServerUrl.validate('ws://user:pass@example.test'), throwsFormatException); + }); + + test('resolves relative artifacts at the server origin', () { + expect(ServerUrl.resolveArtifactUrl('ws://example.test:8081/connect', '/artifacts/a')!.toString(), + 'http://example.test:8081/artifacts/a'); + expect(ServerUrl.resolveArtifactUrl('', '/artifacts/a'), isNull); + expect(ServerUrl.resolveArtifactUrl('', 'https://cdn.test/a')!.toString(), 'https://cdn.test/a'); + }); +} From 7cdb9e8338d00e747928c9938e61fe33f74a1204 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:24:49 +0100 Subject: [PATCH 04/84] feat(app): add chat foundation --- app/.gitignore | 3 + .../features/chat/data/chat_repository.dart | 146 ++++++++++ .../features/chat/domain/chat_sessions.dart | 64 +++++ .../features/chat/domain/chat_transcript.dart | 235 ++++++++++++++++ app/notes/F4.md | 17 ++ .../features/chat/chat_foundation_test.dart | 259 ++++++++++++++++++ 6 files changed, 724 insertions(+) create mode 100644 app/lib/features/chat/data/chat_repository.dart create mode 100644 app/lib/features/chat/domain/chat_sessions.dart create mode 100644 app/lib/features/chat/domain/chat_transcript.dart create mode 100644 app/notes/F4.md create mode 100644 app/test/features/chat/chat_foundation_test.dart diff --git a/app/.gitignore b/app/.gitignore index 3820a95c..e747ec42 100644 --- a/app/.gitignore +++ b/app/.gitignore @@ -43,3 +43,6 @@ app.*.map.json /android/app/debug /android/app/profile /android/app/release + +# Chat's source adapter lives in a directory commonly ignored as generated data. +!lib/features/chat/data/ diff --git a/app/lib/features/chat/data/chat_repository.dart b/app/lib/features/chat/data/chat_repository.dart new file mode 100644 index 00000000..8053ef5c --- /dev/null +++ b/app/lib/features/chat/data/chat_repository.dart @@ -0,0 +1,146 @@ +import '../../../core/api_gateway.dart'; + +/// Chat wire adapter. ApiGateway supplies request ids and returns full envelopes. +class ChatRepository { + ChatRepository(this.gateway); + final ApiGateway gateway; + + Future> sessions() async => + _maps((await gateway.call('chat_sessions'))['chat_sessions']); + Future> models(String sessionId) async => _maps( + (await gateway.call('chat_models', { + 'chat_query': {'session_id': sessionId}, + }))['chat_models'], + ); + Future selectModel( + String sessionId, + String provider, + String model, + ) => gateway.call('chat_model', { + 'chat_model': { + 'session_id': sessionId, + 'provider': provider, + 'model': model, + }, + }); + Future> shells(String sessionId) async => _maps( + (await gateway.call('chat_shells', { + 'chat_query': {'session_id': sessionId}, + }))['chat_shells'], + ); + Future> directories() async => + ((await gateway.call('chat_directories'))['chat_directories'] as List? ?? + const []) + .whereType() + .toList(); + + Future history( + String sessionId, { + int limit = 50, + String cursor = '', + }) async { + final reply = await gateway.call('chat_messages', { + 'chat_query': {'session_id': sessionId, 'limit': limit, 'cursor': cursor}, + }); + final page = reply['chat_history']; + if (page is Map) { + return { + 'messages': _maps(page['messages']), + 'nextCursor': '${page['next_cursor'] ?? ''}', + 'hasMore': page['has_more'] == true, + }; + } + return { + 'messages': _maps(reply['chat_messages']), + 'nextCursor': '', + 'hasMore': false, + }; + } + + Future subscribe(String sessionId) => + gateway.call('chat_subscribe', { + 'chat_subscribe': {'session_id': sessionId}, + }); + Future create({ + required String title, + required String directory, + required String operationId, + String backend = 'opencode', + String instructions = '', + }) => gateway.call('chat_create', { + 'chat_create': { + 'title': title, + 'directory': directory, + 'operation_id': operationId, + if (backend.isNotEmpty && backend != 'opencode') 'backend': backend, + if (instructions.trim().isNotEmpty) 'instructions': instructions.trim(), + }, + }); + Future rename(String sessionId, String title) => + gateway.call('chat_rename', { + 'chat_rename': {'session_id': sessionId, 'title': title.trim()}, + }); + Future star(String sessionId, bool starred) => + gateway.call('chat_star', { + 'chat_query': {'session_id': sessionId, 'starred': starred}, + }); + Future close(String sessionId) => gateway.call('chat_close', { + 'chat_query': {'session_id': sessionId}, + }); + Future reopen(String sessionId) => gateway.call('chat_reopen', { + 'chat_query': {'session_id': sessionId}, + }); + + Future prompt( + String sessionId, + String text, { + required String operationId, + List files = const [], + }) { + final body = { + 'session_id': sessionId, + 'text': text.trim(), + 'operation_id': operationId, + }; + if (files.isNotEmpty) body['files'] = files; + return gateway.call('chat_prompt', {'chat_prompt': body}); + } + + Future interrupt(String sessionId) => + gateway.call('chat_interrupt', { + 'chat_query': {'session_id': sessionId}, + }); + Future answerForm( + String sessionId, + String formId, + JsonMap answers, { + String action = '', + }) => gateway.call('chat_answer', { + 'chat_answer': { + 'session_id': sessionId, + 'form_id': formId, + 'answers': answers, + if (action.isNotEmpty) 'action': action, + }, + }); + Future replyPermission( + String sessionId, + String requestId, + String decision, { + String client = 'web', + String message = '', + }) => gateway.call('chat_reply', { + 'chat_reply': { + 'session_id': sessionId, + 'request_id': requestId, + 'decision': decision, + 'client': client, + if (message.trim().isNotEmpty) 'message': message.trim(), + }, + }); + + static List _maps(Object? value) => (value as List? ?? const []) + .whereType() + .map((item) => Map.from(item)) + .toList(); +} diff --git a/app/lib/features/chat/domain/chat_sessions.dart b/app/lib/features/chat/domain/chat_sessions.dart new file mode 100644 index 00000000..76bacdf6 --- /dev/null +++ b/app/lib/features/chat/domain/chat_sessions.dart @@ -0,0 +1,64 @@ +import '../../../core/api_gateway.dart'; + +/// Pure session-list operations. Unknown server fields remain on each row. +String chatSessionTitle(JsonMap session) { + final title = '${session['title'] ?? ''}'; + if (title.trim().isNotEmpty) return title; + final id = '${session['id'] ?? ''}'; + return id.isEmpty ? 'Untitled chat' : id.substring(0, id.length.clamp(0, 18)); +} + +List filterChatSessions(List sessions, String query) { + final needle = query.trim().toLowerCase(); + if (needle.isEmpty) return sessions; + return sessions + .where( + (session) => + '${chatSessionTitle(session)}\u0000${session['directory'] ?? ''}' + .toLowerCase() + .contains(needle), + ) + .toList(); +} + +/// Directory groups retain server recency order, both within and between groups. +List<({String directory, List sessions})> groupChatSessions( + List sessions, +) { + final groups = >{}; + for (final session in sessions) { + groups.putIfAbsent('${session['directory'] ?? ''}', () => []).add(session); + } + return groups.entries + .map((entry) => (directory: entry.key, sessions: entry.value)) + .toList(); +} + +String chatSessionActivity({required bool running, required bool unseen}) => + running + ? 'streaming' + : unseen + ? 'new' + : 'idle'; + +/// Native reported values only; missing and invalid values remain unavailable. +JsonMap? chatUsageSnapshot(Object? value) { + if (value is! Map || value is List) return null; + final usage = Map.from(value); + final result = {}; + for (final key in ['total_tokens', 'context_tokens', 'context_window']) { + final n = usage[key]; + result[key] = n is int && n >= 0 ? n : null; + } + for (final key in ['cost_usd', 'output_tokens_per_second']) { + final n = usage[key]; + result[key] = n is num && n.isFinite && n >= 0 ? n : null; + } + result['scope'] = ['session', 'turn'].contains(usage['scope']) + ? usage['scope'] + : ''; + result['rate_basis'] = ['generation', 'turn'].contains(usage['rate_basis']) + ? usage['rate_basis'] + : ''; + return result.values.any((v) => v != null && v != '') ? result : null; +} diff --git a/app/lib/features/chat/domain/chat_transcript.dart b/app/lib/features/chat/domain/chat_transcript.dart new file mode 100644 index 00000000..b766f15e --- /dev/null +++ b/app/lib/features/chat/domain/chat_transcript.dart @@ -0,0 +1,235 @@ +import '../../../core/api_gateway.dart'; + +/// Merge chronological history pages by message id. Incoming authoritative +/// copies replace held copies without changing their order; cursor is opaque. +JsonMap mergeChatHistory(JsonMap previous, JsonMap page, {bool older = false}) { + final held = (previous['messages'] as List? ?? const []) + .whereType() + .map((m) => Map.from(m)) + .toList(); + final incoming = (page['messages'] as List? ?? const []) + .whereType() + .map((m) => Map.from(m)) + .toList(); + final latest = {}; + for (final message in incoming) { + if (message['id'] != null) latest[message['id']] = message; + } + final combined = older ? [...incoming, ...held] : [...held, ...incoming]; + final seen = {}; + final messages = []; + for (final message in combined) { + final id = message['id']; + if (id != null && !seen.add(id)) continue; + messages.add(id == null ? message : latest[id] ?? message); + } + return { + 'messages': messages, + 'nextCursor': '${page['nextCursor'] ?? ''}', + 'hasMore': page['hasMore'] == true, + 'loaded': true, + 'loading': false, + }; +} + +/// Consecutive assistant messages form one answer turn. All part fields (also +/// future/unknown protocol types) are preserved in original order. +List transcriptRows(List messages) { + final rows = []; + String? key; + final parts = []; + void flush() { + if (key != null && parts.isNotEmpty) { + rows.add({ + 'kind': 'assistant', + 'key': key, + 'parts': List.of(parts), + }); + } + key = null; + parts.clear(); + } + + for (final message in messages) { + if (message['role'] == 'assistant') { + key ??= '${message['id'] ?? ''}'; + for (final part in (message['parts'] as List? ?? const [])) { + if (part is Map) parts.add(Map.from(part)); + } + } else { + flush(); + rows.add({'kind': 'user', 'key': message['id'], 'message': message}); + } + } + flush(); + return rows; +} + +/// Replace a local optimistic user row when its server echo identifies the +/// same operation/native message; otherwise append once by authoritative id. +List reconcileChatUser(List messages, JsonMap remote) { + final operation = remote['operation_id']; + final nativeId = remote['native_message_id']; + final id = remote['id']; + final index = messages.indexWhere( + (message) => + (operation != null && message['operation_id'] == operation) || + (nativeId != null && message['native_message_id'] == nativeId) || + (id != null && message['id'] == id), + ); + if (index < 0) return [...messages, remote]; + final result = List.of(messages); + result[index] = remote; + return result; +} + +/// Fold a live chat frame into an immutable thread snapshot. Text and reasoning +/// deltas append by part id, tool snapshots merge without dropping prior fields, +/// and step frames update turn activity. Frames for another session are ignored. +JsonMap applyChatEvent(JsonMap thread, JsonMap frame) { + final session = thread['sessionId']; + if (session != null && + frame['session_id'] != null && + session != frame['session_id']) { + return thread; + } + final messages = (thread['messages'] as List? ?? const []) + .whereType() + .map((m) => Map.from(m)) + .toList(); + final kind = frame['kind']; + if (kind == 'user') { + final part = frame['part']; + final text = part is Map ? part['text'] : null; + final id = frame['message_id']; + if (text is! String || + text.isEmpty || + id == null || + messages.any( + (m) => + m['id'] == id || + (frame['operation_id'] != null && + m['operation_id'] == frame['operation_id']), + )) { + return thread; + } + messages.add({ + 'id': id, + 'session_id': frame['session_id'], + 'role': 'user', + 'client': frame['client'], + 'operation_id': frame['operation_id'], + 'parts': [ + {'type': 'text', 'text': text}, + ...(frame['attachments'] is List + ? frame['attachments'] as List + : const []), + ], + }); + return {...thread, 'messages': messages}; + } + if (kind == 'text' || kind == 'reasoning' || kind == 'tool') { + final incoming = frame['part']; + if (incoming is! Map || incoming['id'] == null) return thread; + final messageId = frame['message_id']; + var index = messages.indexWhere( + (m) => m['id'] == messageId && m['role'] == 'assistant', + ); + if (index < 0) { + messages.add({ + 'id': messageId, + 'session_id': frame['session_id'], + 'role': 'assistant', + 'parts': [], + }); + index = messages.length - 1; + } + final message = messages[index]; + final parts = (message['parts'] as List? ?? const []) + .whereType() + .map((p) => Map.from(p)) + .toList(); + final partIndex = parts.indexWhere( + (p) => p['id'] == incoming['id'] && p['type'] == kind, + ); + if (kind == 'text' || kind == 'reasoning') { + final delta = frame['delta']; + if (delta is! String || delta.isEmpty) return thread; + if (partIndex < 0) { + parts.add({'type': kind, 'id': incoming['id'], 'text': delta}); + } else { + parts[partIndex] = { + ...parts[partIndex], + 'text': '${parts[partIndex]['text'] ?? ''}$delta', + }; + } + } else if (partIndex < 0) { + parts.add(Map.from(incoming)); + } else { + final merged = { + ...parts[partIndex], + ...Map.from(incoming), + }; + if (parts[partIndex]['state'] is Map && incoming['state'] is Map) { + merged['state'] = { + ...Map.from(parts[partIndex]['state'] as Map), + ...Map.from(incoming['state'] as Map), + }; + } + parts[partIndex] = merged; + } + messages[index] = {...message, 'parts': parts}; + return {...thread, 'messages': messages, 'running': true}; + } + if (kind == 'step' && frame['step'] is Map) { + final step = frame['step'] as Map; + if (step['intermediate'] == true) return thread; + return { + ...thread, + 'running': step['status'] != 'ended', + 'nativeTurnId': step['status'] == 'ended' + ? '' + : (step['turn_id'] ?? thread['nativeTurnId'] ?? ''), + }; + } + return thread; +} + +/// Queue serialized sends per session; operation ids survive retries/replays. +class QueuedChatSend { + QueuedChatSend({ + required this.operationId, + required this.text, + this.files = const [], + }); + final String operationId; + final String text; + final List files; + + /// Retry the same immutable intent with the same idempotency key. + QueuedChatSend retry() => QueuedChatSend( + operationId: operationId, + text: text, + files: List.unmodifiable(files), + ); +} + +class ChatSendQueue { + final Map> _sessions = {}; + List forSession(String sessionId) => + List.unmodifiable(_sessions[sessionId] ?? const []); + bool enqueue(String sessionId, QueuedChatSend send) { + final queue = _sessions.putIfAbsent(sessionId, () => []); + if (queue.any((item) => item.operationId == send.operationId)) return false; + queue.add(send); + return true; + } + + QueuedChatSend? takeNext(String sessionId) { + final queue = _sessions[sessionId]; + if (queue == null || queue.isEmpty) return null; + final result = queue.removeAt(0); + if (queue.isEmpty) _sessions.remove(sessionId); + return result; + } +} diff --git a/app/notes/F4.md b/app/notes/F4.md new file mode 100644 index 00000000..a2578786 --- /dev/null +++ b/app/notes/F4.md @@ -0,0 +1,17 @@ +# F4 chat foundation + +Non-visual chat foundations for the UI lane, using the shared `ApiGateway` and no socket ownership. + +## Imports and API + +- `package:pipelines_app/features/chat/domain/chat_sessions.dart`: `chatSessionTitle`, `filterChatSessions`, `groupChatSessions`, `chatSessionActivity`, and `chatUsageSnapshot`. +- `package:pipelines_app/features/chat/domain/chat_transcript.dart`: `mergeChatHistory`, `transcriptRows`, `reconcileChatUser`, `applyChatEvent`, `QueuedChatSend`, and `ChatSendQueue`. +- `package:pipelines_app/features/chat/data/chat_repository.dart`: `ChatRepository(gateway)`; exposes sessions, directories, history, subscribe, create/rename/star/close/reopen, prompt/interrupt, form answer, permission reply, models/shells and model selection. `gateway.frames` remains the UI/controller's unsolicited event source. + +History uses `chat_history.next_cursor` verbatim, falls back to legacy `chat_messages`, and replaces duplicate authoritative messages while preserving order. `transcriptRows` preserves unknown part maps. Live fold supports user echoes, text/reasoning deltas, tool state snapshots, and step activity; UI should retain its richer thread/timing state as needed. Queue operation IDs are stable across retry objects and deduplicated within each session. Usage values remain unavailable unless reported and valid. + +Wire envelopes are asserted in `test/features/chat/chat_foundation_test.dart`. Current backend has no `chat_forms` or `chat_permissions` list command; forms and permissions arrive as live events and are answered through `chat_answer` / `chat_reply`. + +## Verification + +`/Users/alan/development/flutter/bin/flutter test test/features/chat` passed. Nonvisual foundation: UI/browser review and captures are not applicable at this stage. Web is the only permitted target; Android/iOS remain unverified. diff --git a/app/test/features/chat/chat_foundation_test.dart b/app/test/features/chat/chat_foundation_test.dart new file mode 100644 index 00000000..76e74353 --- /dev/null +++ b/app/test/features/chat/chat_foundation_test.dart @@ -0,0 +1,259 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/data/chat_repository.dart'; +import 'package:pipelines_app/features/chat/domain/chat_sessions.dart'; +import 'package:pipelines_app/features/chat/domain/chat_transcript.dart'; + +class RecordingGateway implements ApiGateway { + final calls = <({String type, JsonMap fields})>[]; + JsonMap reply = {}; + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add((type: type, fields: fields)); + return reply; + } + + @override + Stream get frames => const Stream.empty(); +} + +void main() { + group('chat domain', () { + test( + 'filters/groups in server order and keeps server usage unknowns unavailable', + () { + final sessions = [ + {'id': 'a', 'directory': '/work', 'title': 'First'}, + {'id': 'b', 'directory': '/else', 'title': 'Second'}, + {'id': 'c', 'directory': '/work', 'title': 'Third'}, + ]; + expect(filterChatSessions(sessions, 'ELSE').single['id'], 'b'); + expect(groupChatSessions(sessions).map((g) => g.directory), [ + '/work', + '/else', + ]); + expect(chatSessionActivity(running: true, unseen: true), 'streaming'); + expect( + chatUsageSnapshot({ + 'total_tokens': 3, + 'context_window': 'unknown', + })!['context_window'], + isNull, + ); + expect(chatUsageSnapshot({'legacy_tokens': 9}), isNull); + }, + ); + + test( + 'merges pages by id, retains idless events, replaces authority, and folds parts', + () { + final first = mergeChatHistory({}, { + 'messages': [ + { + 'id': 'a', + 'role': 'assistant', + 'parts': [ + {'type': 'reasoning', 'text': 'think'}, + ], + }, + { + 'role': 'assistant', + 'parts': [ + {'type': 'future_part', 'payload': 4}, + ], + }, + {'id': 'u', 'role': 'user', 'text': 'hello', 'operation_id': 'op'}, + ], + 'nextCursor': 'opaque/1', + 'hasMore': true, + }); + final older = mergeChatHistory(first, { + 'messages': [ + { + 'id': 'a', + 'role': 'assistant', + 'parts': [ + {'type': 'text', 'text': 'final'}, + ], + }, + ], + 'nextCursor': '', + 'hasMore': false, + }, older: true); + expect(older['nextCursor'], ''); + final msgs = older['messages'] as List; + expect(msgs.map((m) => m['id']), ['a', null, 'u']); + expect( + (transcriptRows(msgs).first['parts'] as List).map((p) => p['type']), + ['text', 'future_part'], + ); + expect( + reconcileChatUser(msgs, { + 'id': 'remote', + 'role': 'user', + 'operation_id': 'op', + }).where((m) => m['operation_id'] == 'op').length, + 1, + ); + }, + ); + + test( + 'send queue is session-scoped and operation IDs deduplicate retries', + () { + final queue = ChatSendQueue(); + final send = QueuedChatSend( + operationId: 'stable', + text: ' prompt ', + files: ['/tmp/a'], + ); + expect(queue.enqueue('s1', send), isTrue); + expect(queue.enqueue('s1', send.retry()), isFalse); + expect(queue.enqueue('s2', send.retry()), isTrue); + expect(queue.takeNext('s1')!.operationId, 'stable'); + expect(queue.takeNext('s1'), isNull); + expect(queue.forSession('s2').single.files, ['/tmp/a']); + }, + ); + + test( + 'live text/reasoning append, tool snapshots merge, and steps settle only activity', + () { + var thread = { + 'sessionId': 's', + 'messages': [], + }; + thread = applyChatEvent(thread, { + 'kind': 'text', + 'session_id': 's', + 'message_id': 'a', + 'part': {'id': 'p'}, + 'delta': 'one', + }); + thread = applyChatEvent(thread, { + 'kind': 'text', + 'session_id': 's', + 'message_id': 'a', + 'part': {'id': 'p'}, + 'delta': ' two', + }); + thread = applyChatEvent(thread, { + 'kind': 'reasoning', + 'session_id': 's', + 'message_id': 'a', + 'part': {'id': 'r'}, + 'delta': 'hidden', + }); + thread = applyChatEvent(thread, { + 'kind': 'tool', + 'session_id': 's', + 'message_id': 'a', + 'part': { + 'id': 't', + 'type': 'tool', + 'state': {'input': 'x'}, + }, + }); + thread = applyChatEvent(thread, { + 'kind': 'tool', + 'session_id': 's', + 'message_id': 'a', + 'part': { + 'id': 't', + 'type': 'tool', + 'state': {'status': 'completed'}, + }, + }); + final parts = + ((thread['messages'] as List).single as JsonMap)['parts'] + as List; + expect(parts[0]['text'], 'one two'); + expect(parts[1]['text'], 'hidden'); + expect(parts[2]['state'], {'input': 'x', 'status': 'completed'}); + expect(thread['running'], true); + thread = applyChatEvent(thread, { + 'kind': 'step', + 'session_id': 's', + 'step': {'status': 'ended', 'turn_id': 'turn'}, + }); + expect(thread['running'], false); + expect( + applyChatEvent(thread, {'kind': 'text', 'session_id': 'other'}), + same(thread), + ); + }, + ); + }); + + group('chat wire adapter', () { + late RecordingGateway gateway; + late ChatRepository repo; + setUp(() { + gateway = RecordingGateway(); + repo = ChatRepository(gateway); + }); + test('uses web envelopes and opaque history cursor', () async { + gateway.reply = { + 'chat_history': { + 'messages': [ + {'id': 'm', 'role': 'user'}, + ], + 'next_cursor': 'opaque', + 'has_more': true, + }, + }; + final page = await repo.history('s', cursor: 'before', limit: 17); + expect(page['nextCursor'], 'opaque'); + expect(gateway.calls.last.type, 'chat_messages'); + expect(gateway.calls.last.fields, { + 'chat_query': {'session_id': 's', 'cursor': 'before', 'limit': 17}, + }); + await repo.subscribe('s'); + expect(gateway.calls.last.fields, { + 'chat_subscribe': {'session_id': 's'}, + }); + }); + test( + 'sends stable operation id, omits empty files, and builds action envelopes', + () async { + await repo.prompt('s', ' hi ', operationId: 'same'); + expect(gateway.calls.last.fields, { + 'chat_prompt': { + 'session_id': 's', + 'text': 'hi', + 'operation_id': 'same', + }, + }); + await repo.answerForm('s', 'f', {'choice': 'yes'}, action: 'submit'); + expect(gateway.calls.last.fields, { + 'chat_answer': { + 'session_id': 's', + 'form_id': 'f', + 'answers': {'choice': 'yes'}, + 'action': 'submit', + }, + }); + await repo.replyPermission('s', 'r', 'once', message: ' approved '); + expect(gateway.calls.last.fields, { + 'chat_reply': { + 'session_id': 's', + 'request_id': 'r', + 'decision': 'once', + 'client': 'web', + 'message': 'approved', + }, + }); + await repo.create(title: 'New', directory: '~', operationId: 'create'); + expect(gateway.calls.last.fields, { + 'chat_create': { + 'title': 'New', + 'directory': '~', + 'operation_id': 'create', + }, + }); + await repo.selectModel('s', 'provider', 'model'); + expect(gateway.calls.last.type, 'chat_model'); + }, + ); + }); +} From e3a82b0b366cc02c24fef04ef28c6c24b75a0e9d Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:25:09 +0100 Subject: [PATCH 05/84] feat(app): add guarded web preview server --- app/test/tool/preview.test.mjs | 48 ++++++++++++++++++++++++ app/tool/preview/README.md | 14 +++++++ app/tool/preview/server.mjs | 68 ++++++++++++++++++++++++++++++++++ 3 files changed, 130 insertions(+) create mode 100644 app/test/tool/preview.test.mjs create mode 100644 app/tool/preview/README.md create mode 100644 app/tool/preview/server.mjs diff --git a/app/test/tool/preview.test.mjs b/app/test/tool/preview.test.mjs new file mode 100644 index 00000000..68b70c36 --- /dev/null +++ b/app/test/tool/preview.test.mjs @@ -0,0 +1,48 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, mkdir, writeFile, symlink, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { createServer } from 'node:http'; +import { start } from '../../tool/preview/server.mjs'; + +test('serves guarded assets, deep links, MIME and missing assets; forwards auth routes and artifacts', async t => { + const dir=await mkdtemp(join(tmpdir(),'preview-')); await mkdir(join(dir,'assets')); await writeFile(join(dir,'index.html'),'shell'); await writeFile(join(dir,'assets/a.wasm'),'wasm'); + const upstream=createServer((req,res)=>{ if(req.url==='/') {res.writeHead(req.headers.cookie==='sid=yes'?200:302,{location:'/login'}).end();return} res.writeHead(200,{'x-forwarded':req.url}).end(req.url) }); + await new Promise(ok=>upstream.listen(0,'127.0.0.1',ok)); + const preview=await start({root:dir,upstream:`http://127.0.0.1:${upstream.address().port}`,port:0}); t.after(async()=>{await preview.close();upstream.close();await rm(dir,{recursive:true,force:true})}); + const base=`http://127.0.0.1:${preview.port}`; + assert.equal((await fetch(base+'/assets/a.wasm')).status,401); + const headers={cookie:'sid=yes'}; + const wasm=await fetch(base+'/assets/a.wasm',{headers}); assert.equal(wasm.headers.get('content-type'),'application/wasm'); assert.equal(wasm.headers.get('cache-control'),'no-store'); + assert.equal(await (await fetch(base+'/runs/4',{headers})).text(),'shell'); + assert.equal((await fetch(base+'/assets/missing.js',{headers})).status,404); + assert.equal((await fetch(base+'/..%2f..%2fetc/passwd',{headers})).status,403); + assert.equal((await fetch(base+'/artifacts/1/a',{headers})).status,200); + assert.equal((await fetch(base+'/login')).status,200); +}); + +test('rejects a directory index symlink that escapes the preview root', async t => { + const dir=await mkdtemp(join(tmpdir(),'preview-')), outside=await mkdtemp(join(tmpdir(),'preview-out-')); + await mkdir(join(dir,'linked')); await writeFile(join(outside,'secret.html'),'secret'); + await symlink(join(outside,'secret.html'),join(dir,'linked','index.html')); + const upstream=createServer((req,res)=>res.end('ok')); + await new Promise(ok=>upstream.listen(0,'127.0.0.1',ok)); + const preview=await start({root:dir,upstream:`http://127.0.0.1:${upstream.address().port}`,port:0}); + t.after(async()=>{await preview.close();upstream.close();await rm(dir,{recursive:true,force:true});await rm(outside,{recursive:true,force:true})}); + const response=await fetch(`http://127.0.0.1:${preview.port}/linked/`,{headers:{cookie:'sid=yes'}}); + assert.equal(response.status,403); +}); + +test('rejects an SPA fallback index symlink that escapes the preview root', async t => { + const dir=await mkdtemp(join(tmpdir(),'preview-')), outside=await mkdtemp(join(tmpdir(),'preview-out-')); + await writeFile(join(outside,'secret.html'),'secret'); + await symlink(join(outside,'secret.html'),join(dir,'index.html')); + const upstream=createServer((req,res)=>res.end('ok')); + await new Promise(ok=>upstream.listen(0,'127.0.0.1',ok)); + const preview=await start({root:dir,upstream:`http://127.0.0.1:${upstream.address().port}`,port:0}); + t.after(async()=>{await preview.close();upstream.close();await rm(dir,{recursive:true,force:true});await rm(outside,{recursive:true,force:true})}); + const response=await fetch(`http://127.0.0.1:${preview.port}/missing-route`,{headers:{cookie:'sid=yes'}}); + assert.equal(response.status,403); + assert.notEqual(await response.text(),'secret'); +}); diff --git a/app/tool/preview/README.md b/app/tool/preview/README.md new file mode 100644 index 00000000..2d62a8f5 --- /dev/null +++ b/app/tool/preview/README.md @@ -0,0 +1,14 @@ +# Flutter web preview + +Build and run from `app/`: + +```sh +/Users/alan/development/flutter/bin/flutter build web +UPSTREAM=http://127.0.0.1:8095 node tool/preview/server.mjs --port 8080 +``` + +The preview binds to loopback by default and authenticates static requests by +checking the upstream authenticated web proxy with the browser cookie. Login, +logout and artifacts are forwarded to that proxy; `/connect` is forwarded only +for same-origin websocket upgrades. Set `UPSTREAM` to the authenticated proxy, +never the raw control server. Tests use isolated local fixtures and port 0. diff --git a/app/tool/preview/server.mjs b/app/tool/preview/server.mjs new file mode 100644 index 00000000..bd203128 --- /dev/null +++ b/app/tool/preview/server.mjs @@ -0,0 +1,68 @@ +import { createServer } from 'node:http'; +import { realpath, stat } from 'node:fs/promises'; +import { extname, resolve, sep } from 'node:path'; +import net from 'node:net'; +import tls from 'node:tls'; + +const mime = { '.html':'text/html; charset=utf-8', '.js':'text/javascript; charset=utf-8', '.mjs':'text/javascript; charset=utf-8', '.wasm':'application/wasm', '.woff':'font/woff', '.woff2':'font/woff2', '.ttf':'font/ttf', '.json':'application/json', '.css':'text/css; charset=utf-8', '.png':'image/png', '.svg':'image/svg+xml' }; +const noCache = { 'Cache-Control':'no-store' }; +const response = (res, status, body='') => { if (!res.headersSent) res.writeHead(status, { ...noCache, 'Content-Type':'text/plain; charset=utf-8' }); res.end(body); }; + +export async function start({ root=resolve('build/web'), upstream='http://127.0.0.1:8095', host='127.0.0.1', port=8080 }={}) { + const base = await realpath(root), target = new URL(upstream); + if (!['http:','https:'].includes(target.protocol)) throw new Error('UPSTREAM must be HTTP(S)'); + const server = createServer(async (req,res) => { + let pathname; + try { pathname = decodeURIComponent(new URL(req.url, 'http://preview').pathname); } catch { return response(res,400); } + if (!['GET','HEAD','POST'].includes(req.method)) { res.setHeader('Allow','GET, HEAD, POST'); return response(res,405); } + if (pathname === '/login' || pathname === '/logout' || pathname.startsWith('/artifacts/')) return proxy(req,res,target); + try { + const check = await fetch(new URL('/', target), { headers: { cookie:req.headers.cookie ?? '', accept:'text/html' }, redirect:'manual' }); + if (!check.ok || check.status >= 300) return response(res, check.status === 401 || check.status === 302 ? 401 : 502, 'Authentication required'); + } catch { return response(res,502,'Authentication upstream unavailable'); } + if (req.method !== 'GET' && req.method !== 'HEAD') return response(res,405); + let file = resolve(base, `.${pathname}`); + if (file !== base && !file.startsWith(base + sep)) return response(res,403); + try { + let real = await realpath(file); + if (real !== base && !real.startsWith(base + sep)) return response(res,403); + if ((await stat(real)).isDirectory()) { + real = await realpath(resolve(real,'index.html')); + if (real !== base && !real.startsWith(base + sep)) return response(res,403); + } + file = real; + const body = await (await import('node:fs/promises')).readFile(file); + res.writeHead(200,{...noCache,'Content-Type':mime[extname(file)] ?? 'application/octet-stream'}); res.end(req.method==='HEAD' ? undefined : body); + } catch (e) { + if (e.code !== 'ENOENT' && e.code !== 'ENOTDIR') return response(res,403); + if (extname(pathname)) return response(res,404,'Not found'); + try { + const fallback=await realpath(resolve(base,'index.html')); + if (fallback !== base && !fallback.startsWith(base + sep)) return response(res,403); + const body=await (await import('node:fs/promises')).readFile(fallback); + res.writeHead(200,{...noCache,'Content-Type':mime['.html']}); res.end(body); + } catch { response(res,404,'Not found'); } + } + }); + server.on('upgrade', (req,socket,head) => { + try { + const hostHeader=req.headers.host, origin=new URL(req.headers.origin); + if (req.url.split('?')[0] !== '/connect' || !hostHeader || origin.host.toLowerCase() !== hostHeader.toLowerCase() || !['http:','https:'].includes(origin.protocol)) return reject(socket,403); + const connect=target.protocol==='https:' ? tls.connect : net.connect; + const u=connect(Number(target.port || (target.protocol==='https:'?443:80)),target.hostname,()=>{ + const headers={...req.headers,host:target.host}; delete headers.origin; + u.write(`GET ${req.url} HTTP/1.1\r\n${Object.entries(headers).map(([k,v])=>`${k}: ${v}`).join('\r\n')}\r\n\r\n`); if(head.length)u.write(head); u.pipe(socket); socket.pipe(u); + }); u.on('error',()=>socket.destroy()); socket.on('error',()=>u.destroy()); + } catch { reject(socket,403); } + }); + await new Promise((ok,fail)=>{server.once('error',fail);server.listen(port,host,ok)}); + return { server, port:server.address().port, close:()=>new Promise((ok,fail)=>server.close(e=>e?fail(e):ok())) }; +} +function reject(socket,status){socket.end(`HTTP/1.1 ${status} Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`)} +function proxy(req,res,target){ + const url=new URL(req.url,target); fetch(url,{method:req.method,headers:{cookie:req.headers.cookie??'',...(req.headers['content-type']?{'content-type':req.headers['content-type']}:{})},body:['GET','HEAD'].includes(req.method)?undefined:req,duplex:'half',redirect:'manual'}).then(async r=>{res.writeHead(r.status,{...Object.fromEntries(r.headers),...noCache});res.end(Buffer.from(await r.arrayBuffer()))}).catch(()=>response(res,502,'Upstream unavailable')); +} +if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) { + const args=Object.fromEntries(process.argv.slice(2).reduce((a,v,i,x)=>{if(v.startsWith('--'))a.push([v.slice(2),x[i+1]]);return a},[])); + start({root:args.root??'build/web',upstream:process.env.UPSTREAM??args.upstream??'http://127.0.0.1:8095',host:args.host??'127.0.0.1',port:Number(args.port??8080)}).then(s=>console.log(`preview http://${args.host??'127.0.0.1'}:${s.port}`)).catch(e=>{console.error(e);process.exitCode=1}); +} From fed90ea35eba3ac55321b27b6d616c92d3357f55 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:28:28 +0100 Subject: [PATCH 06/84] docs(app): track candidate verification and next feature runs --- app/WORK.md | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/app/WORK.md b/app/WORK.md index 300c7588..69b2057a 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -7,11 +7,13 @@ All work under app/. Existing applications remain running and unchanged. | Item | Scope | Source | Verification | Landing | Preview | | --- | --- | --- | --- | --- | --- | | F0 | Scaffold and gateway contract | 0e0ef54 | analyze + 1 scaffold test pass | main | not served | -| F1 | Socket transport, endpoint rules, reconnect | run 29 / flutter/f1-transport | running | pending | — | -| F2 | Adaptive shell and standard platform controls | run 31 / flutter/f2-shell | running | pending | pending | -| F3 | Run models, live event fold, actions | run 32 / flutter/f3-runs | running | pending | — | -| F4 | Chat models, history/live fold, request facade | run 33 / flutter/f4-chat | running | pending | — | -| F5 | Isolated authenticated web preview tooling | run 30 / flutter/f5-preview | running | pending | pending | +| F1 | Socket transport, endpoint rules, reconnect | run 29 / flutter/f1-transport | pipeline passed; manager expanded to 12 regressions and corrected races | pending | — | +| F2 | Adaptive shell and standard platform controls | run 31 / flutter/f2-shell | pipeline passed; manager completing real browser evidence and native-default corrections | pending | pending | +| F3 | Run models, live event fold, actions | run 32 / flutter/f3-runs | pipeline passed; manager correcting ignored source and parity gaps | pending | — | +| F4 | Chat models, history/live fold, request facade | run 33 / flutter/f4-chat | pipeline passed; wire omissions carried into C1 | pending C1 adapter fixes | — | +| F5 | Isolated authenticated web preview tooling | run 30 / flutter/f5-preview | pipeline passed; manager checking actual websocket/auth/byte forwarding | pending | pending | +| P1 | Pipeline list/detail/source/version browser | run 34 / flutter/p1-pipelines | running (DeepSeek V4.1 Flash) | pending | pending | +| C1 | Chat session browser and management | run 35 / flutter/f4-chat | running (Luna), includes adapter prerequisites | pending | pending | ## Next ready work - P1 pipelines list/detail/source/version; P2 graph and stage/visit selection. @@ -43,6 +45,18 @@ workspace/write scope, so could not correct this admission mistake. No policy override, server edit or shell-write bypass was used by the manager. Allowed pipeline models: Luna or DeepSeek V4.1 Flash; current runs use Luna. +### Manager integration findings +- F3 candidate omitted `lib/features/runs/data/runs_repository.dart`: root + runtime-data ignore matched source. Main 718442d adds an app-only exception; + candidate branch has it merged. Source is preserved, awaiting corrective + commit and expanded lifecycle/decision regression tests before landing. +- F2 UIReview was auto-skipped despite rendered shell changes (existing server + classifies workspace-relative lib/ paths as nonvisual). Do not change server; + manager obtains browser evidence directly and keeps rendered acceptance open. +- Direct Luna correction agents are scoped to the idle F2/F3 worktrees. No + recovery workflow or pipeline version was created. P1 is independent and + already started while corrections proceed. + ## Completion loop Use pipelines wait for every started run. Inspect failure evidence before fixing, resuming or retrying; preserve partial work. On success inspect actual diff and From 830726fa1914493c801cda8f1fd51f2837ee2271 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:28:50 +0100 Subject: [PATCH 07/84] fix Flutter shell platform defaults and tab state --- app/lib/main.dart | 11 +--- app/lib/shell/adaptive_shell.dart | 49 ++++++++++------- app/lib/shell/destination.dart | 38 ++++++++----- app/notes/F2.md | 7 ++- app/test/widget_test.dart | 35 ++++++++++++ app/tool/shell_probe.mjs | 88 +++++++++++++++++++++++++++++++ 6 files changed, 185 insertions(+), 43 deletions(-) create mode 100644 app/tool/shell_probe.mjs diff --git a/app/lib/main.dart b/app/lib/main.dart index 0c08d900..53ef59d8 100644 --- a/app/lib/main.dart +++ b/app/lib/main.dart @@ -31,15 +31,8 @@ class MyApp extends StatelessWidget { } return MaterialApp( title: 'Pipelines', - theme: ThemeData( - colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue), - ), - darkTheme: ThemeData( - colorScheme: ColorScheme.fromSeed( - seedColor: Colors.blue, - brightness: Brightness.dark, - ), - ), + theme: ThemeData(), + darkTheme: ThemeData(brightness: Brightness.dark), themeMode: ThemeMode.system, home: AdaptiveShell(destinationBodies: destinationBodies), ); diff --git a/app/lib/shell/adaptive_shell.dart b/app/lib/shell/adaptive_shell.dart index 6964f4b0..0def351a 100644 --- a/app/lib/shell/adaptive_shell.dart +++ b/app/lib/shell/adaptive_shell.dart @@ -30,30 +30,38 @@ class _AdaptiveShellState extends State { Widget build(BuildContext context) { final index = AppDestination.values.indexOf(_selected); final details = destinationDetails(_selected); - final content = - widget.destinationBodies[_selected]?.call(context) ?? - Center(child: Text('${details.label} — Not implemented')); + final contents = AppDestination.values.map((destination) { + final item = destinationDetails(destination); + return KeyedSubtree( + key: ValueKey(destination), + child: + widget.destinationBodies[destination]?.call(context) ?? + Center(child: Text('${item.label} — Not implemented')), + ); + }).toList(); return LayoutBuilder( builder: (context, constraints) { final wide = constraints.maxWidth >= 600; if (widget.cupertino) { return CupertinoPageScaffold( navigationBar: CupertinoNavigationBar(middle: Text(details.label)), - child: Column( - children: [ - Expanded(child: content), - CupertinoTabBar( - currentIndex: index, - onTap: (value) => _select(AppDestination.values[value]), - items: _items((destination) { - final item = destinationDetails(destination); - return BottomNavigationBarItem( - icon: Icon(item.icon), - label: item.label, - ); - }), - ), - ], + child: SafeArea( + child: Column( + children: [ + Expanded(child: _destinationStack(contents, index)), + CupertinoTabBar( + currentIndex: index, + onTap: (value) => _select(AppDestination.values[value]), + items: _items((destination) { + final item = destinationDetails(destination); + return BottomNavigationBarItem( + icon: Icon(item.cupertinoIcon), + label: item.label, + ); + }), + ), + ], + ), ), ); } @@ -75,7 +83,7 @@ class _AdaptiveShellState extends State { ); }), ), - Expanded(child: content), + Expanded(child: _destinationStack(contents, index)), ], ), bottomNavigationBar: wide @@ -96,4 +104,7 @@ class _AdaptiveShellState extends State { }, ); } + + Widget _destinationStack(List contents, int index) => + IndexedStack(index: index, children: contents); } diff --git a/app/lib/shell/destination.dart b/app/lib/shell/destination.dart index e8d0c373..932bc92c 100644 --- a/app/lib/shell/destination.dart +++ b/app/lib/shell/destination.dart @@ -1,17 +1,29 @@ import 'package:flutter/material.dart'; +import 'package:flutter/cupertino.dart'; enum AppDestination { pipelines, runs, chat, settings } -({String label, IconData icon}) destinationDetails(AppDestination value) => - switch (value) { - AppDestination.pipelines => ( - label: 'Pipelines', - icon: Icons.account_tree_outlined, - ), - AppDestination.runs => (label: 'Runs', icon: Icons.play_circle_outline), - AppDestination.chat => (label: 'Chat', icon: Icons.chat_bubble_outline), - AppDestination.settings => ( - label: 'Settings', - icon: Icons.settings_outlined, - ), - }; +({String label, IconData icon, IconData cupertinoIcon}) destinationDetails( + AppDestination value, +) => switch (value) { + AppDestination.pipelines => ( + label: 'Pipelines', + icon: Icons.account_tree_outlined, + cupertinoIcon: CupertinoIcons.arrow_branch, + ), + AppDestination.runs => ( + label: 'Runs', + icon: Icons.play_circle_outline, + cupertinoIcon: CupertinoIcons.play_circle, + ), + AppDestination.chat => ( + label: 'Chat', + icon: Icons.chat_bubble_outline, + cupertinoIcon: CupertinoIcons.chat_bubble_2, + ), + AppDestination.settings => ( + label: 'Settings', + icon: Icons.settings_outlined, + cupertinoIcon: CupertinoIcons.gear, + ), +}; diff --git a/app/notes/F2.md b/app/notes/F2.md index e70e653a..ff1fd3c5 100644 --- a/app/notes/F2.md +++ b/app/notes/F2.md @@ -12,7 +12,10 @@ themes active elsewhere, and accepts injectable `WidgetBuilder` bodies through - `flutter test test/widget_test.dart`: passed (narrow/wide, 2x text scale, Cupertino controls and injected destination body). - `flutter analyze`: passed, no issues. -- Web build/browser interaction/capture: not run in this stage; no browser - automation/capture evidence available. Mobile targets are unverified. +- Follow-up verification: widget tests now cover state retention across tab + switches and Cupertino safe-area insets. `flutter build web` succeeds. +- Browser interaction/capture remains unverified: the local Chrome DevTools + probe did not complete, so no rendered evidence is claimed. Mobile targets + are unverified. No API capabilities are asserted or mocked. No dependencies were added. diff --git a/app/test/widget_test.dart b/app/test/widget_test.dart index e10bf144..774496bc 100644 --- a/app/test/widget_test.dart +++ b/app/test/widget_test.dart @@ -47,6 +47,41 @@ void main() { expect(find.text('Pipelines — Not implemented'), findsOneWidget); }); + testWidgets('Cupertino content stays inside safe area', (tester) async { + tester.view.padding = const FakeViewPadding(top: 36, bottom: 28); + addTearDown(tester.view.resetPadding); + await tester.pumpWidget(const MyApp(cupertino: true)); + final tabBar = tester.getRect(find.byType(CupertinoTabBar)); + expect(tabBar.bottom, lessThanOrEqualTo(900 - 28)); + expect(tester.takeException(), isNull); + }); + + testWidgets('destination state survives switching tabs', (tester) async { + var builds = 0; + await tester.pumpWidget( + MaterialApp( + home: AdaptiveShell( + destinationBodies: { + AppDestination.pipelines: (_) => StatefulBuilder( + builder: (context, setState) => TextButton( + onPressed: () => setState(() => builds++), + child: Text('Builds: $builds'), + ), + ), + AppDestination.runs: (_) => const Text('Runs screen'), + }, + ), + ), + ); + await tester.tap(find.text('Builds: 0')); + await tester.pump(); + await tester.tap(find.text('Runs').last); + await tester.pumpAndSettle(); + await tester.tap(find.text('Pipelines').last); + await tester.pumpAndSettle(); + expect(find.text('Builds: 1'), findsOneWidget); + }); + testWidgets('destination content can be supplied by integration', ( tester, ) async { diff --git a/app/tool/shell_probe.mjs b/app/tool/shell_probe.mjs new file mode 100644 index 00000000..73d4695f --- /dev/null +++ b/app/tool/shell_probe.mjs @@ -0,0 +1,88 @@ +import { createServer } from 'node:http'; +import { readFile } 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 } from 'node:path'; +import { tmpdir } from 'node:os'; +import { mkdtemp, rm } from 'node:fs/promises'; + +const root = join(process.cwd(), 'build/web'); +const mime = { '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.wasm': 'application/wasm', '.png': 'image/png', '.ico': 'image/x-icon' }; +const server = createServer(async (req, res) => { + try { + const path = join(root, decodeURIComponent(new URL(req.url, 'http://localhost').pathname)); + const file = await readFile(path.endsWith('/') ? join(path, 'index.html') : path); + res.writeHead(200, { 'content-type': mime[extname(path)] ?? 'application/octet-stream' }).end(file); + } catch { res.writeHead(404).end('not found'); } +}); +server.listen(0, '127.0.0.1'); +await once(server, 'listening'); +const port = server.address().port; +const profile = await mkdtemp(join(tmpdir(), 'f2-shell-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; }); +const waitFor = async fn => { + for (let i = 0; i < 100; i++) { const value = await fn(); if (value) return value; await delay(100); } + throw new Error('Timed out waiting for Chrome DevTools'); +}; +let ws; +try { + const endpoint = await waitFor(() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1]); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + ws.addEventListener('message', event => { + const msg = JSON.parse(event.data); + if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); } + }); + const send = (method, params = {}, sessionId) => new Promise(resolve => { + const callId = ++id; pending.set(callId, resolve); + ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) })); + }); + const created = await send('Target.createTarget', { url: `http://127.0.0.1:${port}/` }); + 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); + 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)}`); + return response.result?.result?.value; + }; + await delay(3500); + const loaded = await evaluate("({url:location.href, ready:document.readyState, body:document.body.innerText, html:document.body.innerHTML.slice(0,500)})"); + if (!loaded?.url.includes(`127.0.0.1:${port}`)) throw new Error(`Fixture did not load: ${JSON.stringify(loaded)}`); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(900); + const clickLabel = async label => evaluate(`(() => { const e=[...document.querySelectorAll('flt-semantics')].find(x => (x.getAttribute('aria-label') || x.innerText || '').includes(${JSON.stringify(label)})); if (!e) return false; e.click(); return true; })()`); + const labels = await evaluate("[...document.querySelectorAll('flt-semantics')].map(x=>x.getAttribute('aria-label')||x.innerText).filter(Boolean)"); + if (!labels?.some(x => x.includes('Pipelines'))) throw new Error(`Flutter semantics unavailable: ${JSON.stringify(labels)}`); + const capture = async (name, width, height) => { + await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 }, session); + await delay(350); + const data = (await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session)).result.data; + await (await import('node:fs/promises')).writeFile(`${process.env.OPENCODE_ARTIFACT_DIR}/${name}.png`, Buffer.from(data, 'base64')); + }; + await capture('f2-shell-phone', 390, 844); + for (const label of ['Runs', 'Chat', 'Settings', 'Pipelines']) { + if (!await clickLabel(label)) throw new Error(`Could not interact with ${label} navigation`); + await delay(250); + const current = await evaluate("[...document.querySelectorAll('flt-semantics')].map(x=>x.getAttribute('aria-label')||x.innerText).filter(Boolean)"); + if (!current?.some(x => x.includes(label))) throw new Error(`${label} missing after navigation`); + } + await capture('f2-shell-desktop', 1280, 800); + console.log(JSON.stringify({ labels, captures: ['f2-shell-phone.png', 'f2-shell-desktop.png'], navigated: ['Runs', 'Chat', 'Settings', 'Pipelines'] }, 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 }); +} From 1e4ecea82390e043f18664fc15705726b9eafbbd Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:28:59 +0100 Subject: [PATCH 08/84] fix(app): harden socket lifecycle and expand transport regressions --- app/lib/core/transport/connection_state.dart | 27 +++ app/lib/core/transport/pipelines_client.dart | 171 ++++++++++++------ app/lib/core/transport/server_url.dart | 77 ++++++-- app/notes/F1.md | 8 + .../transport/client_regression_test.dart | 144 +++++++++++++++ .../core/transport/pipelines_client_test.dart | 15 +- app/test/core/transport/server_url_test.dart | 38 +++- 7 files changed, 401 insertions(+), 79 deletions(-) create mode 100644 app/lib/core/transport/connection_state.dart create mode 100644 app/test/core/transport/client_regression_test.dart diff --git a/app/lib/core/transport/connection_state.dart b/app/lib/core/transport/connection_state.dart new file mode 100644 index 00000000..f8d6d32f --- /dev/null +++ b/app/lib/core/transport/connection_state.dart @@ -0,0 +1,27 @@ +enum ConnectionKind { idle, connecting, connected, disconnected } + +class ConnectionState { + const ConnectionState( + this.kind, { + this.attempt = 0, + this.reason = '', + this.retrying = false, + }); + final ConnectionKind kind; + final int attempt; + final String reason; + final bool retrying; +} + +class ProtocolError implements Exception { + const ProtocolError(this.message); + final String message; + @override + String toString() => message; +} + +class NotConnectedError implements Exception { + const NotConnectedError(); + @override + String toString() => 'Not connected to the Pipelines server'; +} diff --git a/app/lib/core/transport/pipelines_client.dart b/app/lib/core/transport/pipelines_client.dart index 923b66f3..dfdeacf0 100644 --- a/app/lib/core/transport/pipelines_client.dart +++ b/app/lib/core/transport/pipelines_client.dart @@ -4,39 +4,21 @@ import 'dart:convert'; import 'package:web_socket_channel/web_socket_channel.dart'; import '../api_gateway.dart'; +import 'connection_state.dart'; import 'server_url.dart'; -enum ConnectionKind { idle, connecting, connected, disconnected } - -class ConnectionState { - const ConnectionState(this.kind, {this.attempt = 0, this.reason = '', this.retrying = false}); - final ConnectionKind kind; - final int attempt; - final String reason; - final bool retrying; -} - -class ProtocolError implements Exception { - const ProtocolError(this.message); - final String message; - @override - String toString() => message; -} - -class NotConnectedError implements Exception { - const NotConnectedError(); - @override - String toString() => 'Not connected to the Pipelines server'; -} +export 'connection_state.dart'; typedef ChannelFactory = WebSocketChannel Function(Uri uri); /// One correlated websocket transport shared by all feature gateways. class PipelinesClient implements ApiGateway { - PipelinesClient({ChannelFactory? channelFactory, + PipelinesClient({ + ChannelFactory? channelFactory, this.requestTimeout = const Duration(seconds: 30), this.backoffBase = const Duration(seconds: 1), - this.backoffMax = const Duration(seconds: 30)}) : _factory = channelFactory ?? WebSocketChannel.connect; + this.backoffMax = const Duration(seconds: 30), + }) : _factory = channelFactory ?? WebSocketChannel.connect; final ChannelFactory _factory; final Duration requestTimeout, backoffBase, backoffMax; @@ -74,19 +56,26 @@ class PipelinesClient implements ApiGateway { _setState(ConnectionState(ConnectionKind.connecting, attempt: ++_attempt)); final old = _channel; _channel = null; - await _subscription?.cancel(); _failPending('Connection replaced'); if (old != null) unawaited(old.sink.close()); + final subscription = _subscription; + _subscription = null; + await subscription?.cancel(); + if (generation != _generation || _manual || _disposed) return; try { final channel = _factory(endpoint); _channel = channel; - _subscription = channel.stream.listen((data) { - if (generation == _generation) _onMessage(data); - }, onError: (Object error) { - if (generation == _generation) _closed(error.toString()); - }, onDone: () { - if (generation == _generation) _closed('Connection closed'); - }); + _subscription = channel.stream.listen( + (data) { + if (generation == _generation) _onMessage(data); + }, + onError: (Object error) { + if (generation == _generation) _closed(error.toString()); + }, + onDone: () { + if (generation == _generation) _closed('Connection closed'); + }, + ); await channel.ready; if (generation != _generation) return; _attempt = 0; @@ -96,36 +85,72 @@ class PipelinesClient implements ApiGateway { } } - void _setState(ConnectionState value) { _state = value; if (!_states.isClosed) _states.add(value); } + void _setState(ConnectionState value) { + _state = value; + if (!_states.isClosed) _states.add(value); + } @override Future call(String type, [JsonMap fields = const {}]) { final completer = Completer(); - final run = _queue.then((_) => _sendCall(type, fields, completer)); + final generation = _generation; + final snapshot = Map.of(fields); + final run = _queue.then( + (_) => _sendCall(type, snapshot, completer, generation), + ); _queue = run.catchError((_) {}); return completer.future; } - Future _sendCall(String type, JsonMap fields, Completer result) async { + Future _sendCall( + String type, + JsonMap fields, + Completer result, + int generation, + ) async { + if (generation != _generation) { + result.completeError(StateError('Connection replaced')); + return; + } final channel = _channel; - if (channel == null || _state.kind != ConnectionKind.connected) { result.completeError(const NotConnectedError()); return; } + if (channel == null || _state.kind != ConnectionKind.connected) { + result.completeError(const NotConnectedError()); + return; + } final id = 'flutter-${++_sequence}'; _pending[id] = result; final timer = Timer(requestTimeout, () { - if (_pending.remove(id) != null) result.completeError(TimeoutException('request timed out after ${requestTimeout.inMilliseconds}ms')); + if (_pending.remove(id) != null) { + result.completeError( + TimeoutException( + 'request timed out after ${requestTimeout.inMilliseconds}ms', + ), + ); + } }); - result.future.then((_) => timer.cancel(), onError: (Object error, StackTrace stack) => timer.cancel()); + result.future.then( + (_) => timer.cancel(), + onError: (Object error, StackTrace stack) => timer.cancel(), + ); try { channel.sink.add(jsonEncode({...fields, 'type': type, 'id': id})); } catch (error) { timer.cancel(); if (_pending.remove(id) != null) result.completeError(error); } + // Match the existing client's serialized request semantics, even on errors. + try { + await result.future; + } catch (_) { + /* The caller receives the error. */ + } } String sendOnly(String type, [JsonMap fields = const {}]) { final channel = _channel; - if (channel == null || _state.kind != ConnectionKind.connected) throw const NotConnectedError(); + if (channel == null || _state.kind != ConnectionKind.connected) { + throw const NotConnectedError(); + } final id = 'flutter-${++_sequence}'; channel.sink.add(jsonEncode({...fields, 'type': type, 'id': id})); return id; @@ -134,50 +159,88 @@ class PipelinesClient implements ApiGateway { void _onMessage(dynamic data) { if (data is! String) return; final Object? decoded; - try { decoded = jsonDecode(data); } on FormatException { return; } + try { + decoded = jsonDecode(data); + } on FormatException { + return; + } if (decoded is! Map) return; final message = decoded; final id = message['id']; final pending = id is String ? _pending.remove(id) : null; if (pending != null) { if (message['type'] == 'error') { - final reason = (message['error'] as String? ?? '').trim(); - pending.completeError(ProtocolError(reason.isEmpty ? 'server error' : reason)); + final reason = '${message['error'] ?? ''}'.trim(); + pending.completeError( + ProtocolError(reason.isEmpty ? 'server error' : reason), + ); } else { pending.complete(message); } - } else if (!_frames.isClosed) { _frames.add(message); } + } else if (!_frames.isClosed) { + _frames.add(message); + } } void _failPending(String reason) { - final values = _pending.values.toList(); _pending.clear(); - for (final item in values) { if (!item.isCompleted) item.completeError(StateError(reason)); } + final values = _pending.values.toList(); + _pending.clear(); + for (final item in values) { + if (!item.isCompleted) item.completeError(StateError(reason)); + } } void _closed(String reason) { _generation++; + final channel = _channel; + final subscription = _subscription; _channel = null; + _subscription = null; + if (subscription != null) unawaited(subscription.cancel()); + if (channel != null) unawaited(channel.sink.close().catchError((_) {})); _failPending(reason); - if (_manual || _disposed) { _setState(const ConnectionState(ConnectionKind.idle)); return; } - _setState(ConnectionState(ConnectionKind.disconnected, attempt: _attempt, reason: reason, retrying: true)); + if (_manual || _disposed) { + _setState(const ConnectionState(ConnectionKind.idle)); + return; + } + _setState( + ConnectionState( + ConnectionKind.disconnected, + attempt: _attempt, + reason: reason, + retrying: true, + ), + ); final shift = (_attempt - 1).clamp(0, 6); final delay = backoffBase * (1 << shift); _reconnect?.cancel(); - _reconnect = Timer(delay > backoffMax ? backoffMax : delay, () => unawaited(_open())); + _reconnect = Timer( + delay > backoffMax ? backoffMax : delay, + () => unawaited(_open()), + ); } Future disconnect() async { - _manual = true; _reconnect?.cancel(); _generation++; - final channel = _channel; _channel = null; - await _subscription?.cancel(); _subscription = null; + _manual = true; + _reconnect?.cancel(); + final generation = ++_generation; + final channel = _channel; + _channel = null; + final subscription = _subscription; + _subscription = null; _failPending('Disconnected'); + await subscription?.cancel(); if (channel != null) await channel.sink.close(); - _setState(const ConnectionState(ConnectionKind.idle)); + if (generation == _generation) { + _setState(const ConnectionState(ConnectionKind.idle)); + } } Future dispose() async { if (_disposed) return; - await disconnect(); _disposed = true; - await _frames.close(); await _states.close(); + _disposed = true; + await disconnect(); + await _frames.close(); + await _states.close(); } } diff --git a/app/lib/core/transport/server_url.dart b/app/lib/core/transport/server_url.dart index 7f2eb59b..b08a10ac 100644 --- a/app/lib/core/transport/server_url.dart +++ b/app/lib/core/transport/server_url.dart @@ -1,7 +1,12 @@ /// Validation result for a configured Pipelines websocket endpoint. class ServerUrl { - const ServerUrl._({required this.wsUrl, required this.httpUrl, - required this.host, required this.port, required this.secure}); + const ServerUrl._({ + required this.wsUrl, + required this.httpUrl, + required this.host, + required this.port, + required this.secure, + }); final String wsUrl; final String httpUrl; @@ -11,35 +16,73 @@ class ServerUrl { static ServerUrl validate(String raw) { final value = raw.trim(); - if (value.isEmpty) throw const FormatException('Enter the Pipelines server URL, for example ws://192.168.1.20:8081/connect'); + if (value.isEmpty) { + throw const FormatException( + 'Enter the Pipelines server URL, for example ws://192.168.1.20:8081/connect', + ); + } final uri = Uri.tryParse(value); - if (uri == null || !uri.hasScheme) throw const FormatException('That is not a valid URL.'); + if (uri == null || !uri.hasScheme) { + throw const FormatException('That is not a valid URL.'); + } final scheme = uri.scheme.toLowerCase(); if (scheme != 'ws' && scheme != 'wss') { - throw FormatException('Unsupported scheme "$scheme"; use ws:// (trusted LAN/VPN) or wss://'); + throw FormatException( + 'Unsupported scheme "$scheme"; use ws:// (trusted LAN/VPN) or wss://', + ); + } + if (uri.userInfo.isNotEmpty) { + throw const FormatException( + 'Credentials are not supported; the server has no authentication. Remove userinfo from the URL', + ); + } + if (uri.hasFragment) { + throw const FormatException( + 'Remove the # fragment; it is not part of the server endpoint', + ); + } + if (uri.host.isEmpty) { + throw const FormatException( + 'The URL is missing a host, for example ws://192.168.1.20:8081/connect', + ); + } + if (!uri.hasAuthority || + (uri.hasPort && (uri.port < 1 || uri.port > 65535))) { + throw const FormatException( + 'That is not a valid server authority or port.', + ); } - if (uri.userInfo.isNotEmpty) throw const FormatException('Credentials are not supported; the server has no authentication. Remove userinfo from the URL'); - if (uri.hasFragment) throw const FormatException('Remove the # fragment; it is not part of the server endpoint'); - if (uri.host.isEmpty) throw const FormatException('The URL is missing a host, for example ws://192.168.1.20:8081/connect'); final secure = scheme == 'wss'; - final port = uri.hasPort ? uri.port : secure ? 443 : 80; + final port = uri.hasPort + ? uri.port + : secure + ? 443 + : 80; final path = uri.path.isEmpty || uri.path == '/' ? '/connect' : uri.path; - final authority = uri.hasPort ? '${uri.host}:$port' : uri.host; - final suffix = uri.hasQuery ? '?${uri.query}' : ''; - return ServerUrl._(wsUrl: '$scheme://$authority$path$suffix', - httpUrl: '${secure ? 'https' : 'http'}://$authority$path$suffix', - host: uri.host, port: port, secure: secure); + final normalized = uri.replace(scheme: scheme, path: path); + return ServerUrl._( + wsUrl: normalized.toString(), + httpUrl: normalized.replace(scheme: secure ? 'https' : 'http').toString(), + host: uri.host, + port: port, + secure: secure, + ); } static Uri? resolveArtifactUrl(String configured, String artifactUrl) { final path = artifactUrl.trim(); if (path.isEmpty) return null; final parsed = Uri.tryParse(path); - if (parsed != null && (parsed.scheme == 'http' || parsed.scheme == 'https')) return parsed; + if (parsed != null && + (parsed.scheme == 'http' || parsed.scheme == 'https')) { + return parsed; + } try { final endpoint = validate(configured); - final portPart = endpoint.port != (endpoint.secure ? 443 : 80) ? ':${endpoint.port}' : ''; - return Uri.parse('${endpoint.secure ? 'https' : 'http'}://${endpoint.host}$portPart/${path.replaceFirst(RegExp(r'^/+'), '')}'); + final origin = Uri.parse( + endpoint.httpUrl, + ).replace(path: '/', query: null); + return origin.resolve(path.replaceFirst(RegExp(r'^/+'), '')); } on FormatException { return null; } diff --git a/app/notes/F1.md b/app/notes/F1.md index 269e2685..3b8504b0 100644 --- a/app/notes/F1.md +++ b/app/notes/F1.md @@ -11,3 +11,11 @@ endpoint helper: `package:pipelines_app/core/transport/server_url.dart`. The client accepts an injected `ChannelFactory` for deterministic tests. No live server was used. Browser and mobile target verification should be reported separately from these unit tests. + +## Manager verification +Expanded to 12 focused tests, including serialized requests, queue recovery +after protocol errors/timeouts, late replies, replacement of queued requests, +send-only subscriptions, concurrent connects, reconnect and disposal. Corrected +generation races and socket cleanup; URI construction now retains bracketed +IPv6 hosts and encoded artifact query strings. Analyze passes after formatting. +These are unit checks, not browser/live-server acceptance or mobile verification. diff --git a/app/test/core/transport/client_regression_test.dart b/app/test/core/transport/client_regression_test.dart new file mode 100644 index 00000000..2409ac5b --- /dev/null +++ b/app/test/core/transport/client_regression_test.dart @@ -0,0 +1,144 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; + +import 'pipelines_client_test.dart' show FakeChannel; + +Future flush() => Future.delayed(Duration.zero); +Map sent(FakeChannel channel, [int index = 0]) => + jsonDecode(channel.outgoing[index] as String) as Map; +void reply(FakeChannel channel, {int index = 0, String type = 'pong'}) => + channel.incoming.add( + jsonEncode({'id': sent(channel, index)['id'], 'type': type}), + ); + +void main() { + test( + 'requests serialize through replies, errors do not poison queue', + () async { + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + await client.connect(Uri.parse('ws://example.test')); + final first = client.call('ping'); + final firstError = expectLater(first, throwsA(isA())); + final second = client.call('list_runs'); + await flush(); + expect(channel.outgoing, hasLength(1)); + channel.incoming.add( + jsonEncode({ + 'id': sent(channel)['id'], + 'type': 'error', + 'error': 'refused', + }), + ); + await firstError; + await flush(); + expect(channel.outgoing, hasLength(2)); + reply(channel, index: 1, type: 'runs'); + expect((await second)['type'], 'runs'); + await client.dispose(); + }, + ); + + test( + 'timeout releases queue and late response is an unsolicited frame', + () async { + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient( + channelFactory: (_) => channel, + requestTimeout: const Duration(milliseconds: 10), + ); + await client.connect(Uri.parse('ws://example.test')); + await expectLater(client.call('ping'), throwsA(isA())); + final late = client.frames.first; + reply(channel); + expect((await late)['type'], 'pong'); + await client.dispose(); + }, + ); + + test( + 'replacement fails queued calls rather than sending on new socket', + () async { + final channels = [ + FakeChannel()..readyCompleter.complete(), + FakeChannel()..readyCompleter.complete(), + ]; + var index = 0; + final client = PipelinesClient(channelFactory: (_) => channels[index++]); + await client.connect(Uri.parse('ws://old.test')); + final firstError = expectLater(client.call('ping'), throwsStateError); + final queuedError = expectLater( + client.call('list_runs'), + throwsStateError, + ); + await flush(); + await client.connect(Uri.parse('ws://new.test')); + await Future.wait([firstError, queuedError]); + expect(channels.last.outgoing, isEmpty); + expect(client.state.kind, ConnectionKind.connected); + await client.dispose(); + }, + ); + + test('sendOnly never blocks correlated requests', () async { + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + await client.connect(Uri.parse('ws://example.test')); + client.sendOnly('subscribe', {'workspace': ''}); + final ping = client.call('ping'); + await flush(); + expect(sent(channel)['type'], 'subscribe'); + reply(channel, index: 1); + expect((await ping)['type'], 'pong'); + await client.dispose(); + }); + + test('overlapping connect cannot create a superseded socket', () async { + var factories = 0; + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient( + channelFactory: (_) { + factories++; + return channel; + }, + ); + await Future.wait([ + client.connect(Uri.parse('ws://old.test')), + client.connect(Uri.parse('ws://new.test')), + ]); + expect(factories, 1); + expect(client.state.kind, ConnectionKind.connected); + await client.dispose(); + await expectLater( + client.connect(Uri.parse('ws://new.test')), + throwsStateError, + ); + }); + + test('socket failure reconnects, disconnect cancels retry', () async { + final first = FakeChannel()..readyCompleter.complete(); + final next = FakeChannel()..readyCompleter.complete(); + var factories = 0; + final client = PipelinesClient( + channelFactory: (_) => factories++ == 0 ? first : next, + backoffBase: const Duration(milliseconds: 5), + ); + await client.connect(Uri.parse('ws://example.test')); + final connectedAgain = client.states.firstWhere( + (s) => s.kind == ConnectionKind.connected, + ); + first.incoming.addError(StateError('network drop')); + await connectedAgain.timeout(const Duration(seconds: 2)); + expect(factories, 2); + await client.disconnect(); + expect(client.state.retrying, isFalse); + expect( + () => client.sendOnly('subscribe'), + throwsA(isA()), + ); + await client.dispose(); + }); +} diff --git a/app/test/core/transport/pipelines_client_test.dart b/app/test/core/transport/pipelines_client_test.dart index 01840d05..e71b78f6 100644 --- a/app/test/core/transport/pipelines_client_test.dart +++ b/app/test/core/transport/pipelines_client_test.dart @@ -34,9 +34,17 @@ class FakeSink implements WebSocketSink { @override void addError(Object error, [StackTrace? stackTrace]) => throw error; @override - Future addStream(Stream stream) async { await for (final item in stream) { add(item); } } + Future addStream(Stream stream) async { + await for (final item in stream) { + add(item); + } + } + @override - Future close([int? closeCode, String? closeReason]) async { await incoming.close(); } + Future close([int? closeCode, String? closeReason]) async { + await incoming.close(); + } + @override Future get done async {} @override @@ -54,7 +62,8 @@ void main() { await connecting; final request = client.call('ping', {'value': 1}); await Future.delayed(Duration.zero); - final sent = jsonDecode(channel.outgoing.single as String) as Map; + final sent = + jsonDecode(channel.outgoing.single as String) as Map; channel.incoming.add(jsonEncode({'id': sent['id'], 'type': 'pong'})); expect((await request)['type'], 'pong'); channel.incoming.add(jsonEncode({'type': 'run_event'})); diff --git a/app/test/core/transport/server_url_test.dart b/app/test/core/transport/server_url_test.dart index b7773d31..e2634f99 100644 --- a/app/test/core/transport/server_url_test.dart +++ b/app/test/core/transport/server_url_test.dart @@ -2,6 +2,20 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/core/transport/server_url.dart'; void main() { + test('IPv6 authorities and encoded artifact queries stay intact', () { + expect( + ServerUrl.validate('ws://[::1]:8081').wsUrl, + 'ws://[::1]:8081/connect', + ); + expect( + ServerUrl.resolveArtifactUrl( + 'ws://[::1]:8081/connect', + '/artifacts/a%20b?download=1', + ).toString(), + 'http://[::1]:8081/artifacts/a%20b?download=1', + ); + expect(() => ServerUrl.validate('ws://host:70000'), throwsFormatException); + }); test('validates and normalizes endpoint with path and query', () { final value = ServerUrl.validate(' wss://example.test:8443/?token=x '); expect(value.wsUrl, 'wss://example.test:8443/connect?token=x'); @@ -10,14 +24,28 @@ void main() { }); test('rejects unsupported schemes and credentials', () { - expect(() => ServerUrl.validate('https://example.test'), throwsFormatException); - expect(() => ServerUrl.validate('ws://user:pass@example.test'), throwsFormatException); + expect( + () => ServerUrl.validate('https://example.test'), + throwsFormatException, + ); + expect( + () => ServerUrl.validate('ws://user:pass@example.test'), + throwsFormatException, + ); }); test('resolves relative artifacts at the server origin', () { - expect(ServerUrl.resolveArtifactUrl('ws://example.test:8081/connect', '/artifacts/a')!.toString(), - 'http://example.test:8081/artifacts/a'); + expect( + ServerUrl.resolveArtifactUrl( + 'ws://example.test:8081/connect', + '/artifacts/a', + )!.toString(), + 'http://example.test:8081/artifacts/a', + ); expect(ServerUrl.resolveArtifactUrl('', '/artifacts/a'), isNull); - expect(ServerUrl.resolveArtifactUrl('', 'https://cdn.test/a')!.toString(), 'https://cdn.test/a'); + expect( + ServerUrl.resolveArtifactUrl('', 'https://cdn.test/a')!.toString(), + 'https://cdn.test/a', + ); }); } From 5cd269fca423a2687723c032d932e1138d7f6214 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:32:54 +0100 Subject: [PATCH 09/84] fix(app): harden guarded preview proxy --- app/notes/F5.md | 21 +++ app/test/tool/preview.test.mjs | 182 ++++++++++++++++++++----- app/tool/preview/README.md | 18 ++- app/tool/preview/server.mjs | 241 +++++++++++++++++++++++++-------- 4 files changed, 366 insertions(+), 96 deletions(-) create mode 100644 app/notes/F5.md diff --git a/app/notes/F5.md b/app/notes/F5.md new file mode 100644 index 00000000..b5141ff0 --- /dev/null +++ b/app/notes/F5.md @@ -0,0 +1,21 @@ +# F5 preview server candidate review + +Candidate `e3a82b0`'s static preview route was retained, with stricter decoded +path validation and canonical-path checks for files and SPA fallback. The proxy +now uses `http.request` / `https.request` streams so Range, HEAD, content-encoding, +and exact response bytes are preserved. Authentication checks fail closed after +five seconds and discard their response bodies. Unauthenticated document GETs +are redirected to the authenticated proxy's `/login?next=...`; assets remain +401. Login, logout, and artifact proxying still use the browser's upstream cookie. + +WebSocket upgrades validate `/connect` and a same-origin browser Origin before +authentication or upstream connection. After authentication, both Host and +Origin map to the configured HTTP(S) upstream origin; cookies and upgrade headers +are retained. Upgraded sockets are tracked and destroyed during `close()`. HTTPS +uses Node TLS verification (no certificate bypass). Bind to loopback by default. + +Verification: `node --test test/tool/preview.test.mjs`, `node --check` on server +and test, and `git diff --check`. Tests use only local fixtures and cover login +redirect, denied auth, exact compressed Range/HEAD bytes, origin rejection, +authenticated bidirectional WebSocket bytes, timeout, shutdown, and traversal / symlink +protection. No browser run, Flutter build, production access, or deployment was done. diff --git a/app/test/tool/preview.test.mjs b/app/test/tool/preview.test.mjs index 68b70c36..17561d2a 100644 --- a/app/test/tool/preview.test.mjs +++ b/app/test/tool/preview.test.mjs @@ -1,48 +1,158 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { mkdtemp, mkdir, writeFile, symlink, rm } from 'node:fs/promises'; +import { mkdtemp, writeFile, symlink, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { createServer } from 'node:http'; +import { request as httpRequest } from 'node:http'; +import { gzipSync } from 'node:zlib'; +import net from 'node:net'; import { start } from '../../tool/preview/server.mjs'; -test('serves guarded assets, deep links, MIME and missing assets; forwards auth routes and artifacts', async t => { - const dir=await mkdtemp(join(tmpdir(),'preview-')); await mkdir(join(dir,'assets')); await writeFile(join(dir,'index.html'),'shell'); await writeFile(join(dir,'assets/a.wasm'),'wasm'); - const upstream=createServer((req,res)=>{ if(req.url==='/') {res.writeHead(req.headers.cookie==='sid=yes'?200:302,{location:'/login'}).end();return} res.writeHead(200,{'x-forwarded':req.url}).end(req.url) }); - await new Promise(ok=>upstream.listen(0,'127.0.0.1',ok)); - const preview=await start({root:dir,upstream:`http://127.0.0.1:${upstream.address().port}`,port:0}); t.after(async()=>{await preview.close();upstream.close();await rm(dir,{recursive:true,force:true})}); - const base=`http://127.0.0.1:${preview.port}`; - assert.equal((await fetch(base+'/assets/a.wasm')).status,401); - const headers={cookie:'sid=yes'}; - const wasm=await fetch(base+'/assets/a.wasm',{headers}); assert.equal(wasm.headers.get('content-type'),'application/wasm'); assert.equal(wasm.headers.get('cache-control'),'no-store'); - assert.equal(await (await fetch(base+'/runs/4',{headers})).text(),'shell'); - assert.equal((await fetch(base+'/assets/missing.js',{headers})).status,404); - assert.equal((await fetch(base+'/..%2f..%2fetc/passwd',{headers})).status,403); - assert.equal((await fetch(base+'/artifacts/1/a',{headers})).status,200); - assert.equal((await fetch(base+'/login')).status,200); +async function fixture(t, { auth = true, hanging = false } = {}) { + const root = await mkdtemp(join(tmpdir(), 'preview-')); + await writeFile(join(root, 'index.html'), 'shell'); + await writeFile(join(root, 'bundle.js'), 'bundle'); + const seen = []; + const upstream = createServer((req, res) => { + seen.push({ url: req.url, headers: req.headers, method: req.method }); + if (req.url === '/' && auth && req.headers.cookie !== 'sid=yes') { + res.writeHead(302, { location: '/login' }).end(); + } else if (req.url === '/' && hanging) { + // Deliberately hold the auth check open to exercise its timeout. + } else if (req.url === '/login' || req.url === '/logout' || req.url.startsWith('/artifacts/')) { + res.writeHead(200, { 'content-type': 'application/octet-stream' }).end('proxied'); + } else res.writeHead(200).end('authenticated'); + }); + upstream.on('upgrade', (req, socket, head) => { + seen.push({ url: req.url, headers: req.headers, upgraded: true }); + socket.write('HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n'); + if (head.length) socket.write(head); + socket.pipe(socket); + }); + await new Promise((resolve) => upstream.listen(0, '127.0.0.1', resolve)); + const preview = await start({ root, upstream: `http://127.0.0.1:${upstream.address().port}`, port: 0 }); + t.after(async () => { + await preview.close(); + await new Promise((resolve) => upstream.close(resolve)); + await rm(root, { recursive: true, force: true }); + }); + return { root, upstream, preview, seen, base: `http://127.0.0.1:${preview.port}` }; +} + +function rawRequest(port, path, method, headers = {}) { + return new Promise((resolve, reject) => { + const request = httpRequest({ host: '127.0.0.1', port, path, method, headers }, (response) => { + const chunks = []; + response.on('data', (chunk) => chunks.push(chunk)); + response.on('end', () => resolve({ status: response.statusCode, headers: response.headers, body: Buffer.concat(chunks) })); + }); + request.on('error', reject); + request.end(); + }); +} + +test('guards assets and redirects unauthenticated document requests to proxy login', async (t) => { + const { base, seen } = await fixture(t); + const redirect = await fetch(`${base}/runs/4?tab=active`, { redirect: 'manual', headers: { accept: 'text/html' } }); + assert.equal(redirect.status, 302); + assert.equal(redirect.headers.get('location'), '/login?next=%2Fruns%2F4%3Ftab%3Dactive'); + assert.equal((await fetch(`${base}/bundle.js`)).status, 401); + const auth = { cookie: 'sid=yes' }; + assert.equal(await (await fetch(`${base}/bundle.js`, { headers: auth })).text(), 'bundle'); + assert.equal((await fetch(`${base}/login`)).status, 200); + assert.equal(seen.filter((item) => item.url === '/login').length, 1); + assert.equal((await fetch(`${base}/%2f%2fevil`, { headers: auth })).status, 400); }); -test('rejects a directory index symlink that escapes the preview root', async t => { - const dir=await mkdtemp(join(tmpdir(),'preview-')), outside=await mkdtemp(join(tmpdir(),'preview-out-')); - await mkdir(join(dir,'linked')); await writeFile(join(outside,'secret.html'),'secret'); - await symlink(join(outside,'secret.html'),join(dir,'linked','index.html')); - const upstream=createServer((req,res)=>res.end('ok')); - await new Promise(ok=>upstream.listen(0,'127.0.0.1',ok)); - const preview=await start({root:dir,upstream:`http://127.0.0.1:${upstream.address().port}`,port:0}); - t.after(async()=>{await preview.close();upstream.close();await rm(dir,{recursive:true,force:true});await rm(outside,{recursive:true,force:true})}); - const response=await fetch(`http://127.0.0.1:${preview.port}/linked/`,{headers:{cookie:'sid=yes'}}); - assert.equal(response.status,403); +test('streams exact compressed range bytes for GET and HEAD with mapped proxy requests', async (t) => { + const bytes = gzipSync(Buffer.from('preserve these exact compressed bytes')); + const { base, upstream, seen } = await fixture(t); + upstream.removeAllListeners('request'); + upstream.on('request', (req, res) => { + if (req.url === '/') return res.end('authenticated'); + seen.push({ url: req.url, headers: req.headers, method: req.method }); + res.writeHead(206, { 'content-type': 'application/octet-stream', 'content-encoding': 'gzip', 'content-range': 'bytes 1-3/6', 'content-length': '3' }); + res.end(bytes.subarray(1, 4)); + }); + const auth = { cookie: 'sid=yes', range: 'bytes=1-3' }; + const response = await rawRequest(new URL(base).port, '/artifacts/x', 'GET', auth); + assert.equal(response.status, 206); + assert.equal(response.headers['content-encoding'], 'gzip'); + assert.deepEqual(response.body, bytes.subarray(1, 4)); + const head = await rawRequest(new URL(base).port, '/artifacts/x', 'HEAD', auth); + assert.equal(head.status, 206); + assert.equal(head.headers['content-length'], '3'); + assert.equal(head.body.byteLength, 0); + assert.equal(seen.at(-1).headers.range, 'bytes=1-3'); }); -test('rejects an SPA fallback index symlink that escapes the preview root', async t => { - const dir=await mkdtemp(join(tmpdir(),'preview-')), outside=await mkdtemp(join(tmpdir(),'preview-out-')); - await writeFile(join(outside,'secret.html'),'secret'); - await symlink(join(outside,'secret.html'),join(dir,'index.html')); - const upstream=createServer((req,res)=>res.end('ok')); - await new Promise(ok=>upstream.listen(0,'127.0.0.1',ok)); - const preview=await start({root:dir,upstream:`http://127.0.0.1:${upstream.address().port}`,port:0}); - t.after(async()=>{await preview.close();upstream.close();await rm(dir,{recursive:true,force:true});await rm(outside,{recursive:true,force:true})}); - const response=await fetch(`http://127.0.0.1:${preview.port}/missing-route`,{headers:{cookie:'sid=yes'}}); - assert.equal(response.status,403); - assert.notEqual(await response.text(),'secret'); +test('rejects cross-origin and unauthenticated WebSocket upgrades before proxying', async (t) => { + const { preview, seen } = await fixture(t); + async function upgrade(headers) { + return new Promise((resolve) => { + const socket = net.connect(preview.port, '127.0.0.1', () => socket.write(`GET /connect HTTP/1.1\r\nHost: 127.0.0.1:${preview.port}\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n${headers}\r\n`)); + let response = ''; + socket.on('data', (chunk) => { response += chunk.toString(); if (response.includes('\r\n\r\n')) { socket.destroy(); resolve(response); } }); + socket.on('error', () => resolve(response)); + }); + } + assert.match(await upgrade(`Origin: http://evil.test\r\nCookie: sid=yes\r\n`), /^HTTP\/1\.1 403/); + assert.match(await upgrade(`Origin: http://127.0.0.1:${preview.port}\r\n`), /^HTTP\/1\.1 401/); + assert.equal(seen.filter((item) => item.upgraded).length, 0); +}); + +test('authenticates and maps same-origin WebSocket Origin; bytes flow both directions and close completes', async (t) => { + const { preview, seen } = await fixture(t); + const socket = net.connect(preview.port, '127.0.0.1'); + const chunks = []; + socket.on('data', (chunk) => chunks.push(chunk)); + socket.write(`GET /connect HTTP/1.1\r\nHost: 127.0.0.1:${preview.port}\r\nOrigin: http://127.0.0.1:${preview.port}\r\nCookie: sid=yes\r\nConnection: Upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n`); + await new Promise((resolve, reject) => { + const deadline = setTimeout(() => reject(new Error('upgrade timeout')), 1500); + const poll = setInterval(() => { + if (chunks.some((chunk) => chunk.toString().includes('101 Switching Protocols'))) { clearInterval(poll); clearTimeout(deadline); resolve(); } + }, 10); + }); + const upgraded = seen.find((item) => item.upgraded); + assert.equal(upgraded.headers.origin, new URL(`http://${seen[0].headers.host}`).origin); + assert.equal(upgraded.headers.cookie, 'sid=yes'); + const payload = Buffer.from([0x81, 0x02, 0x6f, 0x6b]); + socket.write(payload); + await new Promise((resolve, reject) => { + const deadline = setTimeout(() => reject(new Error('echo timeout')), 1500); + const poll = setInterval(() => { + if (Buffer.concat(chunks).includes(payload)) { clearInterval(poll); clearTimeout(deadline); resolve(); } + }, 10); + }); + socket.destroy(); + await preview.close(); +}); + +test('fails closed on authentication timeout and closes idle upgraded sockets', async (t) => { + const { base } = await fixture(t, { auth: false, hanging: true }); + const started = Date.now(); + const response = await fetch(`${base}/bundle.js`); + assert.equal(response.status, 502); + assert.ok(Date.now() - started < 7000); +}); + +test('rejects encoded traversal and symlinked SPA fallback outside the root', async (t) => { + const root = await mkdtemp(join(tmpdir(), 'preview-')); + const outside = await mkdtemp(join(tmpdir(), 'preview-out-')); + await writeFile(join(outside, 'index.html'), 'private'); + await symlink(join(outside, 'index.html'), join(root, 'index.html')); + const upstream = createServer((req, res) => res.end('authenticated')); + await new Promise((resolve) => upstream.listen(0, '127.0.0.1', resolve)); + const preview = await start({ root, upstream: `http://127.0.0.1:${upstream.address().port}`, port: 0 }); + t.after(async () => { + await preview.close(); + await new Promise((resolve) => upstream.close(resolve)); + await rm(root, { recursive: true, force: true }); + await rm(outside, { recursive: true, force: true }); + }); + const response = await fetch(`http://127.0.0.1:${preview.port}/missing/route`, { headers: { cookie: 'sid=yes' } }); + assert.equal(response.status, 403); + assert.notEqual(await response.text(), 'private'); + assert.equal((await fetch(`http://127.0.0.1:${preview.port}/%2e%2e%2fsecret`, { headers: { cookie: 'sid=yes' } })).status, 403); }); diff --git a/app/tool/preview/README.md b/app/tool/preview/README.md index 2d62a8f5..e060f920 100644 --- a/app/tool/preview/README.md +++ b/app/tool/preview/README.md @@ -8,7 +8,17 @@ UPSTREAM=http://127.0.0.1:8095 node tool/preview/server.mjs --port 8080 ``` The preview binds to loopback by default and authenticates static requests by -checking the upstream authenticated web proxy with the browser cookie. Login, -logout and artifacts are forwarded to that proxy; `/connect` is forwarded only -for same-origin websocket upgrades. Set `UPSTREAM` to the authenticated proxy, -never the raw control server. Tests use isolated local fixtures and port 0. +checking the upstream authenticated web proxy with the browser cookie. Unauthenticated +HTML navigation goes to the proxy's `/login?next=...`; unauthenticated assets and +WebSocket upgrades are refused. Login, logout and artifacts are streamed to the +proxy without decoding compressed response bodies. `/connect` accepts only a +same-origin browser Origin, checks the cookie, then maps Origin and Host to the +configured upstream origin before upgrading. HTTP and HTTPS upstreams are +supported using Node's normal TLS certificate verification. Set `UPSTREAM` to +the authenticated proxy, never the raw control server. The root path and files +must exist locally, and only GET, HEAD, and POST are supported. Tests use +isolated loopback fixtures and port 0. + +The persistent preview API is `start({ root, upstream, host, port })` from +`tool/preview/server.mjs`; it resolves to `{ server, port, close }`. Call +`close()` to stop accepting requests and close tracked upgraded sockets. diff --git a/app/tool/preview/server.mjs b/app/tool/preview/server.mjs index bd203128..818f985f 100644 --- a/app/tool/preview/server.mjs +++ b/app/tool/preview/server.mjs @@ -1,68 +1,197 @@ -import { createServer } from 'node:http'; -import { realpath, stat } from 'node:fs/promises'; +import { createServer, request as httpRequest } from 'node:http'; +import { request as httpsRequest } from 'node:https'; +import { realpath, stat, readFile } from 'node:fs/promises'; import { extname, resolve, sep } from 'node:path'; import net from 'node:net'; import tls from 'node:tls'; -const mime = { '.html':'text/html; charset=utf-8', '.js':'text/javascript; charset=utf-8', '.mjs':'text/javascript; charset=utf-8', '.wasm':'application/wasm', '.woff':'font/woff', '.woff2':'font/woff2', '.ttf':'font/ttf', '.json':'application/json', '.css':'text/css; charset=utf-8', '.png':'image/png', '.svg':'image/svg+xml' }; -const noCache = { 'Cache-Control':'no-store' }; -const response = (res, status, body='') => { if (!res.headersSent) res.writeHead(status, { ...noCache, 'Content-Type':'text/plain; charset=utf-8' }); res.end(body); }; +const mime = { + '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', + '.mjs': 'text/javascript; charset=utf-8', '.wasm': 'application/wasm', + '.woff': 'font/woff', '.woff2': 'font/woff2', '.ttf': 'font/ttf', + '.json': 'application/json', '.css': 'text/css; charset=utf-8', + '.png': 'image/png', '.svg': 'image/svg+xml', +}; +const noCache = { 'Cache-Control': 'no-store' }; +const timeoutMs = 5000; -export async function start({ root=resolve('build/web'), upstream='http://127.0.0.1:8095', host='127.0.0.1', port=8080 }={}) { - const base = await realpath(root), target = new URL(upstream); - if (!['http:','https:'].includes(target.protocol)) throw new Error('UPSTREAM must be HTTP(S)'); - const server = createServer(async (req,res) => { - let pathname; - try { pathname = decodeURIComponent(new URL(req.url, 'http://preview').pathname); } catch { return response(res,400); } - if (!['GET','HEAD','POST'].includes(req.method)) { res.setHeader('Allow','GET, HEAD, POST'); return response(res,405); } - if (pathname === '/login' || pathname === '/logout' || pathname.startsWith('/artifacts/')) return proxy(req,res,target); - try { - const check = await fetch(new URL('/', target), { headers: { cookie:req.headers.cookie ?? '', accept:'text/html' }, redirect:'manual' }); - if (!check.ok || check.status >= 300) return response(res, check.status === 401 || check.status === 302 ? 401 : 502, 'Authentication required'); - } catch { return response(res,502,'Authentication upstream unavailable'); } - if (req.method !== 'GET' && req.method !== 'HEAD') return response(res,405); - let file = resolve(base, `.${pathname}`); - if (file !== base && !file.startsWith(base + sep)) return response(res,403); - try { - let real = await realpath(file); - if (real !== base && !real.startsWith(base + sep)) return response(res,403); - if ((await stat(real)).isDirectory()) { - real = await realpath(resolve(real,'index.html')); - if (real !== base && !real.startsWith(base + sep)) return response(res,403); - } - file = real; - const body = await (await import('node:fs/promises')).readFile(file); - res.writeHead(200,{...noCache,'Content-Type':mime[extname(file)] ?? 'application/octet-stream'}); res.end(req.method==='HEAD' ? undefined : body); - } catch (e) { - if (e.code !== 'ENOENT' && e.code !== 'ENOTDIR') return response(res,403); - if (extname(pathname)) return response(res,404,'Not found'); - try { - const fallback=await realpath(resolve(base,'index.html')); - if (fallback !== base && !fallback.startsWith(base + sep)) return response(res,403); - const body=await (await import('node:fs/promises')).readFile(fallback); - res.writeHead(200,{...noCache,'Content-Type':mime['.html']}); res.end(body); - } catch { response(res,404,'Not found'); } +function reply(res, status, body = '') { + if (res.destroyed) return; + if (!res.headersSent) res.writeHead(status, { ...noCache, 'Content-Type': 'text/plain; charset=utf-8' }); + res.end(body); +} + +function inside(base, path) { + return path === base || path.startsWith(base + sep); +} + +async function staticFile(base, pathname, req, res) { + let file = resolve(base, `.${pathname}`); + if (!inside(base, file)) return reply(res, 403); + try { + let real = await realpath(file); + if (!inside(base, real)) return reply(res, 403); + if ((await stat(real)).isDirectory()) { + real = await realpath(resolve(real, 'index.html')); + if (!inside(base, real)) return reply(res, 403); } - }); - server.on('upgrade', (req,socket,head) => { + file = real; + } catch (error) { + if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') return reply(res, 403); + if (extname(pathname)) return reply(res, 404, 'Not found'); try { - const hostHeader=req.headers.host, origin=new URL(req.headers.origin); - if (req.url.split('?')[0] !== '/connect' || !hostHeader || origin.host.toLowerCase() !== hostHeader.toLowerCase() || !['http:','https:'].includes(origin.protocol)) return reject(socket,403); - const connect=target.protocol==='https:' ? tls.connect : net.connect; - const u=connect(Number(target.port || (target.protocol==='https:'?443:80)),target.hostname,()=>{ - const headers={...req.headers,host:target.host}; delete headers.origin; - u.write(`GET ${req.url} HTTP/1.1\r\n${Object.entries(headers).map(([k,v])=>`${k}: ${v}`).join('\r\n')}\r\n\r\n`); if(head.length)u.write(head); u.pipe(socket); socket.pipe(u); - }); u.on('error',()=>socket.destroy()); socket.on('error',()=>u.destroy()); - } catch { reject(socket,403); } + file = await realpath(resolve(base, 'index.html')); + if (!inside(base, file)) return reply(res, 403); + } catch { return reply(res, 404, 'Not found'); } + } + try { + const body = await readFile(file); + res.writeHead(200, { ...noCache, 'Content-Type': mime[extname(file)] ?? 'application/octet-stream' }); + res.end(req.method === 'HEAD' ? undefined : body); + } catch { reply(res, 404, 'Not found'); } +} + +function upstreamRequest(target, options, callback) { + return (target.protocol === 'https:' ? httpsRequest : httpRequest)( + { protocol: target.protocol, hostname: target.hostname, port: target.port || undefined, + ...options, timeout: timeoutMs }, callback, + ); +} + +function proxy(req, res, target) { + const url = new URL(req.url, target); + const headers = { ...req.headers, host: target.host }; + delete headers.connection; + const upstream = upstreamRequest(target, { method: req.method, path: `${url.pathname}${url.search}`, headers }, (replyFromUpstream) => { + const forwarded = { ...replyFromUpstream.headers, ...noCache }; + res.writeHead(replyFromUpstream.statusCode ?? 502, forwarded); + replyFromUpstream.on('error', () => res.destroy()); + replyFromUpstream.pipe(res); }); - await new Promise((ok,fail)=>{server.once('error',fail);server.listen(port,host,ok)}); - return { server, port:server.address().port, close:()=>new Promise((ok,fail)=>server.close(e=>e?fail(e):ok())) }; + upstream.setTimeout(timeoutMs, () => upstream.destroy(new Error('upstream timeout'))); + upstream.on('error', () => reply(res, 502, 'Upstream unavailable')); + req.on('aborted', () => upstream.destroy()); + res.on('close', () => { if (!res.writableEnded) upstream.destroy(); }); + if (req.method === 'GET' || req.method === 'HEAD') { req.resume(); upstream.end(); } + else req.pipe(upstream); } -function reject(socket,status){socket.end(`HTTP/1.1 ${status} Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`)} -function proxy(req,res,target){ - const url=new URL(req.url,target); fetch(url,{method:req.method,headers:{cookie:req.headers.cookie??'',...(req.headers['content-type']?{'content-type':req.headers['content-type']}:{})},body:['GET','HEAD'].includes(req.method)?undefined:req,duplex:'half',redirect:'manual'}).then(async r=>{res.writeHead(r.status,{...Object.fromEntries(r.headers),...noCache});res.end(Buffer.from(await r.arrayBuffer()))}).catch(()=>response(res,502,'Upstream unavailable')); + +function authCheck(req, target, callback) { + let completed = false; + const finish = (result) => { + if (completed) return; + completed = true; + callback(result); + }; + const check = upstreamRequest(target, { method: 'GET', path: '/', headers: { + cookie: req.headers.cookie ?? '', accept: 'text/html', 'accept-encoding': 'identity', + } }, (response) => { + response.resume(); + finish(response.statusCode === 200); + }); + check.setTimeout(timeoutMs, () => check.destroy(new Error('authentication check timeout'))); + check.on('error', () => finish(null)); + req.on('aborted', () => check.destroy()); + req.socket.once('close', () => { if (!completed) check.destroy(); }); + check.end(); } + +function reject(socket, status, phrase = 'Forbidden') { + if (!socket.destroyed) socket.end(`HTTP/1.1 ${status} ${phrase}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`); +} + +export async function start({ root = resolve('build/web'), upstream = 'http://127.0.0.1:8095', host = '127.0.0.1', port = 8080 } = {}) { + const base = await realpath(root); + const target = new URL(upstream); + if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password) throw new Error('UPSTREAM must be credential-free HTTP(S)'); + const sockets = new Set(); + const upgrades = new Set(); + let closing = false; + let closePromise; + const server = createServer((req, res) => { + let url; + try { + url = new URL(req.url, 'http://preview'); + if (!req.url.startsWith('/') || req.url.startsWith('//')) throw new Error('invalid path'); + decodeURIComponent(url.pathname); + } catch { return reply(res, 400, 'Bad request'); } + const pathname = decodeURIComponent(url.pathname); + if (pathname.startsWith('//')) return reply(res, 400, 'Bad request'); + if (!['GET', 'HEAD', 'POST'].includes(req.method)) { + res.setHeader('Allow', 'GET, HEAD, POST'); return reply(res, 405); + } + if (pathname === '/login' || pathname === '/logout' || pathname.startsWith('/artifacts/')) return proxy(req, res, target); + if (req.method !== 'GET' && req.method !== 'HEAD') return reply(res, 405); + authCheck(req, target, (authenticated) => { + if (res.destroyed) return; + if (authenticated === null) return reply(res, 502, 'Authentication upstream unavailable'); + if (!authenticated) { + if (req.method === 'GET' && String(req.headers.accept ?? '').includes('text/html') && !pathname.startsWith('/assets/')) { + res.writeHead(302, { ...noCache, Location: `/login?next=${encodeURIComponent(`${url.pathname}${url.search}`)}` }); + return res.end(); + } + return reply(res, 401, 'Authentication required'); + } + staticFile(base, pathname, req, res); + }); + }); + server.on('connection', (socket) => { + sockets.add(socket); + socket.on('close', () => sockets.delete(socket)); + }); + server.on('upgrade', (req, socket, head) => { + upgrades.add(socket); + socket.on('close', () => upgrades.delete(socket)); + let origin; + try { + if (req.url.split('?')[0] !== '/connect' || !req.headers.host || !req.headers.origin || !req.url.startsWith('/')) throw new Error(); + origin = new URL(req.headers.origin); + if (!['http:', 'https:'].includes(origin.protocol) || origin.host.toLowerCase() !== req.headers.host.toLowerCase()) throw new Error(); + } catch { return reject(socket, 403); } + authCheck(req, target, (authenticated) => { + if (closing || socket.destroyed) return; + if (authenticated === null) return reject(socket, 502, 'Bad Gateway'); + if (!authenticated) return reject(socket, 401, 'Unauthorized'); + const connect = target.protocol === 'https:' ? tls.connect : net.connect; + const upstreamSocket = connect({ host: target.hostname, port: Number(target.port || (target.protocol === 'https:' ? 443 : 80)), ...(target.protocol === 'https:' ? { servername: target.hostname } : {}) }); + upgrades.add(upstreamSocket); + upstreamSocket.on('close', () => upgrades.delete(upstreamSocket)); + upstreamSocket.setTimeout(timeoutMs, () => upstreamSocket.destroy(new Error('upgrade timeout'))); + upstreamSocket.once(target.protocol === 'https:' ? 'secureConnect' : 'connect', () => { + const headers = { ...req.headers, host: target.host, origin: target.origin }; + const lines = Object.entries(headers).filter(([, value]) => value != null) + .map(([key, value]) => `${key}: ${Array.isArray(value) ? value.join(', ') : value}`).join('\r\n'); + upstreamSocket.write(`GET ${req.url} HTTP/1.1\r\n${lines}\r\n\r\n`); + if (head.length) upstreamSocket.write(head); + upstreamSocket.pipe(socket); + socket.pipe(upstreamSocket); + }); + upstreamSocket.on('error', () => socket.destroy()); + socket.on('error', () => upstreamSocket.destroy()); + socket.on('close', () => upstreamSocket.destroy()); + }); + }); + await new Promise((resolveListen, rejectListen) => { + server.once('error', rejectListen); + server.listen(port, host, resolveListen); + }); + return { + server, port: server.address().port, + close: () => closePromise ??= new Promise((resolveClose, rejectClose) => { + closing = true; + for (const socket of upgrades) socket.destroy(); + server.close((error) => error ? rejectClose(error) : resolveClose()); + for (const socket of sockets) socket.destroy(); + }), + }; +} + if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) { - const args=Object.fromEntries(process.argv.slice(2).reduce((a,v,i,x)=>{if(v.startsWith('--'))a.push([v.slice(2),x[i+1]]);return a},[])); - start({root:args.root??'build/web',upstream:process.env.UPSTREAM??args.upstream??'http://127.0.0.1:8095',host:args.host??'127.0.0.1',port:Number(args.port??8080)}).then(s=>console.log(`preview http://${args.host??'127.0.0.1'}:${s.port}`)).catch(e=>{console.error(e);process.exitCode=1}); + const args = Object.fromEntries(process.argv.slice(2).reduce((result, value, index, all) => { + if (value.startsWith('--')) result.push([value.slice(2), all[index + 1]]); + return result; + }, [])); + start({ root: args.root ?? 'build/web', upstream: process.env.UPSTREAM ?? args.upstream ?? 'http://127.0.0.1:8095', host: args.host ?? '127.0.0.1', port: Number(args.port ?? 8080) }) + .then((preview) => console.log(`preview http://${args.host ?? '127.0.0.1'}:${preview.port}`)) + .catch((error) => { console.error(error); process.exitCode = 1; }); } From 1515ebee990e1db31cc365a03d24be30ecc0d304 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:34:56 +0100 Subject: [PATCH 10/84] fix flutter runs foundation parity gaps --- .../features/runs/data/runs_repository.dart | 105 ++++++++ .../features/runs/domain/run_decisions.dart | 110 ++++++++ app/lib/features/runs/domain/run_events.dart | 242 ++++++++++++++++-- app/lib/features/runs/domain/run_models.dart | 222 ++++++++++++++-- .../runs/domain/run_step_evidence.dart | 142 ++++++++++ app/notes/F3.md | 26 +- .../features/runs/run_decisions_test.dart | 87 +++++++ .../features/runs/runs_foundation_test.dart | 228 +++++++++++++---- .../features/runs/runs_repository_test.dart | 163 ++++++++++++ 9 files changed, 1229 insertions(+), 96 deletions(-) create mode 100644 app/lib/features/runs/data/runs_repository.dart create mode 100644 app/lib/features/runs/domain/run_decisions.dart create mode 100644 app/lib/features/runs/domain/run_step_evidence.dart create mode 100644 app/test/features/runs/run_decisions_test.dart create mode 100644 app/test/features/runs/runs_repository_test.dart diff --git a/app/lib/features/runs/data/runs_repository.dart b/app/lib/features/runs/data/runs_repository.dart new file mode 100644 index 00000000..5a1ea8c4 --- /dev/null +++ b/app/lib/features/runs/data/runs_repository.dart @@ -0,0 +1,105 @@ +import '../../../core/api_gateway.dart'; +import '../domain/run_models.dart'; + +/// Protocol failure kept separate from transport errors; server error envelopes +/// are otherwise propagated unchanged by [ApiGateway]. +class RunsRepositoryException implements Exception { + const RunsRepositoryException(this.message); + final String message; + @override + String toString() => message; +} + +/// Run protocol requests over the application's shared gateway. +class RunsRepository { + RunsRepository(this._gateway); + final ApiGateway _gateway; + + Future listRuns() async { + final reply = await _gateway.call('list_runs'); + final runs = reply['runs']; + return RunListResult( + runs is List + ? runs + .whereType() + .map((r) => Map.from(r)) + .toList() + : const [], + reply['usage'] is Map + ? Map.from(reply['usage'] as Map) + : null, + ); + } + + Future getRun(num id) async => + _required(await _gateway.call('get_run', {'run_id': id}), 'run_detail'); + Future cancelRun(num id) async => _required( + await _gateway.call('cancel_run', {'run_id': id}), + 'run_detail', + ); + + Future retryRun( + num id, { + required String requestKey, + String? mode, + }) async { + final fields = {'run_id': id, 'request_key': requestKey}; + if (mode == 'restart') fields['retry_mode'] = mode; + return _required(await _gateway.call('retry_run', fields), 'run_detail'); + } + + Future decideRun( + num id, { + String? stage, + required String option, + String feedback = '', + }) async { + final selected = option.trim(); + if (selected.isEmpty) { + throw const RunsRepositoryException( + 'Choose an option before continuing.', + ); + } + final fields = {'run_id': id, 'option': selected}; + if (stage != null && stage.trim().isNotEmpty) fields['stage'] = stage; + if (feedback.trim().isNotEmpty) fields['feedback'] = feedback.trim(); + return _required(await _gateway.call('decide_run', fields), 'run_detail'); + } + + Future setRunTitle(num id, String title) async => _required( + await _gateway.call('set_run_title', {'run_id': id, 'title': title}), + 'run_detail', + ); + + Future startRun({ + required num pipelineId, + required num version, + required String prompt, + required String workspace, + required String requestKey, + String title = '', + String outputFormat = '', + String notifyMode = 'auto', + }) async { + final fields = { + 'pipeline_id': pipelineId, + 'version': version, + 'request_key': requestKey, + 'workspace': workspace.trim(), + 'input': {'prompt': prompt}, + }; + if (title.trim().isNotEmpty) fields['title'] = title.trim(); + if (outputFormat.isNotEmpty) fields['output_format'] = outputFormat; + final mode = notifyMode.trim().toLowerCase(); + if (mode == 'on' || mode == 'off') fields['notify_mode'] = mode; + return _required(await _gateway.call('run_pipeline', fields), 'run_detail'); + } + + JsonMap _required(JsonMap reply, String key) { + final value = reply[key]; + if (value is! Map) { + throw RunsRepositoryException('The server returned no $key.'); + } + return Map.from(value); + } +} diff --git a/app/lib/features/runs/domain/run_decisions.dart b/app/lib/features/runs/domain/run_decisions.dart new file mode 100644 index 00000000..339508e6 --- /dev/null +++ b/app/lib/features/runs/domain/run_decisions.dart @@ -0,0 +1,110 @@ +import '../../../core/api_gateway.dart'; +import 'run_models.dart'; + +class PendingDecision { + const PendingDecision({ + required this.runId, + required this.runLabel, + required this.stageKey, + required this.instructions, + required this.options, + }); + final num runId; + final String runLabel; + final String stageKey; + final String instructions; + final List options; +} + +JsonMap? lastWaitingStep(List steps) { + for (final value in steps.reversed) { + if (value is Map && value['status'] == 'waiting') { + return Map.from(value); + } + } + return null; +} + +String waitingPrompt(dynamic output) => + output is Map && output['prompt'] is String + ? output['prompt'] as String + : ''; + +List waitingOptions(dynamic output) { + final options = output is Map ? output['options'] : null; + if (options is! List) return const []; + return options + .whereType() + .where((entry) => entry.trim().isNotEmpty) + .toList(); +} + +List humanOptions(dynamic edges) { + if (edges is! Map) return const []; + return edges.keys.map((key) => '$key').where((key) => key != 'error').toList() + ..sort(); +} + +PendingDecision? pendingDecision(JsonMap? run) { + if (run == null || + run['status'] != 'waiting' || + _positive(run['export_pending_sequence'])) { + return null; + } + final steps = run['steps'] is List ? run['steps'] as List : const []; + final step = lastWaitingStep(steps); + final stage = _string(step?['stage']).trim().isNotEmpty + ? _string(step?['stage']) + : _string(run['current_stage']); + if (stage.trim().isEmpty) return null; + JsonMap? declaration; + final graph = run['graph']; + final graphStages = graph is Map ? graph['stages'] : null; + if (graphStages is List) { + for (final value in graphStages.whereType()) { + if (value['key'] == stage) { + declaration = Map.from(value); + break; + } + } + } + if (declaration?['type'] != null && declaration!['type'] != 'human') { + return null; + } + final edges = declaration?['edges']; + final options = waitingOptions(step?['output']); + final keys = options.isNotEmpty ? options : humanOptions(edges); + if (keys.isEmpty) return null; + final instructions = waitingPrompt(step?['output']).trim().isNotEmpty + ? waitingPrompt(step?['output']) + : _string(declaration?['prompt']); + return PendingDecision( + runId: run['id'] is num ? run['id'] as num : 0, + runLabel: runIdentity(run['title'], run['name']).label, + stageKey: stage, + instructions: instructions, + options: keys + .map( + (key) => DecisionOption( + key, + target: _targetLabel(key, edges is Map ? edges[key] : null), + ), + ) + .toList(), + ); +} + +String _targetLabel(String option, dynamic target) { + if (target == null || '$target'.trim().isEmpty) return ''; + final resolved = target == '#' + ? (option == 'error' ? '#failure' : '#success') + : '$target'; + return switch (resolved) { + '#success' => 'SUCCESS', + '#failure' => 'FAILURE', + _ => resolved, + }; +} + +bool _positive(dynamic value) => value is num && value > 0; +String _string(dynamic value) => value == null ? '' : '$value'; diff --git a/app/lib/features/runs/domain/run_events.dart b/app/lib/features/runs/domain/run_events.dart index 5462d217..3ce3bc87 100644 --- a/app/lib/features/runs/domain/run_events.dart +++ b/app/lib/features/runs/domain/run_events.dart @@ -1,24 +1,226 @@ import '../../../core/api_gateway.dart'; -const _terminal = {'succeeded','failed','canceled','interrupted'}; -int _rank(dynamic s) => s == 'queued' ? 0 : {'running','waiting'}.contains(s) ? 1 : _terminal.contains(s) ? 2 : -1; -int _stepRank(dynamic s) => {'running','waiting'}.contains(s) ? 1 : {'completed','failed','canceled','interrupted'}.contains(s) ? 2 : -1; -bool _stale(dynamic a, dynamic b, int Function(dynamic) rank) => '${b ?? ''}'.trim().isNotEmpty && rank(a) >= 0 && rank(b) >= 0 && (rank(b) < rank(a) || (rank(a) == 2 && rank(b) == 2 && a != b)); -String _advance(dynamic a, dynamic b, int Function(dynamic) rank) => '${b ?? ''}'.trim().isEmpty || rank(b) < rank(a) || (rank(a) == 2 && rank(b) == 2) ? '${a ?? ''}' : '${b ?? ''}'; -({List runs, bool needsResync}) foldRunEvent(List runs, JsonMap frame) { - final id = frame['run_id']; if (id is! num || id <= 0) return (runs:runs, needsResync:false); - final i = runs.indexWhere((r) => r['id'] == id); - if (i < 0) { final pid=frame['pipeline_id']; final name=frame['name']; if (pid is! num || '${name ?? ''}'.trim().isEmpty) return (runs:runs, needsResync:true); - return (runs:[{'id':id,'pipeline_id':pid,'name':name,'title':frame['title'],'version':frame['version'] ?? 0,'status':frame['status'] ?? '', 'executing':true,'completed_steps':frame['completed_steps'] ?? 0,'created_at':frame['created_at'] ?? '', 'finished_at':frame['finished_at'] ?? '', 'resource_wait':frame['resource_wait']}, ...runs], needsResync:false); } - final current=runs[i]; if (_stale(current['status'],frame['status'],_rank) && frame['resource_wait_set'] != true) return (runs:runs, needsResync:false); - final status=frame['resource_wait_set']==true && frame['status']=='queued' && !_terminal.contains(current['status']) ? 'queued' : _advance(current['status'],frame['status'],_rank); - final updated={...current,'status':status,'executing':status=='queued'||status=='running','completed_steps':(((current['completed_steps'] as num?)??0).toInt()).clamp(((frame['completed_steps'] as num?)??0).toInt(),0x7fffffff),'resource_wait':_terminal.contains(status)?null:frame['resource_wait_set']==true?frame['resource_wait']:current['resource_wait']}; - for(final k in ['outcome','current_stage','finished_at','created_at']) { if ('${frame[k]??''}'.trim().isNotEmpty) updated[k]=frame[k]; } - final next=[...runs]; next[i]=updated; return (runs:next,needsResync:false); +import 'run_step_evidence.dart'; + +const terminalRunStatuses = {'succeeded', 'failed', 'canceled', 'interrupted'}; + +bool isTerminalRunStatus(dynamic status) => + terminalRunStatuses.contains(_word(status)); +bool isWaitingRunStatus(dynamic status) => _word(status) == 'waiting'; + +int runLifecycleRank(dynamic status) => switch (_word(status)) { + 'queued' => 0, + 'running' || 'waiting' => 1, + 'succeeded' || 'failed' || 'canceled' || 'interrupted' => 2, + _ => -1, +}; + +int stepLifecycleRank(dynamic status) => switch (_word(status)) { + 'running' || 'waiting' => 1, + 'completed' || 'failed' || 'canceled' || 'interrupted' => 2, + _ => -1, +}; + +bool _stale(dynamic current, dynamic incoming, int Function(dynamic) rank) { + if (_word(incoming).isEmpty) return false; + final oldRank = rank(current); + final newRank = rank(incoming); + return oldRank >= 0 && + newRank >= 0 && + (newRank < oldRank || + (oldRank == 2 && newRank == 2 && incoming != current)); } -bool runDetailNeedsFullSync(JsonMap f) => _terminal.contains(f['status']) || f['status']=='waiting' || f['cancel_requested']==true || f['cleanup_unconfirmed']==true || f['step']?['status']=='waiting' || _stepRank(f['step']?['status'])==2; + +String _advance(dynamic current, dynamic incoming, int Function(dynamic) rank) { + if (_word(incoming).isEmpty || incoming == current) return '${current ?? ''}'; + final oldRank = rank(current); + final newRank = rank(incoming); + if (oldRank < 0) return '$incoming'; + if (newRank < 0 || (oldRank == 2 && newRank == 2) || newRank < oldRank) { + return '${current ?? ''}'; + } + return '$incoming'; +} + +bool executingFor(dynamic status, bool current) => switch (_word(status)) { + 'queued' || 'running' => true, + 'waiting' || 'succeeded' || 'failed' || 'canceled' || 'interrupted' => false, + _ => current, +}; + +bool _blank(dynamic value) => '${value ?? ''}'.trim().isEmpty; + +JsonMap _scheduleOrigin(JsonMap current, JsonMap frame) { + final oldId = _positiveInt(current['schedule_id']); + final newId = _positiveInt(frame['schedule_id']); + final known = + current.containsKey('scheduled') || + frame.containsKey('scheduled') || + oldId > 0 || + newId > 0; + if (!known) return {}; + final id = oldId > 0 ? oldId : newId; + final nameConflict = oldId > 0 && newId > 0 && oldId != newId; + final name = + '${current['schedule_name'] ?? (nameConflict ? '' : frame['schedule_name'] ?? '')}'; + return { + 'scheduled': + current['scheduled'] == true || frame['scheduled'] == true || id > 0, + if (id > 0) 'schedule_id': id, + if (name.isNotEmpty) 'schedule_name': name, + }; +} + +int _positiveInt(dynamic value) => + value is num && value > 0 ? value.toInt() : 0; + +JsonMap _mergeRunFields(JsonMap current, JsonMap frame) { + if (_stale(current['status'], frame['status'], runLifecycleRank) && + frame['resource_wait_set'] != true) { + return current; + } + final beforeStatus = '${current['status'] ?? ''}'; + final status = + frame['resource_wait_set'] == true && + frame['status'] == 'queued' && + !isTerminalRunStatus(beforeStatus) + ? 'queued' + : _advance(beforeStatus, frame['status'], runLifecycleRank); + final merged = { + ...current, + ..._scheduleOrigin(current, frame), + 'status': status, + 'executing': executingFor(status, current['executing'] == true), + 'completed_steps': _maxInt( + current['completed_steps'], + frame['completed_steps'], + ), + 'resource_wait': isTerminalRunStatus(status) + ? null + : frame['resource_wait_set'] == true + ? frame['resource_wait'] + : current['resource_wait'], + 'notify_mode': _blank(frame['notify_mode']) + ? current['notify_mode'] ?? 'auto' + : frame['notify_mode'], + 'cancel_requested': + current['cancel_requested'] == true || + frame['cancel_requested'] == true, + 'cleanup_unconfirmed': + current['cleanup_unconfirmed'] == true || + frame['cleanup_unconfirmed'] == true, + }; + for (final key in ['outcome', 'current_stage', 'created_at', 'finished_at']) { + if (!_blank(frame[key])) merged[key] = frame[key]; + } + final oldExport = _positiveInt(current['export_pending_sequence']); + if (oldExport > 0 || frame.containsKey('export_pending_sequence')) { + merged['export_pending_sequence'] = _blank(frame['status']) + ? oldExport + : status == 'waiting' + ? _positiveInt(frame['export_pending_sequence']) + : 0; + } + if (current['steps'] is! List) { + final evidence = mergeGraphEvidence( + current['graph_evidence'] as JsonMap?, + frame, + ); + if (evidence != null) merged['graph_evidence'] = evidence; + } + return merged; +} + +int _maxInt(dynamic a, dynamic b) => + (a is num ? a.toInt() : 0).clamp(b is num ? b.toInt() : 0, 0x7fffffff); + +/// A summary row can be built from a sufficiently identified push; otherwise +/// the caller must resync from the server's authoritative list. +JsonMap? newRunSummaryFromFrame(JsonMap frame) { + final id = frame['run_id']; + final pipelineId = frame['pipeline_id']; + if (id is! num || + id <= 0 || + pipelineId is! num || + pipelineId <= 0 || + _blank(frame['name'])) { + return null; + } + final row = { + 'id': id, + 'pipeline_id': pipelineId, + 'name': frame['name'], + 'title': _blank(frame['title']) ? null : frame['title'], + 'version': frame['version'] ?? 0, + 'notify_mode': frame['notify_mode'] ?? 'auto', + 'status': frame['status'] ?? '', + 'executing': executingFor(frame['status'], true), + 'completed_steps': _maxInt(0, frame['completed_steps']), + 'created_at': frame['created_at'] ?? '', + 'finished_at': frame['finished_at'] ?? '', + 'outcome': frame['outcome'] ?? '', + 'current_stage': frame['current_stage'] ?? '', + 'resource_wait': frame['resource_wait'], + 'cancel_requested': frame['cancel_requested'] == true, + 'cleanup_unconfirmed': frame['cleanup_unconfirmed'] == true, + }; + row.addAll(_scheduleOrigin({}, frame)); + final sequence = _positiveInt(frame['export_pending_sequence']); + if (sequence > 0) row['export_pending_sequence'] = sequence; + final evidence = mergeGraphEvidence(null, frame); + if (evidence != null) row['graph_evidence'] = evidence; + return row; +} + +({List runs, bool needsResync}) foldRunEvent( + List runs, + JsonMap frame, +) { + final id = frame['run_id']; + if (id is! num || id <= 0) return (runs: runs, needsResync: false); + final index = runs.indexWhere((run) => run['id'] == id); + if (index < 0) { + final row = newRunSummaryFromFrame(frame); + return row == null + ? (runs: runs, needsResync: true) + : (runs: [row, ...runs], needsResync: false); + } + final updated = _mergeRunFields(runs[index], frame); + if (identical(updated, runs[index])) return (runs: runs, needsResync: false); + final next = [...runs]; + next[index] = updated; + return (runs: next, needsResync: false); +} + JsonMap? foldRunEventDetail(JsonMap? detail, JsonMap frame) { - if(detail==null || detail['id']!=frame['run_id'] || (_stale(detail['status'],frame['status'],_rank)&&frame['resource_wait_set']!=true)) return detail; - final folded=foldRunEvent([detail],frame).runs.single; final delta=frame['step']; - if(delta is Map) { final steps=List.from(detail['steps']??[]); final i=steps.indexWhere((s)=>s['sequence']==delta['sequence']); if(i<0){steps.add(Map.from(delta));steps.sort((a,b)=>((a['sequence'] as num?)??0).compareTo((b['sequence'] as num?)??0));} else if(!_stale(steps[i]['status'],delta['status'],_stepRank)){steps[i]={...steps[i],...Map.from(delta)};} folded['steps']=steps; } - return folded; + if (detail == null || detail['id'] != frame['run_id']) return detail; + if (_stale(detail['status'], frame['status'], runLifecycleRank) && + frame['resource_wait_set'] != true) { + return detail; + } + final merged = _mergeRunFields(detail, frame); + final steps = frame['step'] is Map + ? upsertRunStep( + detail['steps'] is List + ? (detail['steps'] as List) + .whereType() + .map((s) => Map.from(s)) + .toList() + : [], + Map.from(frame['step'] as Map), + ) + : detail['steps'] ?? []; + return {...merged, 'steps': steps}; } + +bool runDetailNeedsFullSync(JsonMap frame) { + final step = frame['step']; + final stepStatus = step is Map ? step['status'] : null; + return isTerminalRunStatus(frame['status']) || + isWaitingRunStatus(frame['status']) || + frame['cancel_requested'] == true || + frame['cleanup_unconfirmed'] == true || + isWaitingRunStatus(stepStatus) || + stepLifecycleRank(stepStatus) == 2; +} + +String _word(dynamic value) => '${value ?? ''}'.trim().toLowerCase(); diff --git a/app/lib/features/runs/domain/run_models.dart b/app/lib/features/runs/domain/run_models.dart index 5fe96a56..0c2ff344 100644 --- a/app/lib/features/runs/domain/run_models.dart +++ b/app/lib/features/runs/domain/run_models.dart @@ -1,33 +1,217 @@ import '../../../core/api_gateway.dart'; -const runStates = ['queued', 'running', 'waiting', 'succeeded', 'failed', 'canceled', 'interrupted']; +const runStates = [ + 'queued', + 'running', + 'waiting', + 'succeeded', + 'failed', + 'canceled', + 'interrupted', +]; + ({String label, String? pipeline}) runIdentity(dynamic title, dynamic name) { final stored = '${title ?? ''}'.trim(); - return (label: stored.isNotEmpty ? stored : '${name ?? ''}', pipeline: stored.isNotEmpty ? '${name ?? ''}' : null); + return ( + label: stored.isNotEmpty ? stored : '${name ?? ''}', + pipeline: stored.isNotEmpty ? '${name ?? ''}' : null, + ); } -String runStateOf(dynamic status) => switch ('${status ?? ''}'.trim().toLowerCase()) { - 'queued' || 'running' || 'waiting' || 'active' || 'blocked' || 'skipped' => '${status ?? ''}'.trim().toLowerCase(), - 'succeeded' || 'success' || 'completed' || 'done' => 'succeeded', - 'failed' || 'error' => 'failed', 'canceled' || 'cancelled' => 'canceled', 'interrupted' => 'interrupted', _ => 'unknown', -}; -List filterRuns(List runs, {Set statuses = const {}, int? pipelineId}) => runs.where((r) => (statuses.isEmpty || statuses.contains(runStateOf(r['status']))) && (pipelineId == null || r['pipeline_id'] == pipelineId)).toList(); + +String runStateOf(dynamic status) => + switch ('${status ?? ''}'.trim().toLowerCase()) { + 'queued' || + 'running' || + 'waiting' || + 'active' || + 'blocked' || + 'skipped' => '${status ?? ''}'.trim().toLowerCase(), + 'succeeded' || 'success' || 'completed' || 'done' => 'succeeded', + 'failed' || 'error' => 'failed', + 'canceled' || 'cancelled' => 'canceled', + 'interrupted' => 'interrupted', + _ => 'unknown', + }; + +List filterRuns( + List runs, { + Set statuses = const {}, + int? pipelineId, + String timeRange = 'any_time', + String scheduled = 'any', + DateTime? today, +}) => runs.where((run) { + if (statuses.isNotEmpty && !statuses.contains(runStateOf(run['status']))) { + return false; + } + if (pipelineId != null && run['pipeline_id'] != pipelineId) { + return false; + } + if (scheduled == 'scheduled' && !_isScheduled(run)) { + return false; + } + if (scheduled == 'unscheduled' && + (run['scheduled'] != false || _isScheduled(run))) { + return false; + } + if (timeRange == 'any_time' || timeRange.isEmpty) { + return true; + } + final created = DateTime.tryParse('${run['created_at'] ?? ''}')?.toLocal(); + if (created == null) { + return false; + } + final now = today ?? DateTime.now(); + final start = DateTime(now.year, now.month, now.day); + final date = DateTime(created.year, created.month, created.day); + if (date.isAfter(start)) { + return false; + } + final days = switch (timeRange) { + 'today' => 0, + 'last_7_days' => 6, + 'last_30_days' => 29, + _ => null, + }; + return days == null || !date.isBefore(start.subtract(Duration(days: days))); +}).toList(); + +bool _isScheduled(JsonMap run) => + run['scheduled'] == true || + (run['schedule_id'] is num && (run['schedule_id'] as num) > 0); + +String runStatusLabel(JsonMap run) { + final status = '${run['status'] ?? ''}'; + if (!{'queued', 'running', 'waiting'}.contains(status)) { + return status.isEmpty ? 'unknown' : status; + } + if (run['cleanup_unconfirmed'] == true) { + return 'Cleanup unconfirmed — workspace reserved'; + } + if (run['cancel_requested'] == true) { + return 'Stopping — waiting for execution to stop'; + } + if (status == 'waiting' && + (run['export_pending_sequence'] as num? ?? 0) > 0) { + return 'Waiting for session export'; + } + return status; +} + List sortRuns(List runs, {String sort = 'newest_first'}) { - int time(dynamic x) => DateTime.tryParse('${x ?? ''}')?.millisecondsSinceEpoch ?? -0x7fffffffffffffff; final result = [...runs]; - result.sort((a,b) { - final c = switch (sort) { 'oldest_first' => time(a['created_at']).compareTo(time(b['created_at'])), 'pipeline_name' => '${a['name'] ?? ''}'.toLowerCase().compareTo('${b['name'] ?? ''}'.toLowerCase()), 'status' => '${a['status'] ?? ''}'.compareTo('${b['status'] ?? ''}'), _ => time(b['created_at']).compareTo(time(a['created_at'])) }; - return c == 0 ? ((b['id'] as num?) ?? 0).compareTo((a['id'] as num?) ?? 0) : c; + int? instant(dynamic value) => + DateTime.tryParse('${value ?? ''}')?.millisecondsSinceEpoch; + int? duration(JsonMap run) { + final from = instant(run['created_at']); + final to = instant(run['finished_at']); + if (from == null || to == null || to < from) return null; + return (to - from) ~/ 1000; + } + + int cmp>(T a, T b) => a.compareTo(b); + result.sort((a, b) { + final at = instant(a['created_at']); + final bt = instant(b['created_at']); + int primary; + switch (sort) { + case 'oldest_first': + primary = cmp(at ?? 0x7fffffffffffffff, bt ?? 0x7fffffffffffffff); + break; + case 'longest_duration': + primary = cmp(duration(a) == null ? 1 : 0, duration(b) == null ? 1 : 0); + if (primary == 0) primary = cmp(duration(b) ?? -1, duration(a) ?? -1); + if (primary == 0) { + primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff); + } + break; + case 'shortest_duration': + primary = cmp(duration(a) == null ? 1 : 0, duration(b) == null ? 1 : 0); + if (primary == 0) { + primary = cmp( + duration(a) ?? 0x7fffffffffffffff, + duration(b) ?? 0x7fffffffffffffff, + ); + } + if (primary == 0) { + primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff); + } + break; + case 'pipeline_name': + primary = '${a['name'] ?? ''}'.toLowerCase().compareTo( + '${b['name'] ?? ''}'.toLowerCase(), + ); + if (primary == 0) { + primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff); + } + break; + case 'status': + primary = '${a['status'] ?? ''}'.toLowerCase().compareTo( + '${b['status'] ?? ''}'.toLowerCase(), + ); + if (primary == 0) { + primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff); + } + break; + default: + primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff); + } + return primary == 0 + ? ((b['id'] as num?) ?? 0).compareTo((a['id'] as num?) ?? 0) + : primary; }); return result; } + /// Null usage means unsupported/unavailable, not zero. -class RunListResult { const RunListResult(this.runs, this.usage); final List runs; final JsonMap? usage; } -class DecisionOption { const DecisionOption(this.key, {this.target = ''}); final String key; final String target; } -class DecisionDraft { const DecisionDraft({this.selected, this.feedback = ''}); final String? selected; final String feedback; bool get canSubmit => selected != null && selected!.trim().isNotEmpty; } +class RunListResult { + const RunListResult(this.runs, this.usage); + final List runs; + final JsonMap? usage; +} + +class DecisionOption { + const DecisionOption(this.key, {this.target = ''}); + final String key; + final String target; +} + +class DecisionDraft { + const DecisionDraft({this.selected, this.feedback = ''}); + final String? selected; + final String feedback; + bool get canSubmit => selected != null && selected!.trim().isNotEmpty; + DecisionDraft select(String option) => + DecisionDraft(selected: option, feedback: feedback); + DecisionDraft withFeedback(String value) => + DecisionDraft(selected: selected, feedback: value); +} + String attentionKey(num runId, String kind) => '$runId:$kind'; -List orderAttention(List runs, {Set dismissed = const {}}) { - final result = runs.where((r) => ['waiting','failed'].contains(r['status']) && !dismissed.contains(attentionKey(r['id'] as num, r['status'] == 'waiting' ? 'Decision' : 'Failed'))).toList(); - int at(JsonMap r) => DateTime.tryParse('${r['finished_at'] ?? r['created_at'] ?? ''}')?.millisecondsSinceEpoch ?? 0; - result.sort((a,b) { final rank = (a['status'] == 'waiting' ? 0 : 1).compareTo(b['status'] == 'waiting' ? 0 : 1); if (rank != 0) return rank; final date = at(b).compareTo(at(a)); return date != 0 ? date : (b['id'] as num).compareTo(a['id'] as num); }); + +List orderAttention( + List runs, { + Set dismissed = const {}, +}) { + final result = runs.where((run) { + final waiting = run['status'] == 'waiting'; + if (waiting && (run['export_pending_sequence'] as num? ?? 0) > 0) { + return false; + } + final kind = waiting ? 'Decision' : 'Failed'; + return (waiting || run['status'] == 'failed') && + !dismissed.contains(attentionKey(run['id'] as num, kind)); + }).toList(); + String recency(JsonMap run) => '${run['finished_at'] ?? ''}'.trim().isNotEmpty + ? '${run['finished_at']}' + : '${run['created_at'] ?? ''}'; + result.sort((a, b) { + final rank = (a['status'] == 'waiting' ? 0 : 1).compareTo( + b['status'] == 'waiting' ? 0 : 1, + ); + if (rank != 0) return rank; + final date = recency(b).compareTo(recency(a)); + return date != 0 ? date : (b['id'] as num).compareTo(a['id'] as num); + }); return result; } diff --git a/app/lib/features/runs/domain/run_step_evidence.dart b/app/lib/features/runs/domain/run_step_evidence.dart new file mode 100644 index 00000000..f4fdb710 --- /dev/null +++ b/app/lib/features/runs/domain/run_step_evidence.dart @@ -0,0 +1,142 @@ +import '../../../core/api_gateway.dart'; + +/// Merge a visit by sequence without allowing stale status or blank sparse +/// deltas to erase evidence already held by the detail cache. +List upsertRunStep(List steps, JsonMap delta) { + final sequence = delta['sequence'] is num + ? (delta['sequence'] as num).toInt() + : 0; + final index = steps.indexWhere((step) => step['sequence'] == sequence); + if (index < 0) { + final result = [...steps, _stepFields({}, delta, sequence)]; + result.sort( + (a, b) => ((a['sequence'] as num?) ?? 0).compareTo( + (b['sequence'] as num?) ?? 0, + ), + ); + return result; + } + final old = steps[index]; + final incomingStatus = '${delta['status'] ?? ''}'; + final oldStatus = '${old['status'] ?? ''}'; + if (_stale(oldStatus, incomingStatus)) return steps; + final merged = _stepFields(old, delta, sequence); + if (_same(old, merged)) return steps; + final result = [...steps]; + result[index] = merged; + return result; +} + +JsonMap _stepFields(JsonMap old, JsonMap delta, int sequence) { + final oldStatus = '${old['status'] ?? ''}'; + final incoming = '${delta['status'] ?? ''}'; + return { + ...old, + 'sequence': sequence, + for (final key in ['stage', 'outcome', 'target', 'diagnostic']) + key: _blank(delta[key]) ? old[key] ?? '' : delta[key], + 'status': _advance(oldStatus, incoming), + }; +} + +bool _stale(String old, String incoming) { + if (_blank(incoming)) return false; + final before = _rank(old); + final after = _rank(incoming); + return before >= 0 && + after >= 0 && + (after < before || (before == 2 && after == 2 && old != incoming)); +} + +String _advance(String old, String incoming) { + if (_blank(incoming)) return old; + final before = _rank(old); + final after = _rank(incoming); + if (before < 0 || (after >= 0 && after > before && before < 2)) { + return incoming; + } + if (before < 2 && after == before) return incoming; + return old; +} + +int _rank(String status) => switch (status.trim().toLowerCase()) { + 'running' || 'waiting' => 1, + 'completed' || 'failed' || 'canceled' || 'interrupted' => 2, + _ => -1, +}; + +bool _same(JsonMap a, JsonMap b) => + a.length == b.length && a.entries.every((e) => b[e.key] == e.value); + +/// Compact graph evidence is intentionally allowlisted. It retains latest +/// visit-by-stage and distinct outcome routes, not arbitrary frame diagnostics. +JsonMap? mergeGraphEvidence(JsonMap? current, JsonMap frame) { + final incomingEvidence = frame['graph_evidence']; + final graphVisits = frame['graph_visits']; + final step = frame['step']; + if (incomingEvidence is! Map && graphVisits is! List && step is! Map) { + return current; + } + var visits = []; + final oldVisits = current?['visits']; + if (oldVisits is List) { + visits = oldVisits + .whereType() + .map((v) => Map.from(v)) + .toList(); + } + final additions = []; + if (incomingEvidence is Map && incomingEvidence['visits'] is List) { + additions.addAll(incomingEvidence['visits'] as List); + } + if (graphVisits is List) additions.addAll(graphVisits); + if (step is Map) additions.add(step); + for (final item in additions.whereType()) { + final delta = Map.from(item); + visits = upsertRunStep(visits, { + 'sequence': delta['sequence'], + 'stage': delta['stage'], + 'status': delta['status'], + 'outcome': delta['outcome'], + 'target': delta['target'], + }); + } + final latestByStage = {}; + final routeSequence = {}; + for (final visit in visits) { + final sequence = (visit['sequence'] as num?)?.toInt() ?? 0; + final stage = '${visit['stage'] ?? ''}'; + latestByStage[stage] = sequence; + if (!_blank(visit['outcome']) && !_blank(visit['target'])) { + routeSequence['$stage\u0000${visit['outcome']}\u0000${visit['target']}'] = + sequence; + } + } + visits = visits + .where((visit) { + final sequence = (visit['sequence'] as num?)?.toInt() ?? 0; + final stage = '${visit['stage'] ?? ''}'; + final route = '$stage\u0000${visit['outcome']}\u0000${visit['target']}'; + return latestByStage[stage] == sequence || + routeSequence[route] == sequence; + }) + .map( + (visit) => { + for (final key in [ + 'sequence', + 'stage', + 'status', + 'outcome', + 'target', + ]) + key: visit[key], + }, + ) + .toList(); + final complete = + current?['complete'] == true || + (incomingEvidence is Map && incomingEvidence['complete'] == true); + return {'complete': complete, 'visits': visits}; +} + +bool _blank(dynamic value) => '${value ?? ''}'.trim().isEmpty; diff --git a/app/notes/F3.md b/app/notes/F3.md index 79954b60..687abed2 100644 --- a/app/notes/F3.md +++ b/app/notes/F3.md @@ -1,12 +1,22 @@ # F3 run foundation Public API: `run_models.dart` provides run identity/state/filter/sort helpers, -`RunListResult`, decision draft/option values, and attention ordering/identity. -`run_events.dart` provides monotonic list/detail event folds and -`runDetailNeedsFullSync`. `data/runs_repository.dart` provides `RunsRepository` -for list/get/cancel/retry/decide/title/start calls through the shared gateway. +status wording, `RunListResult`, decision draft/option values, and attention +ordering/identity. `run_decisions.dart` resolves recorded human options and +prompt evidence with graph fallback. `run_events.dart` and +`run_step_evidence.dart` provide monotonic list/detail folds, immutable schedule +origin, graph evidence, and `runDetailNeedsFullSync`. `data/runs_repository.dart` +provides list/get/cancel/retry/decide/title/start calls through the shared gateway. -Focused tests cover stale lifecycle deltas, explicit resource-wait clearing, -unknown usage versus zero, decision refusal, attention identity/order, and exact -retry/start fields. This is a nonvisual foundation; browser UI captures were not -applicable. Mobile targets are unverified. +Focused tests cover stale and terminal lifecycle deltas, resource-wait clearing, +sparse step preservation, sticky cancel/cleanup flags, schedule provenance, +export gating, pending-decision evidence, list/detail agreement, filters/sorts, +exact request fields and server refusals. The repository file is deliberately +tracked despite the repository's `data/` ignore rule. This is a nonvisual +foundation; browser UI captures were not applicable. Mobile targets are +unverified. + +This is not total web parity: date filtering uses Dart local-time conversion +rather than web's explicit IANA-zone/locale helpers; the complete attention +dismissal/persistence surface, retry key generation, and repository methods for +export repair/request-key reconciliation are not included in this foundation. diff --git a/app/test/features/runs/run_decisions_test.dart b/app/test/features/runs/run_decisions_test.dart new file mode 100644 index 00000000..2cb47b1c --- /dev/null +++ b/app/test/features/runs/run_decisions_test.dart @@ -0,0 +1,87 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/domain/run_decisions.dart'; +import 'package:pipelines_app/features/runs/domain/run_events.dart'; +import 'package:pipelines_app/features/runs/domain/run_models.dart'; + +void main() { + test( + 'scheduled origin is immutable and export pending blocks attention/decision', + () { + final rows = [ + { + 'id': 5, + 'status': 'waiting', + 'scheduled': true, + 'schedule_id': 12, + 'schedule_name': 'Nightly', + }, + ]; + final changed = foldRunEvent(rows, { + 'run_id': 5, + 'status': 'waiting', + 'scheduled': false, + 'schedule_id': 99, + 'schedule_name': 'Other', + 'export_pending_sequence': 4, + }); + expect(changed.runs.single['schedule_id'], 12); + expect(changed.runs.single['schedule_name'], 'Nightly'); + expect(changed.runs.single['scheduled'], true); + expect(orderAttention(changed.runs), isEmpty); + expect( + pendingDecision({ + ...changed.runs.single, + 'current_stage': 'human', + 'steps': [], + }), + isNull, + ); + }, + ); + + test( + 'pending decision uses recorded options then graph fallback and target labels', + () { + final run = { + 'id': 7, + 'status': 'waiting', + 'current_stage': 'human', + 'name': 'Build', + 'graph': { + 'stages': [ + { + 'key': 'human', + 'type': 'human', + 'prompt': 'Graph prompt', + 'edges': {'go': '#', 'error': '#', 'skip': 'finish'}, + }, + ], + }, + 'steps': [ + { + 'sequence': 1, + 'status': 'waiting', + 'stage': 'human', + 'output': { + 'prompt': 'Recorded prompt', + 'options': ['go'], + }, + }, + ], + }; + final decision = pendingDecision(run)!; + expect(decision.instructions, 'Recorded prompt'); + expect(decision.options.map((option) => option.key), ['go']); + expect(decision.options.single.target, 'SUCCESS'); + final fallback = pendingDecision({ + ...run, + 'steps': [ + {'status': 'waiting', 'stage': 'human', 'output': {}}, + ], + })!; + expect(fallback.instructions, 'Graph prompt'); + expect(fallback.options.map((option) => option.key), ['go', 'skip']); + }, + ); +} diff --git a/app/test/features/runs/runs_foundation_test.dart b/app/test/features/runs/runs_foundation_test.dart index 9ad8f833..df77eca0 100644 --- a/app/test/features/runs/runs_foundation_test.dart +++ b/app/test/features/runs/runs_foundation_test.dart @@ -1,59 +1,189 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/core/api_gateway.dart'; -import 'package:pipelines_app/features/runs/data/runs_repository.dart'; import 'package:pipelines_app/features/runs/domain/run_events.dart'; -import 'package:pipelines_app/features/runs/domain/run_models.dart'; - -class FakeGateway implements ApiGateway { - String? type; - JsonMap fields = {}; - JsonMap reply = {}; - @override - Future call(String type, [JsonMap fields = const {}]) async { - this.type = type; - this.fields = Map.of(fields); - return reply; - } - @override - Stream get frames => const Stream.empty(); -} void main() { - test('filter/sort identities and unknown usage remain distinct', () { - expect(runIdentity(' Report ', 'Build').label, 'Report'); - final rows = [{'id': 1, 'pipeline_id': 2, 'status': 'failed', 'created_at': '2024-01-01'}, {'id': 2, 'pipeline_id': 2, 'status': 'running', 'created_at': '2025-01-01'}]; - expect(filterRuns(rows, statuses: {'failed'}).single['id'], 1); - expect(sortRuns(rows).first['id'], 2); - expect(RunListResult(const [], null).usage, isNull); - }); + group('event fold', () { + test('terminal status and resource wait reset are monotonic', () { + final initial = [ + { + 'id': 1, + 'status': 'succeeded', + 'executing': false, + 'completed_steps': 4, + }, + ]; + final reset = foldRunEvent(initial, { + 'run_id': 1, + 'status': 'queued', + 'resource_wait_set': true, + 'resource_wait': null, + }); + expect(reset.runs.single['status'], 'succeeded'); + expect(reset.runs.single['executing'], false); + final competing = foldRunEvent(initial, { + 'run_id': 1, + 'status': 'failed', + 'resource_wait_set': true, + }); + expect(competing.runs.single['status'], 'succeeded'); + expect(competing.runs.single['resource_wait'], isNull); + }); - test('fold is monotonic and explicit resource wait clearing is honored', () { - final rows = [{'id': 1, 'status': 'running', 'completed_steps': 3, 'resource_wait': {'resource': 'gpu'}}]; - final stale = foldRunEvent(rows, {'run_id': 1, 'status': 'queued', 'completed_steps': 1}); - expect(stale.runs.single['status'], 'running'); - final cleared = foldRunEvent(rows, {'run_id': 1, 'status': 'queued', 'resource_wait_set': true, 'resource_wait': null}); - expect(cleared.runs.single['status'], 'queued'); - expect(cleared.runs.single['resource_wait'], isNull); - expect(cleared.runs.single['completed_steps'], 3); - expect(runDetailNeedsFullSync({'status': 'waiting'}), isTrue); - }); + test( + 'resource wait reset advances only nonterminal rows, even on stale status', + () { + final rows = [ + { + 'id': 2, + 'status': 'running', + 'executing': true, + 'resource_wait': {'resource': 'gpu'}, + 'completed_steps': 3, + }, + ]; + final result = foldRunEvent(rows, { + 'run_id': 2, + 'status': 'queued', + 'resource_wait_set': true, + 'resource_wait': null, + 'completed_steps': 1, + }); + expect(result.runs.single['status'], 'queued'); + expect(result.runs.single['resource_wait'], isNull); + expect(result.runs.single['completed_steps'], 3); + }, + ); - test('decision guard and attention dismissal identity', () { - expect(const DecisionDraft().canSubmit, isFalse); - expect(const DecisionDraft(selected: ' continue ').canSubmit, isTrue); - expect(attentionKey(7, 'Decision'), '7:Decision'); - final ordered = orderAttention([{'id': 8, 'status': 'failed'}, {'id': 7, 'status': 'waiting'}]); - expect(ordered.first['id'], 7); - }); + test( + 'new waiting and terminal rows are not executing; identity-less frame resyncs', + () { + for (final status in ['waiting', 'succeeded']) { + final result = foldRunEvent([], { + 'run_id': 8, + 'pipeline_id': 4, + 'name': 'Build', + 'status': status, + }); + expect(result.runs.single['executing'], false); + } + expect( + foldRunEvent([], {'run_id': 9, 'status': 'running'}).needsResync, + isTrue, + ); + }, + ); - test('repository emits exact action envelopes and requires idempotency key', () async { - final gateway = FakeGateway()..reply = {'run_detail': {'id': 3}}; - final repo = RunsRepository(gateway); - await repo.retryRun(3, requestKey: 'retry-1'); - expect(gateway.type, 'retry_run'); - expect(gateway.fields, {'run_id': 3, 'request_key': 'retry-1'}); - await repo.startRun(pipelineId: 4, version: 2, prompt: 'hello', workspace: ' /work ', requestKey: 'start-2'); - expect(gateway.fields, {'pipeline_id': 4, 'version': 2, 'request_key': 'start-2', 'workspace': '/work', 'input': {'prompt': 'hello'}}); - await expectLater(repo.decideRun(3, option: ' '), throwsA(isA())); + test( + 'blank sparse step fields preserve graph evidence and terminal visit', + () { + final detail = { + 'id': 1, + 'status': 'running', + 'steps': [ + { + 'sequence': 2, + 'stage': 'review', + 'status': 'completed', + 'outcome': 'approve', + 'target': 'publish', + 'diagnostic': 'kept', + }, + ], + }; + final next = foldRunEventDetail(detail, { + 'run_id': 1, + 'status': 'running', + 'step': { + 'sequence': 2, + 'stage': '', + 'status': 'running', + 'outcome': ' ', + 'target': '', + 'diagnostic': '', + }, + })!; + final step = (next['steps'] as List).single as JsonMap; + expect(step, containsPair('stage', 'review')); + expect(step, containsPair('status', 'completed')); + expect(step, containsPair('outcome', 'approve')); + expect(step, containsPair('target', 'publish')); + expect(step, containsPair('diagnostic', 'kept')); + }, + ); + + test( + 'cancel and cleanup flags stick; resource wait can clear; terminal clears it', + () { + final rows = [ + { + 'id': 3, + 'status': 'running', + 'resource_wait': {'resource': 'gpu'}, + }, + ]; + final first = foldRunEvent(rows, { + 'run_id': 3, + 'status': 'running', + 'cancel_requested': true, + 'cleanup_unconfirmed': true, + }); + final second = foldRunEvent(first.runs, { + 'run_id': 3, + 'status': 'running', + 'cancel_requested': false, + 'cleanup_unconfirmed': false, + 'resource_wait_set': true, + 'resource_wait': null, + }); + expect(second.runs.single['cancel_requested'], true); + expect(second.runs.single['cleanup_unconfirmed'], true); + expect(second.runs.single['resource_wait'], isNull); + final terminal = foldRunEvent(second.runs, { + 'run_id': 3, + 'status': 'failed', + }); + expect(terminal.runs.single['resource_wait'], isNull); + }, + ); + + test( + 'full sync triggers and list/detail folds agree across stale and current frames', + () { + expect(runDetailNeedsFullSync({'status': 'waiting'}), true); + expect( + runDetailNeedsFullSync({ + 'status': 'running', + 'step': {'status': 'completed'}, + }), + true, + ); + final summary = [ + {'id': 1, 'status': 'running', 'completed_steps': 1}, + ]; + final frame = { + 'run_id': 1, + 'status': 'succeeded', + 'completed_steps': 2, + 'outcome': 'done', + }; + final list = foldRunEvent(summary, frame).runs.single; + final detail = foldRunEventDetail({ + 'id': 1, + 'status': 'running', + 'completed_steps': 1, + 'steps': [], + }, frame)!; + expect(list['status'], detail['status']); + expect(list['completed_steps'], detail['completed_steps']); + final old = foldRunEventDetail(detail, { + 'run_id': 1, + 'status': 'running', + 'outcome': '', + })!; + expect(old['status'], 'succeeded'); + expect(old['outcome'], 'done'); + }, + ); }); } diff --git a/app/test/features/runs/runs_repository_test.dart b/app/test/features/runs/runs_repository_test.dart new file mode 100644 index 00000000..e6ee2164 --- /dev/null +++ b/app/test/features/runs/runs_repository_test.dart @@ -0,0 +1,163 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/data/runs_repository.dart'; +import 'package:pipelines_app/features/runs/domain/run_models.dart'; + +class FakeGateway implements ApiGateway { + String? type; + JsonMap fields = {}; + JsonMap reply = {}; + Object? failure; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + this.type = type; + this.fields = Map.of(fields); + if (failure case final error?) throw error; + return reply; + } + + @override + Stream get frames => const Stream.empty(); +} + +void main() { + test( + 'run models match identity, filtering, sorting and null usage behavior', + () { + expect(runIdentity(' Report ', 'Build').label, 'Report'); + final rows = [ + { + 'id': 1, + 'pipeline_id': 2, + 'status': 'failed', + 'created_at': '2024-01-01T00:00:00Z', + 'finished_at': '2024-01-01T00:00:10Z', + }, + { + 'id': 2, + 'pipeline_id': 2, + 'status': 'running', + 'created_at': '2025-01-01T00:00:00Z', + }, + ]; + expect(filterRuns(rows, statuses: {'failed'}).single['id'], 1); + expect(sortRuns(rows).first['id'], 2); + expect(sortRuns(rows, sort: 'shortest_duration').first['id'], 1); + final scheduled = [ + { + 'id': 3, + 'scheduled': true, + 'schedule_id': 9, + 'created_at': '2025-03-10T12:00:00Z', + }, + {'id': 4, 'scheduled': false, 'created_at': '2025-03-10T12:00:00Z'}, + {'id': 5, 'created_at': '2025-03-10T12:00:00Z'}, + ]; + expect( + filterRuns(scheduled, scheduled: 'scheduled').map((run) => run['id']), + [3], + ); + expect( + filterRuns( + scheduled, + scheduled: 'unscheduled', + timeRange: 'today', + today: DateTime(2025, 3, 10), + ).map((run) => run['id']), + [4], + ); + expect( + runStatusLabel({'status': 'waiting', 'export_pending_sequence': 2}), + 'Waiting for session export', + ); + expect(RunListResult(const [], null).usage, isNull); + }, + ); + + test('repository sends exact action and launch requests', () async { + final gateway = FakeGateway() + ..reply = { + 'run_detail': {'id': 3}, + }; + final repo = RunsRepository(gateway); + gateway.reply = { + 'runs': [ + {'id': 1, 'status': 'running'}, + ], + 'usage': {'active': 1}, + }; + final listed = await repo.listRuns(); + expect(gateway.type, 'list_runs'); + expect(gateway.fields, isEmpty); + expect(listed.runs.single['id'], 1); + expect(listed.usage, {'active': 1}); + gateway.reply = { + 'run_detail': {'id': 3}, + }; + await repo.retryRun(3, requestKey: 'retry-1'); + expect(gateway.type, 'retry_run'); + expect(gateway.fields, {'run_id': 3, 'request_key': 'retry-1'}); + await repo.retryRun(3, requestKey: 'retry-2', mode: 'restart'); + expect(gateway.fields, { + 'run_id': 3, + 'request_key': 'retry-2', + 'retry_mode': 'restart', + }); + await repo.decideRun(3, stage: 'human', option: ' go ', feedback: ' yes '); + expect(gateway.fields, { + 'run_id': 3, + 'stage': 'human', + 'option': 'go', + 'feedback': 'yes', + }); + await repo.cancelRun(3); + expect(gateway.type, 'cancel_run'); + expect(gateway.fields, {'run_id': 3}); + await repo.setRunTitle(3, 'New'); + expect(gateway.type, 'set_run_title'); + expect(gateway.fields, {'run_id': 3, 'title': 'New'}); + await repo.startRun( + pipelineId: 4, + version: 2, + prompt: 'hello', + workspace: ' /work ', + requestKey: 'start-2', + title: ' Job ', + notifyMode: 'off', + outputFormat: 'json', + ); + expect(gateway.type, 'run_pipeline'); + expect(gateway.fields, { + 'pipeline_id': 4, + 'version': 2, + 'request_key': 'start-2', + 'workspace': '/work', + 'input': {'prompt': 'hello'}, + 'title': 'Job', + 'notify_mode': 'off', + 'output_format': 'json', + }); + }); + + test( + 'repository propagates server refusals and rejects missing detail', + () async { + final gateway = FakeGateway()..reply = {}; + final repo = RunsRepository(gateway); + await expectLater( + repo.getRun(3), + throwsA(isA()), + ); + await expectLater( + repo.decideRun(3, option: ' '), + throwsA(isA()), + ); + gateway.failure = const RunsRepositoryException('server refused'); + await expectLater( + repo.cancelRun(3), + throwsA(predicate((error) => '$error' == 'server refused')), + ); + }, + ); +} From 48059247d1eb5d9bbea91cb6d63c2eaa38b97f8d Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:37:03 +0100 Subject: [PATCH 11/84] feat(app): add native chat sessions browser --- .../features/chat/data/chat_repository.dart | 105 ++++-- app/lib/features/chat/session_screen.dart | 1 + .../ui/sessions/chat_sessions_screen.dart | 322 ++++++++++++++++++ app/notes/C1.md | 5 + .../features/chat/chat_foundation_test.dart | 39 ++- app/tool/chat_sessions_probe_entry.dart | 62 ++++ 6 files changed, 509 insertions(+), 25 deletions(-) create mode 100644 app/lib/features/chat/session_screen.dart create mode 100644 app/lib/features/chat/ui/sessions/chat_sessions_screen.dart create mode 100644 app/notes/C1.md create mode 100644 app/tool/chat_sessions_probe_entry.dart diff --git a/app/lib/features/chat/data/chat_repository.dart b/app/lib/features/chat/data/chat_repository.dart index 8053ef5c..868408e7 100644 --- a/app/lib/features/chat/data/chat_repository.dart +++ b/app/lib/features/chat/data/chat_repository.dart @@ -1,5 +1,13 @@ import '../../../core/api_gateway.dart'; +const webChatClient = 'Web'; + +String nativeChatMessageId(String operationId) { + final compact = operationId.replaceAll(RegExp('[^A-Za-z0-9]'), ''); + final capped = compact.length > 120 ? compact.substring(0, 120) : compact; + return capped.isEmpty ? '' : 'msg_$capped'; +} + /// Chat wire adapter. ApiGateway supplies request ids and returns full envelopes. class ChatRepository { ChatRepository(this.gateway); @@ -7,11 +15,14 @@ class ChatRepository { Future> sessions() async => _maps((await gateway.call('chat_sessions'))['chat_sessions']); - Future> models(String sessionId) async => _maps( - (await gateway.call('chat_models', { + Future models(String sessionId) async { + final reply = await gateway.call('chat_models', { 'chat_query': {'session_id': sessionId}, - }))['chat_models'], - ); + }); + final catalog = reply['chat_models']; + return catalog is Map ? Map.from(catalog) : {}; + } + Future selectModel( String sessionId, String provider, @@ -34,9 +45,29 @@ class ChatRepository { .whereType() .toList(); + Future> backends() async => + ((await gateway.call('chat_backends'))['chat_backends'] as List? ?? + const []) + .whereType() + .toList(); + + Future shellOutput( + String sessionId, + String shellId, { + int cursor = 0, + int limit = 65536, + }) => gateway.call('chat_shell_output', { + 'chat_shell_output_query': { + 'session_id': sessionId, + 'shell_id': shellId, + 'cursor': cursor, + 'limit': limit, + }, + }); + Future history( String sessionId, { - int limit = 50, + int limit = 200, String cursor = '', }) async { final reply = await gateway.call('chat_messages', { @@ -67,15 +98,21 @@ class ChatRepository { required String operationId, String backend = 'opencode', String instructions = '', - }) => gateway.call('chat_create', { - 'chat_create': { - 'title': title, - 'directory': directory, - 'operation_id': operationId, - if (backend.isNotEmpty && backend != 'opencode') 'backend': backend, - if (instructions.trim().isNotEmpty) 'instructions': instructions.trim(), - }, - }); + }) { + if (title.trim().isEmpty || directory.trim().isEmpty) { + throw ArgumentError('Enter a chat name and choose a directory.'); + } + return gateway.call('chat_create', { + 'chat_create': { + 'title': title.trim(), + 'directory': directory.trim(), + 'operation_id': operationId, + if (backend.isNotEmpty && backend != 'opencode') 'backend': backend, + if (instructions.trim().isNotEmpty) 'instructions': instructions.trim(), + }, + }); + } + Future rename(String sessionId, String title) => gateway.call('chat_rename', { 'chat_rename': {'session_id': sessionId, 'title': title.trim()}, @@ -96,13 +133,22 @@ class ChatRepository { String text, { required String operationId, List files = const [], + List attachments = const [], }) { + if (sessionId.trim().isEmpty) { + throw ArgumentError('Select a chat session first.'); + } + if (text.trim().isEmpty) { + throw ArgumentError('Enter a message before sending.'); + } final body = { 'session_id': sessionId, 'text': text.trim(), 'operation_id': operationId, + 'native_message_id': nativeChatMessageId(operationId), }; if (files.isNotEmpty) body['files'] = files; + if (attachments.isNotEmpty) body['attachments'] = attachments; return gateway.call('chat_prompt', {'chat_prompt': body}); } @@ -127,17 +173,28 @@ class ChatRepository { String sessionId, String requestId, String decision, { - String client = 'web', + String client = webChatClient, String message = '', - }) => gateway.call('chat_reply', { - 'chat_reply': { - 'session_id': sessionId, - 'request_id': requestId, - 'decision': decision, - 'client': client, - if (message.trim().isNotEmpty) 'message': message.trim(), - }, - }); + }) { + if (sessionId.trim().isEmpty) { + throw ArgumentError('Select a chat session first.'); + } + if (requestId.trim().isEmpty) { + throw ArgumentError('This approval request is no longer available.'); + } + if (!const ['once', 'always', 'reject'].contains(decision.trim())) { + throw ArgumentError('Choose once, always or reject.'); + } + return gateway.call('chat_reply', { + 'chat_reply': { + 'session_id': sessionId, + 'request_id': requestId, + 'decision': decision, + 'client': client, + if (message.trim().isNotEmpty) 'message': message.trim(), + }, + }); + } static List _maps(Object? value) => (value as List? ?? const []) .whereType() diff --git a/app/lib/features/chat/session_screen.dart b/app/lib/features/chat/session_screen.dart new file mode 100644 index 00000000..782ccae3 --- /dev/null +++ b/app/lib/features/chat/session_screen.dart @@ -0,0 +1 @@ +export 'ui/sessions/chat_sessions_screen.dart'; diff --git a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart new file mode 100644 index 00000000..c18476b0 --- /dev/null +++ b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart @@ -0,0 +1,322 @@ +import 'package:flutter/material.dart'; + +import '../../../../core/api_gateway.dart'; +import '../../data/chat_repository.dart'; +import '../../domain/chat_sessions.dart'; + +/// Browses server-owned sessions. Opening a row is read-only at this layer. +class ChatSessionsScreen extends StatefulWidget { + const ChatSessionsScreen({ + super.key, + required this.gateway, + required this.onOpen, + }); + final ApiGateway gateway; + final void Function(JsonMap session) onOpen; + + @override + State createState() => _ChatSessionsScreenState(); +} + +class _ChatSessionsScreenState extends State { + late ChatRepository _repository; + final _search = TextEditingController(); + List _sessions = []; + String? _error; + bool _loading = true; + int _generation = 0; + + @override + void initState() { + super.initState(); + _repository = ChatRepository(widget.gateway); + _refresh(); + } + + @override + void didUpdateWidget(covariant ChatSessionsScreen oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.gateway != widget.gateway) { + _repository = ChatRepository(widget.gateway); + _refresh(); + } + } + + @override + void dispose() { + _generation++; + _search.dispose(); + super.dispose(); + } + + Future _refresh() async { + final generation = ++_generation; + setState(() { + _loading = true; + _error = null; + }); + try { + final sessions = await _repository.sessions(); + if (!mounted || generation != _generation) return; + setState(() { + _sessions = sessions; + _loading = false; + }); + } catch (error) { + if (!mounted || generation != _generation) return; + setState(() { + _error = '$error'; + _loading = false; + }); + } + } + + Future _mutate( + Future Function(String) action, + String id, + ) async { + try { + await action(id); + await _refresh(); + } catch (error) { + if (mounted) setState(() => _error = '$error'); + } + } + + Future _rename(JsonMap session) async { + final controller = TextEditingController(text: chatSessionTitle(session)); + final title = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Rename chat'), + content: TextField( + controller: controller, + autofocus: true, + decoration: const InputDecoration(labelText: 'Chat name'), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: () => Navigator.pop(context, controller.text.trim()), + child: const Text('Save'), + ), + ], + ), + ); + controller.dispose(); + if (title == null || title.trim().isEmpty) return; + try { + await _repository.rename('${session['id']}', title); + await _refresh(); + } catch (error) { + if (mounted) setState(() => _error = '$error'); + } + } + + Future _newChat() async { + final dirs = TextEditingController(); + final title = TextEditingController(text: 'New chat'); + final instructions = TextEditingController(); + final result = + await showDialog< + ({String title, String directory, String instructions}) + >( + context: context, + builder: (context) => AlertDialog( + title: const Text('New chat'), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + controller: title, + decoration: const InputDecoration(labelText: 'Name'), + ), + TextField( + controller: dirs, + decoration: const InputDecoration( + labelText: 'Server directory', + ), + ), + TextField( + controller: instructions, + decoration: const InputDecoration(labelText: 'Instructions'), + ), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: () => Navigator.pop(context, ( + title: title.text.trim(), + directory: dirs.text.trim(), + instructions: instructions.text, + )), + child: const Text('Create'), + ), + ], + ), + ); + title.dispose(); + dirs.dispose(); + instructions.dispose(); + if (result == null) return; + if (result.title.isEmpty || result.directory.isEmpty) { + setState(() => _error = 'Enter a name and server directory.'); + return; + } + try { + final reply = await _repository.create( + title: result.title, + directory: result.directory, + operationId: 'native-chat-${DateTime.now().microsecondsSinceEpoch}', + instructions: result.instructions, + ); + final session = reply['chat_session']; + if (session is Map) widget.onOpen(Map.from(session)); + await _refresh(); + } catch (error) { + if (mounted) setState(() => _error = '$error'); + } + } + + @override + Widget build(BuildContext context) { + final visible = filterChatSessions(_sessions, _search.text); + final starred = visible.where((s) => s['starred'] == true).toList(); + final open = visible + .where((s) => s['starred'] != true && s['closed_at'] == null) + .toList(); + final closed = visible.where((s) => s['closed_at'] != null).toList(); + return Scaffold( + appBar: AppBar( + title: const Text('Chats'), + actions: [ + IconButton( + onPressed: _newChat, + tooltip: 'New chat', + icon: const Icon(Icons.add), + ), + IconButton( + onPressed: _refresh, + tooltip: 'Refresh', + icon: const Icon(Icons.refresh), + ), + ], + ), + body: Column( + children: [ + Padding( + padding: const EdgeInsets.all(16), + child: TextField( + controller: _search, + onChanged: (_) => setState(() {}), + decoration: const InputDecoration( + prefixIcon: Icon(Icons.search), + labelText: 'Search chats', + ), + ), + ), + if (_error != null) + MaterialBanner( + content: Text(_error!), + actions: [ + TextButton(onPressed: _refresh, child: const Text('Retry')), + ], + ), + Expanded( + child: _loading && _sessions.isEmpty + ? const Center(child: CircularProgressIndicator()) + : ListView( + children: [ + if (starred.isNotEmpty) _section('Starred', starred), + if (open.isNotEmpty) _section('Chats', open), + if (closed.isNotEmpty) _section('Closed', closed), + if (visible.isEmpty && !_loading) + const ListTile(title: Text('No chats found.')), + ], + ), + ), + ], + ), + floatingActionButton: FloatingActionButton.extended( + onPressed: _newChat, + icon: const Icon(Icons.add), + label: const Text('New chat'), + ), + ); + } + + Widget _section(String title, List sessions) => ExpansionTile( + title: Text(title), + initiallyExpanded: true, + children: [ + for (final group in groupChatSessions(sessions)) ...[ + if (group.directory.isNotEmpty) + ListTile( + dense: true, + leading: const Icon(Icons.folder_outlined), + title: Text(group.directory), + ), + for (final session in group.sessions) _row(session), + ], + ], + ); + + Widget _row(JsonMap session) { + final id = '${session['id'] ?? ''}'; + final isClosed = session['closed_at'] != null; + final starred = session['starred'] == true; + return ListTile( + leading: Icon( + session['running'] == true + ? Icons.sync + : starred + ? Icons.star + : Icons.chat_bubble_outline, + ), + title: Text(chatSessionTitle(session)), + subtitle: Text( + '${session['directory'] ?? ''}${session['running'] == true + ? ' · Streaming' + : session['unseen'] == true + ? ' · New' + : ''}', + ), + onTap: () => widget.onOpen(session), + trailing: PopupMenuButton( + tooltip: 'Chat actions', + onSelected: (value) { + if (value == 'rename') { + _rename(session); + } + if (value == 'star') { + _mutate((id) => _repository.star(id, !starred), id); + } + if (value == 'close') { + _mutate(_repository.close, id); + } + if (value == 'reopen') { + _mutate(_repository.reopen, id); + } + }, + itemBuilder: (_) => [ + const PopupMenuItem(value: 'rename', child: Text('Rename')), + PopupMenuItem( + value: 'star', + child: Text(starred ? 'Remove from Starred' : 'Star'), + ), + if (isClosed) + const PopupMenuItem(value: 'reopen', child: Text('Reopen')) + else + const PopupMenuItem(value: 'close', child: Text('Close')), + ], + ), + ); + } +} diff --git a/app/notes/C1.md b/app/notes/C1.md new file mode 100644 index 00000000..4f79091c --- /dev/null +++ b/app/notes/C1.md @@ -0,0 +1,5 @@ +# C1 — Chat sessions and repository adapter + +Implemented the native Material sessions browser, search, directory grouping, starred/closed groups, standard session actions, and explicit-directory create dialog. Opening a session only invokes the supplied callback. The chat repository includes the web-compatible native message ID, prompt validation, Web permission label, and 200-message history default. + +Verification: `flutter test test/features/chat` passed. Browser build/captures and mobile builds were not performed here. The fixture entry point is `tool/chat_sessions_probe_entry.dart`; a separate browser review should exercise the rendered states and capture them before claiming UI acceptance. diff --git a/app/test/features/chat/chat_foundation_test.dart b/app/test/features/chat/chat_foundation_test.dart index 76e74353..7067c9a1 100644 --- a/app/test/features/chat/chat_foundation_test.dart +++ b/app/test/features/chat/chat_foundation_test.dart @@ -222,6 +222,7 @@ void main() { 'session_id': 's', 'text': 'hi', 'operation_id': 'same', + 'native_message_id': 'msg_same', }, }); await repo.answerForm('s', 'f', {'choice': 'yes'}, action: 'submit'); @@ -239,7 +240,7 @@ void main() { 'session_id': 's', 'request_id': 'r', 'decision': 'once', - 'client': 'web', + 'client': 'Web', 'message': 'approved', }, }); @@ -255,5 +256,41 @@ void main() { expect(gateway.calls.last.type, 'chat_model'); }, ); + test('rejects invalid permissions and prompts before sending', () async { + expect( + () => repo.prompt(' ', 'hello', operationId: 'x'), + throwsArgumentError, + ); + expect( + () => repo.prompt('s', ' ', operationId: 'x'), + throwsArgumentError, + ); + expect( + () => repo.replyPermission('s', 'r', 'approve'), + throwsArgumentError, + ); + expect(gateway.calls, isEmpty); + }); + test( + 'uses the server model catalog object and default history limit', + () async { + gateway.reply = { + 'chat_models': { + 'providers': { + 'p': ['m'], + }, + }, + }; + expect((await repo.models('s'))['providers'], { + 'p': ['m'], + }); + expect(gateway.calls.single.fields, { + 'chat_query': {'session_id': 's'}, + }); + gateway.calls.clear(); + await repo.history('s'); + expect(gateway.calls.single.fields['chat_query']['limit'], 200); + }, + ); }); } diff --git a/app/tool/chat_sessions_probe_entry.dart b/app/tool/chat_sessions_probe_entry.dart new file mode 100644 index 00000000..648fd3bd --- /dev/null +++ b/app/tool/chat_sessions_probe_entry.dart @@ -0,0 +1,62 @@ +import 'package:flutter/material.dart'; + +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/session_screen.dart'; + +class _FixtureGateway implements ApiGateway { + @override + Stream get frames => const Stream.empty(); + @override + Future call(String type, [JsonMap fields = const {}]) async { + if (type == 'chat_sessions') { + return { + 'chat_sessions': [ + { + 'id': 'probe-open', + 'title': 'Open fixture', + 'directory': '/workspace/demo', + 'starred': true, + }, + { + 'id': 'probe-closed', + 'title': 'Closed fixture', + 'directory': '/workspace/archive', + 'closed_at': '2026-01-01', + }, + { + 'id': 'probe-stream', + 'title': 'Streaming fixture', + 'directory': '/workspace/demo', + 'running': true, + }, + ], + }; + } + if (type == 'chat_directories') { + return { + 'chat_directories': ['/workspace/demo', '/workspace/archive'], + }; + } + if (type == 'chat_backends') { + return { + 'chat_backends': ['opencode', 'codex'], + }; + } + if (type == 'chat_create') { + return { + 'chat_session': { + 'id': 'probe-new', + 'title': 'New fixture', + 'directory': '/workspace/demo', + }, + }; + } + return {'chat_session': {}}; + } +} + +void main() => runApp( + MaterialApp( + home: ChatSessionsScreen(gateway: _FixtureGateway(), onOpen: (_) {}), + ), +); From a561c45b659f8abede77ac5cf69e005170aa3949 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:37:18 +0100 Subject: [PATCH 12/84] test(app): verify real browser shell navigation and capture states --- app/notes/F2.md | 12 ++++++++++++ app/tool/shell_probe.mjs | 22 ++++++++++++++-------- 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/app/notes/F2.md b/app/notes/F2.md index ff1fd3c5..12d851f4 100644 --- a/app/notes/F2.md +++ b/app/notes/F2.md @@ -1,5 +1,17 @@ # F2 — Adaptive shell +## Manager browser acceptance +The initial capture attempt failed because the fixture served its index with +binary MIME. Corrected the fixture MIME and navigation assertions; the real +Chrome run now passes actual Pipelines → Runs → Chat → Settings → Pipelines +navigation, checking the selected destination body (not only navigation labels). +Captured and inspected at 390×844 and 1280×800: +`/private/var/folders/jp/q0qvjyg54fl_c5vhhk1ylz2m0000gn/T/opencode/f2-shell-{phone,phone-runs,phone-settings,desktop}.png`. +These show the native Cupertino shell on a macOS browser with explicitly labelled +unimplemented feature bodies. They do not prove feature parity or mobile behavior. +Reproduce from app/ using `OPENCODE_ARTIFACT_DIR= node tool/shell_probe.mjs` +after `flutter build web`. Earlier missing-capture statements below are historical. + Implemented standard adaptive navigation for Pipelines, Runs, Chat and Settings. Material uses a bottom `NavigationBar` below 600 logical pixels and a labeled `NavigationRail` at wider widths. Cupertino uses the native navigation bar and diff --git a/app/tool/shell_probe.mjs b/app/tool/shell_probe.mjs index 73d4695f..c0e02bc2 100644 --- a/app/tool/shell_probe.mjs +++ b/app/tool/shell_probe.mjs @@ -3,7 +3,7 @@ import { readFile } 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 } from 'node:path'; +import { join, extname, resolve, sep } from 'node:path'; import { tmpdir } from 'node:os'; import { mkdtemp, rm } from 'node:fs/promises'; @@ -11,9 +11,11 @@ const root = join(process.cwd(), 'build/web'); const mime = { '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.wasm': 'application/wasm', '.png': 'image/png', '.ico': 'image/x-icon' }; const server = createServer(async (req, res) => { try { - const path = join(root, decodeURIComponent(new URL(req.url, 'http://localhost').pathname)); - const file = await readFile(path.endsWith('/') ? join(path, 'index.html') : path); - res.writeHead(200, { 'content-type': mime[extname(path)] ?? 'application/octet-stream' }).end(file); + const path = resolve(root, '.' + decodeURIComponent(new URL(req.url, 'http://localhost').pathname)); + if (path !== root && !path.startsWith(root + sep)) return res.writeHead(403).end(); + const filePath = path.endsWith('/') ? join(path, 'index.html') : path; + const file = await readFile(filePath); + res.writeHead(200, { 'content-type': mime[extname(filePath)] ?? 'application/octet-stream' }).end(file); } catch { res.writeHead(404).end('not found'); } }); server.listen(0, '127.0.0.1'); @@ -39,18 +41,21 @@ try { const pending = new Map(); ws.addEventListener('message', event => { const msg = JSON.parse(event.data); + if (msg.method?.includes('detached') || msg.method?.includes('crashed')) console.error('CDP event', JSON.stringify(msg)); if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); } }); const send = (method, params = {}, sessionId) => new Promise(resolve => { const callId = ++id; pending.set(callId, resolve); ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) })); }); - const created = await send('Target.createTarget', { url: `http://127.0.0.1:${port}/` }); + 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); + const navigation = await send('Page.navigate', { url: `http://127.0.0.1:${port}/` }, session); + if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation)); 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)}`); @@ -61,7 +66,7 @@ try { if (!loaded?.url.includes(`127.0.0.1:${port}`)) throw new Error(`Fixture did not load: ${JSON.stringify(loaded)}`); await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); await delay(900); - const clickLabel = async label => evaluate(`(() => { const e=[...document.querySelectorAll('flt-semantics')].find(x => (x.getAttribute('aria-label') || x.innerText || '').includes(${JSON.stringify(label)})); if (!e) return false; e.click(); return true; })()`); + const clickLabel = async label => evaluate(`(() => { const e=[...document.querySelectorAll('flt-semantics')].find(x => (x.getAttribute('aria-label') || x.innerText || '') === ${JSON.stringify(label)}); if (!e) return false; e.click(); return true; })()`); const labels = await evaluate("[...document.querySelectorAll('flt-semantics')].map(x=>x.getAttribute('aria-label')||x.innerText).filter(Boolean)"); if (!labels?.some(x => x.includes('Pipelines'))) throw new Error(`Flutter semantics unavailable: ${JSON.stringify(labels)}`); const capture = async (name, width, height) => { @@ -75,10 +80,11 @@ try { if (!await clickLabel(label)) throw new Error(`Could not interact with ${label} navigation`); await delay(250); const current = await evaluate("[...document.querySelectorAll('flt-semantics')].map(x=>x.getAttribute('aria-label')||x.innerText).filter(Boolean)"); - if (!current?.some(x => x.includes(label))) throw new Error(`${label} missing after navigation`); + if (!current?.some(x => x.includes(label + ' — Not implemented'))) throw new Error(`${label} body missing after navigation: ${JSON.stringify(current)}`); + if (label === 'Runs' || label === 'Settings') await capture(`f2-shell-phone-${label.toLowerCase()}`, 390, 844); } await capture('f2-shell-desktop', 1280, 800); - console.log(JSON.stringify({ labels, captures: ['f2-shell-phone.png', 'f2-shell-desktop.png'], navigated: ['Runs', 'Chat', 'Settings', 'Pipelines'] }, null, 2)); + console.log(JSON.stringify({ labels, captures: ['f2-shell-phone.png', 'f2-shell-phone-runs.png', 'f2-shell-phone-settings.png', 'f2-shell-desktop.png'], navigated: ['Runs', 'Chat', 'Settings', 'Pipelines'] }, null, 2)); } finally { ws?.close(); chrome.kill('SIGTERM'); From ae352bb9c6269b2fdfa7ef6e8a26fc9f015a71e9 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:37:18 +0100 Subject: [PATCH 13/84] fix(app): retain idle preview sockets and release auth listeners --- app/notes/F5.md | 5 +++++ app/test/tool/preview.test.mjs | 2 ++ app/tool/preview/README.md | 2 +- app/tool/preview/server.mjs | 13 +++++++++---- 4 files changed, 17 insertions(+), 5 deletions(-) diff --git a/app/notes/F5.md b/app/notes/F5.md index b5141ff0..f4383c02 100644 --- a/app/notes/F5.md +++ b/app/notes/F5.md @@ -1,5 +1,10 @@ # F5 preview server candidate review +Manager reran all 6 fixture tests and added an idle-websocket regression past the +five-second establishment deadline. Healthy idle sockets now keep their session; +auth-check listeners are removed when finished. Default preview port is 8096, +separate from the raw API at 8080. HTTPS certificate paths remain untested. + Candidate `e3a82b0`'s static preview route was retained, with stricter decoded path validation and canonical-path checks for files and SPA fallback. The proxy now uses `http.request` / `https.request` streams so Range, HEAD, content-encoding, diff --git a/app/test/tool/preview.test.mjs b/app/test/tool/preview.test.mjs index 17561d2a..3c6d6630 100644 --- a/app/test/tool/preview.test.mjs +++ b/app/test/tool/preview.test.mjs @@ -117,6 +117,8 @@ test('authenticates and maps same-origin WebSocket Origin; bytes flow both direc const upgraded = seen.find((item) => item.upgraded); assert.equal(upgraded.headers.origin, new URL(`http://${seen[0].headers.host}`).origin); assert.equal(upgraded.headers.cookie, 'sid=yes'); + await new Promise((resolve) => setTimeout(resolve, 5200)); + assert.equal(socket.destroyed, false, 'healthy idle websocket must not time out'); const payload = Buffer.from([0x81, 0x02, 0x6f, 0x6b]); socket.write(payload); await new Promise((resolve, reject) => { diff --git a/app/tool/preview/README.md b/app/tool/preview/README.md index e060f920..8dcfa751 100644 --- a/app/tool/preview/README.md +++ b/app/tool/preview/README.md @@ -4,7 +4,7 @@ Build and run from `app/`: ```sh /Users/alan/development/flutter/bin/flutter build web -UPSTREAM=http://127.0.0.1:8095 node tool/preview/server.mjs --port 8080 +UPSTREAM=http://127.0.0.1:8095 node tool/preview/server.mjs --port 8096 ``` The preview binds to loopback by default and authenticates static requests by diff --git a/app/tool/preview/server.mjs b/app/tool/preview/server.mjs index 818f985f..abc8e55e 100644 --- a/app/tool/preview/server.mjs +++ b/app/tool/preview/server.mjs @@ -81,8 +81,11 @@ function authCheck(req, target, callback) { const finish = (result) => { if (completed) return; completed = true; + req.removeListener('aborted', abort); + req.socket.removeListener('close', abort); callback(result); }; + const abort = () => check.destroy(); const check = upstreamRequest(target, { method: 'GET', path: '/', headers: { cookie: req.headers.cookie ?? '', accept: 'text/html', 'accept-encoding': 'identity', } }, (response) => { @@ -91,8 +94,8 @@ function authCheck(req, target, callback) { }); check.setTimeout(timeoutMs, () => check.destroy(new Error('authentication check timeout'))); check.on('error', () => finish(null)); - req.on('aborted', () => check.destroy()); - req.socket.once('close', () => { if (!completed) check.destroy(); }); + req.once('aborted', abort); + req.socket.once('close', abort); check.end(); } @@ -100,7 +103,7 @@ function reject(socket, status, phrase = 'Forbidden') { if (!socket.destroyed) socket.end(`HTTP/1.1 ${status} ${phrase}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`); } -export async function start({ root = resolve('build/web'), upstream = 'http://127.0.0.1:8095', host = '127.0.0.1', port = 8080 } = {}) { +export async function start({ root = resolve('build/web'), upstream = 'http://127.0.0.1:8095', host = '127.0.0.1', port = 8096 } = {}) { const base = await realpath(root); const target = new URL(upstream); if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password) throw new Error('UPSTREAM must be credential-free HTTP(S)'); @@ -157,6 +160,8 @@ export async function start({ root = resolve('build/web'), upstream = 'http://12 upgrades.add(upstreamSocket); upstreamSocket.on('close', () => upgrades.delete(upstreamSocket)); upstreamSocket.setTimeout(timeoutMs, () => upstreamSocket.destroy(new Error('upgrade timeout'))); + // Bound establishment only. A healthy, idle chat socket stays connected. + upstreamSocket.once('data', () => upstreamSocket.setTimeout(0)); upstreamSocket.once(target.protocol === 'https:' ? 'secureConnect' : 'connect', () => { const headers = { ...req.headers, host: target.host, origin: target.origin }; const lines = Object.entries(headers).filter(([, value]) => value != null) @@ -191,7 +196,7 @@ if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`). if (value.startsWith('--')) result.push([value.slice(2), all[index + 1]]); return result; }, [])); - start({ root: args.root ?? 'build/web', upstream: process.env.UPSTREAM ?? args.upstream ?? 'http://127.0.0.1:8095', host: args.host ?? '127.0.0.1', port: Number(args.port ?? 8080) }) + start({ root: args.root ?? 'build/web', upstream: process.env.UPSTREAM ?? args.upstream ?? 'http://127.0.0.1:8095', host: args.host ?? '127.0.0.1', port: Number(args.port ?? 8096) }) .then((preview) => console.log(`preview http://${args.host ?? '127.0.0.1'}:${preview.port}`)) .catch((error) => { console.error(error); process.exitCode = 1; }); } From ef4ff40c4b8a2e3a8ba5fe5733c7d8855d76078b Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:41:22 +0100 Subject: [PATCH 14/84] docs(app): enforce quality gates and record verified preview progress --- app/AGENTS.md | 1 + app/WORK.md | 23 ++++++++++++++++++----- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/app/AGENTS.md b/app/AGENTS.md index a6c9d870..7752342a 100644 --- a/app/AGENTS.md +++ b/app/AGENTS.md @@ -6,6 +6,7 @@ - Standard Material and Cupertino controls, including buttons/menus in custom graphs/diffs/chat. System typography, theme colors, light/dark, content-driven layout and text scaling. No fixed row/bubble/button dimensions, bespoke palette or CSS token port. Platform differences are intentional. Centralize necessary layout constraints; do not ban legitimate native default spacing or graph coordinates. - Develop and test ONLY web now. No ADB, emulators, device changes, Android/iOS builds or installs. Keep source portable to all three targets. Explicitly report mobile as unverified. - Small cohesive files (aim below 250 lines; split by responsibility, not arbitrary fragments). Each task owns a directory and its tests. Do not edit another lane or root pubspec/main unless assigned. +- Code quality is a delivery requirement. No minified implementations, silent capability fallbacks, fake data masking missing features, or workarounds that bypass the real defect. A pipeline success does not waive missing behavior, native controls, regression coverage or rendered evidence. Label incomplete work honestly and complete it before claiming parity. ## Shared contract - `lib/core/api_gateway.dart`: `JsonMap` alias; `ApiGateway.call(type, [fields])` yields the entire decoded reply envelope; `frames` yields unsolicited server envelopes. Gateway owns request IDs. Do not put domain interpretation in transport. diff --git a/app/WORK.md b/app/WORK.md index 69b2057a..818a5d40 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -7,13 +7,16 @@ All work under app/. Existing applications remain running and unchanged. | Item | Scope | Source | Verification | Landing | Preview | | --- | --- | --- | --- | --- | --- | | F0 | Scaffold and gateway contract | 0e0ef54 | analyze + 1 scaffold test pass | main | not served | -| F1 | Socket transport, endpoint rules, reconnect | run 29 / flutter/f1-transport | pipeline passed; manager expanded to 12 regressions and corrected races | pending | — | -| F2 | Adaptive shell and standard platform controls | run 31 / flutter/f2-shell | pipeline passed; manager completing real browser evidence and native-default corrections | pending | pending | -| F3 | Run models, live event fold, actions | run 32 / flutter/f3-runs | pipeline passed; manager correcting ignored source and parity gaps | pending | — | +| F1 | Socket transport, endpoint rules, reconnect | run 29 + 1e4ecea | 12 regressions pass, analyze/web build pass | main cb1ea90, ancestry verified | — | +| F2 | Adaptive shell and standard platform controls | run 31 + a561c45 | 6 widget tests; real Chrome navigation + inspected phone/desktop PNGs | main 2f60a0e, ancestry verified | served skeleton | +| F3 | Run models, live event fold, actions | run 32 + 1515ebe | 11 regressions/analyze pass; 5 source files 105–226 lines | main 37d0823, ancestry verified | — | | F4 | Chat models, history/live fold, request facade | run 33 / flutter/f4-chat | pipeline passed; wire omissions carried into C1 | pending C1 adapter fixes | — | -| F5 | Isolated authenticated web preview tooling | run 30 / flutter/f5-preview | pipeline passed; manager checking actual websocket/auth/byte forwarding | pending | pending | +| F5 | Isolated authenticated web preview tooling | run 30 + ae352bb | 6 proxy fixtures incl auth/bytes/origin/idle sockets pass | main 160ab45, ancestry verified | http://127.0.0.1:8096/ | | P1 | Pipeline list/detail/source/version browser | run 34 / flutter/p1-pipelines | running (DeepSeek V4.1 Flash) | pending | pending | -| C1 | Chat session browser and management | run 35 / flutter/f4-chat | running (Luna), includes adapter prerequisites | pending | pending | +| C1 | Chat session browser and management | run 35 → resume 36 / flutter/f4-chat | pipeline passed; manager finishing native controls, grouping, selectors + captures | pending; not parity-complete | pending | +| N1 | Connection settings/preferences | run 37 / flutter/n1-settings | running (Flash) | pending | pending | +| R1 | Run list/detail/live timeline | run 38 / flutter/r1-runs-ui | running (Luna) | pending | pending | +| D1 | Recorded changes/diff viewer | run 39 / flutter/d1-diff-viewer | running (Flash) | pending | pending | ## Next ready work - P1 pipelines list/detail/source/version; P2 graph and stage/visit selection. @@ -45,6 +48,16 @@ workspace/write scope, so could not correct this admission mistake. No policy override, server edit or shell-write bypass was used by the manager. Allowed pipeline models: Luna or DeepSeek V4.1 Flash; current runs use Luna. +## Latest integration check +At 160ab45: 29 Flutter tests and 6 Node proxy fixtures pass; flutter analyze, +flutter build web and git diff --check pass. Real Chrome phone/desktop captures +are in the approved OpenCode temporary directory, named f2-shell-*.png. The +preview process is running separately on loopback 8096, authenticating via the +unchanged existing web proxy on 8095. Verified unauthenticated page redirects +to login, JS denies with 401, and proxied login responds 200. The served app is +currently a shell with explicit unimplemented bodies, NOT a feature-complete app. +No Android/iOS build or device verification has occurred. + ### Manager integration findings - F3 candidate omitted `lib/features/runs/data/runs_repository.dart`: root runtime-data ignore matched source. Main 718442d adds an app-only exception; From 774d5d78cc1c8215c90db7ff2c2c247e2d48d87f Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:42:47 +0100 Subject: [PATCH 15/84] feat(app): add native runs list and detail screen --- app/lib/features/runs/screen.dart | 44 +++++++ app/lib/features/runs/ui/run_detail_view.dart | 123 ++++++++++++++++++ app/lib/features/runs/ui/runs_controller.dart | 108 +++++++++++++++ app/lib/features/runs/ui/runs_list.dart | 75 +++++++++++ 4 files changed, 350 insertions(+) create mode 100644 app/lib/features/runs/screen.dart create mode 100644 app/lib/features/runs/ui/run_detail_view.dart create mode 100644 app/lib/features/runs/ui/runs_controller.dart create mode 100644 app/lib/features/runs/ui/runs_list.dart diff --git a/app/lib/features/runs/screen.dart b/app/lib/features/runs/screen.dart new file mode 100644 index 00000000..3edd5240 --- /dev/null +++ b/app/lib/features/runs/screen.dart @@ -0,0 +1,44 @@ +import 'package:flutter/material.dart'; + +import '../../core/api_gateway.dart'; +import 'data/runs_repository.dart'; +import 'ui/runs_controller.dart'; +import 'ui/runs_list.dart'; +import 'ui/run_detail_view.dart'; + +class RunsScreen extends StatefulWidget { + const RunsScreen({super.key, required this.gateway, this.initialRunId}); + final ApiGateway gateway; + final int? initialRunId; + + @override + State createState() => _RunsScreenState(); +} + +class _RunsScreenState extends State { + late RunsController controller; + @override + void initState() { + super.initState(); + controller = RunsController(RunsRepository(widget.gateway)); + controller.listen(widget.gateway.frames); + controller.addListener(_changed); + controller.load(widget.initialRunId); + } + + void _changed() { + if (mounted) setState(() {}); + } + + @override + void dispose() { + controller.removeListener(_changed); + controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => controller.detail == null + ? RunsList(controller: controller) + : RunDetailView(controller: controller); +} diff --git a/app/lib/features/runs/ui/run_detail_view.dart b/app/lib/features/runs/ui/run_detail_view.dart new file mode 100644 index 00000000..c1bd01c5 --- /dev/null +++ b/app/lib/features/runs/ui/run_detail_view.dart @@ -0,0 +1,123 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'runs_controller.dart'; + +class RunDetailView extends StatelessWidget { + const RunDetailView({super.key, required this.controller}); + final RunsController controller; + @override + Widget build(BuildContext context) { + final run = controller.detail; + if (controller.loading && run == null) { + return const Center(child: CircularProgressIndicator()); + } + if (run == null) { + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text(controller.error ?? 'Run details unavailable.'), + FilledButton( + onPressed: controller.back, + child: const Text('Back to runs'), + ), + ], + ), + ); + } + final input = run['input'] is Map ? run['input'] as Map : const {}; + final output = run['output'] is Map ? run['output'] as Map : const {}; + final steps = run['steps'] is List ? run['steps'] as List : const []; + final prompt = input['prompt']; + return ListView( + padding: const EdgeInsets.all(16), + children: [ + TextButton.icon( + onPressed: controller.back, + icon: const Icon(Icons.arrow_back), + label: const Text('Runs'), + ), + Text( + '${run['title'] ?? run['name'] ?? 'Run ${run['id']}'}', + style: Theme.of(context).textTheme.headlineSmall, + ), + Wrap( + spacing: 8, + children: [ + Chip(label: Text('${run['status'] ?? 'unknown'}')), + Text('Run ${run['id']}'), + Text('Pipeline ${run['name'] ?? 'unavailable'}'), + ], + ), + if (prompt is String) ...[ + const SizedBox(height: 12), + Row( + children: [ + Text( + 'Original prompt', + style: Theme.of(context).textTheme.titleMedium, + ), + const Spacer(), + IconButton( + tooltip: 'Copy prompt', + onPressed: () => _copy(context, prompt), + icon: const Icon(Icons.copy), + ), + ], + ), + SelectableText(prompt), + ], + _section(context, 'Input', input), + _section(context, 'Output', output), + Text('Timeline', style: Theme.of(context).textTheme.titleLarge), + if (steps.isEmpty) + const Text('No visits recorded.') + else + ...steps.whereType().map( + (step) => ListTile( + leading: const Icon(Icons.circle_outlined), + title: Text( + '${step['stage'] ?? 'Stage unavailable'} · visit ${step['sequence'] ?? '?'}', + ), + subtitle: Text( + '${step['status'] ?? 'Status unavailable'}${step['outcome'] == null ? '' : ' · ${step['outcome']}'}', + ), + ), + ), + const ListTile(title: Text('Metrics'), subtitle: Text('Unavailable')), + ], + ); + } + + Widget _section(BuildContext context, String title, Map value) => + ExpansionTile( + title: Text(title), + children: [ + Padding( + padding: const EdgeInsets.all(16), + child: SelectableText( + value.isEmpty + ? 'No ${title.toLowerCase()} recorded.' + : value.entries.map((e) => '${e.key}: ${e.value}').join('\n'), + ), + ), + ], + ); + Future _copy(BuildContext context, String text) async { + // Clipboard failure is reported rather than silently substituting title/output. + try { + await Clipboard.setData(ClipboardData(text: text)); + if (context.mounted) { + ScaffoldMessenger.of( + context, + ).showSnackBar(const SnackBar(content: Text('Prompt copied.'))); + } + } catch (_) { + if (context.mounted) { + ScaffoldMessenger.of( + context, + ).showSnackBar(const SnackBar(content: Text('Could not copy prompt.'))); + } + } + } +} diff --git a/app/lib/features/runs/ui/runs_controller.dart b/app/lib/features/runs/ui/runs_controller.dart new file mode 100644 index 00000000..02fa8bf8 --- /dev/null +++ b/app/lib/features/runs/ui/runs_controller.dart @@ -0,0 +1,108 @@ +import 'dart:async'; +import 'package:flutter/foundation.dart'; +import '../../../core/api_gateway.dart'; +import '../data/runs_repository.dart'; +import '../domain/run_events.dart'; +import '../domain/run_models.dart'; + +class RunsController extends ChangeNotifier { + RunsController(this.repository); + final RunsRepository repository; + StreamSubscription? _subscription; + List runs = []; + JsonMap? detail; + String? error; + bool loading = false; + String query = '', sort = 'newest_first'; + int _selection = 0; + Timer? _refresh; + + void listen(Stream frames) { + _subscription?.cancel(); + _subscription = frames + .where((f) => f['type'] == 'run_event') + .listen(_event); + } + + Future load([int? initialId]) async { + final token = ++_selection; + loading = true; + error = null; + notifyListeners(); + try { + final result = await repository.listRuns(); + if (token != _selection) return; + runs = result.runs; + if (initialId != null) await select(initialId); + } catch (e) { + if (token == _selection) error = '$e'; + } + if (token == _selection) { + loading = false; + notifyListeners(); + } + } + + Future select(num id) async { + final token = ++_selection; + detail = null; + error = null; + loading = true; + notifyListeners(); + try { + final value = await repository.getRun(id); + if (token == _selection) detail = value; + } catch (e) { + if (token == _selection) error = '$e'; + } + if (token == _selection) { + loading = false; + notifyListeners(); + } + } + + void back() { + ++_selection; + detail = null; + error = null; + notifyListeners(); + } + + void setQuery(String value) { + query = value; + notifyListeners(); + } + + void _event(JsonMap frame) { + final folded = foldRunEvent(runs, frame); + runs = folded.runs; + if (detail?['id'] == frame['run_id']) { + detail = foldRunEventDetail(detail, frame); + } + if (detail != null && runDetailNeedsFullSync(frame)) { + _refresh?.cancel(); + _refresh = Timer( + const Duration(milliseconds: 150), + () => select(detail!['id'] as num), + ); + } + notifyListeners(); + } + + List get visibleRuns => sortRuns( + runs + .where( + (r) => '${r['title'] ?? r['name'] ?? ''}'.toLowerCase().contains( + query.toLowerCase(), + ), + ) + .toList(), + sort: sort, + ); + @override + void dispose() { + _subscription?.cancel(); + _refresh?.cancel(); + super.dispose(); + } +} diff --git a/app/lib/features/runs/ui/runs_list.dart b/app/lib/features/runs/ui/runs_list.dart new file mode 100644 index 00000000..9ab2d1b8 --- /dev/null +++ b/app/lib/features/runs/ui/runs_list.dart @@ -0,0 +1,75 @@ +import 'package:flutter/material.dart'; +import 'runs_controller.dart'; +import '../domain/run_models.dart'; + +class RunsList extends StatelessWidget { + const RunsList({super.key, required this.controller}); + final RunsController controller; + @override + Widget build(BuildContext context) { + if (controller.loading && controller.runs.isEmpty) { + return const Center(child: CircularProgressIndicator()); + } + if (controller.error != null && controller.runs.isEmpty) { + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text(controller.error!), + const SizedBox(height: 8), + FilledButton( + onPressed: controller.load, + child: const Text('Retry'), + ), + ], + ), + ); + } + return Column( + children: [ + if (controller.error != null) + MaterialBanner( + content: Text(controller.error!), + actions: [ + TextButton(onPressed: controller.load, child: const Text('Retry')), + ], + ), + Padding( + padding: const EdgeInsets.all(16), + child: TextField( + decoration: const InputDecoration( + labelText: 'Filter runs', + prefixIcon: Icon(Icons.search), + ), + onChanged: controller.setQuery, + ), + ), + Expanded( + child: controller.visibleRuns.isEmpty + ? const Center(child: Text('No runs found.')) + : ListView.builder( + itemCount: controller.visibleRuns.length, + itemBuilder: (context, index) { + final run = controller.visibleRuns[index]; + final identity = runIdentity(run['title'], run['name']); + final created = + run['created_at']?.toString() ?? 'Time unavailable'; + final id = run['id']; + return ListTile( + title: Text( + identity.label.isEmpty ? 'Run $id' : identity.label, + ), + subtitle: Text( + '${run['name'] ?? 'Pipeline unavailable'} · $created${run['scheduled'] == true ? ' · Scheduled' : ''}', + ), + leading: Chip(label: Text(runStatusLabel(run))), + trailing: const Icon(Icons.chevron_right), + onTap: id is num ? () => controller.select(id) : null, + ); + }, + ), + ), + ], + ); + } +} From 0a8806b4bb4b5c4580ea5d9d83aa0f66298d8bc6 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:44:11 +0100 Subject: [PATCH 16/84] docs(app): hold run UI candidate for pipeline acceptance fixes --- app/WORK.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/app/WORK.md b/app/WORK.md index 818a5d40..bd2346e2 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -15,7 +15,7 @@ All work under app/. Existing applications remain running and unchanged. | P1 | Pipeline list/detail/source/version browser | run 34 / flutter/p1-pipelines | running (DeepSeek V4.1 Flash) | pending | pending | | C1 | Chat session browser and management | run 35 → resume 36 / flutter/f4-chat | pipeline passed; manager finishing native controls, grouping, selectors + captures | pending; not parity-complete | pending | | N1 | Connection settings/preferences | run 37 / flutter/n1-settings | running (Flash) | pending | pending | -| R1 | Run list/detail/live timeline | run 38 / flutter/r1-runs-ui | running (Luna) | pending | pending | +| R1 | Run list/detail/live timeline | run 38 → continuation 40 / flutter/r1-runs-ui | manager rejected refresh/disposal bugs, missing new tests and native controls; pipeline correcting (Luna) | held | pending | | D1 | Recorded changes/diff viewer | run 39 / flutter/d1-diff-viewer | running (Flash) | pending | pending | ## Next ready work @@ -71,6 +71,11 @@ No Android/iOS build or device verification has occurred. already started while corrections proceed. ## Completion loop +Manager role: check evidence/diffs, verify, merge, update preview and start next +ready items. Per latest user steering, substantial implementation and corrections +belong to existing pipelines, not manager-written replacements. Already-running +direct correction work is preserved; do not discard it or duplicate it. + Use pipelines wait for every started run. Inspect failure evidence before fixing, resuming or retrying; preserve partial work. On success inspect actual diff and checks, integrate, verify ancestry, then launch the next ready item. Do not From eb0d7b4405af1738d6649caf53d57a9f2340dd97 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:47:01 +0100 Subject: [PATCH 17/84] docs(app): record network preview and scoped run-controller resume --- app/WORK.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/app/WORK.md b/app/WORK.md index bd2346e2..c3c2bf90 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -15,7 +15,7 @@ All work under app/. Existing applications remain running and unchanged. | P1 | Pipeline list/detail/source/version browser | run 34 / flutter/p1-pipelines | running (DeepSeek V4.1 Flash) | pending | pending | | C1 | Chat session browser and management | run 35 → resume 36 / flutter/f4-chat | pipeline passed; manager finishing native controls, grouping, selectors + captures | pending; not parity-complete | pending | | N1 | Connection settings/preferences | run 37 / flutter/n1-settings | running (Flash) | pending | pending | -| R1 | Run list/detail/live timeline | run 38 → continuation 40 / flutter/r1-runs-ui | manager rejected refresh/disposal bugs, missing new tests and native controls; pipeline correcting (Luna) | held | pending | +| R1 | Run list/detail/live timeline | run 38 → 40 → resume 41 / flutter/r1-runs-ui | 40 incomplete; smaller R1a controller + new tests now running (Luna); R1b native UI/captures next | held | pending | | D1 | Recorded changes/diff viewer | run 39 / flutter/d1-diff-viewer | running (Flash) | pending | pending | ## Next ready work @@ -58,6 +58,12 @@ to login, JS denies with 401, and proxied login responds 200. The served app is currently a shell with explicit unimplemented bodies, NOT a feature-complete app. No Android/iOS build or device verification has occurred. +Network preview update: per user request, the preview now binds 0.0.0.0:8096, +reachable at http://10.0.0.249:8096/ on the current LAN. Verified listener *:8096, +HTML login redirect 302 and unauthenticated JS 401 via the LAN address. Existing +proxy/API services remain unchanged. Bind command uses --host 0.0.0.0 explicitly; +the source default remains loopback for safety. + ### Manager integration findings - F3 candidate omitted `lib/features/runs/data/runs_repository.dart`: root runtime-data ignore matched source. Main 718442d adds an app-only exception; From a2b02b3810b8b76a31a8e0642dfc93c0b993bf68 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:48:35 +0100 Subject: [PATCH 18/84] Improve chat session catalog creation --- .../features/chat/data/chat_repository.dart | 30 ++-- .../ui/sessions/chat_sessions_screen.dart | 131 ++++++++++++++---- app/notes/C1.md | 4 +- .../features/chat/chat_foundation_test.dart | 20 +++ app/tool/chat_sessions_probe.mjs | 94 +++++++++++++ 5 files changed, 243 insertions(+), 36 deletions(-) create mode 100644 app/tool/chat_sessions_probe.mjs diff --git a/app/lib/features/chat/data/chat_repository.dart b/app/lib/features/chat/data/chat_repository.dart index 868408e7..90f2cc4d 100644 --- a/app/lib/features/chat/data/chat_repository.dart +++ b/app/lib/features/chat/data/chat_repository.dart @@ -39,17 +39,27 @@ class ChatRepository { 'chat_query': {'session_id': sessionId}, }))['chat_shells'], ); - Future> directories() async => - ((await gateway.call('chat_directories'))['chat_directories'] as List? ?? - const []) - .whereType() - .toList(); + Future> directories() async { + final value = (await gateway.call('chat_directories'))['chat_directories']; + if (value is! List) + throw StateError('Server did not return chat directories.'); + return value + .whereType() + .where((entry) => entry.trim().isNotEmpty) + .toList(); + } - Future> backends() async => - ((await gateway.call('chat_backends'))['chat_backends'] as List? ?? - const []) - .whereType() - .toList(); + Future> backends() async { + final value = (await gateway.call('chat_backends'))['chat_backends']; + if (value is! List) + throw StateError('Server did not return chat backends.'); + final result = value + .whereType() + .where((entry) => entry.trim().isNotEmpty) + .toList(); + if (result.isEmpty) throw StateError('Server returned no chat backends.'); + return result; + } Future shellOutput( String sessionId, diff --git a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart index c18476b0..e7ecd20f 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart @@ -117,34 +117,95 @@ class _ChatSessionsScreenState extends State { } Future _newChat() async { - final dirs = TextEditingController(); + List directories; + List backends; + try { + final catalog = await Future.wait([ + _repository.directories(), + _repository.backends(), + ]); + directories = catalog[0]; + backends = catalog[1]; + } catch (error) { + if (mounted) + setState(() => _error = 'Unable to load chat options: $error'); + return; + } + if (!mounted) return; + if (directories.isEmpty || backends.isEmpty) { + setState( + () => _error = + 'The server has no chat directories or backends available.', + ); + return; + } + final dirs = ValueNotifier(directories.first); + final backend = ValueNotifier(backends.first); final title = TextEditingController(text: 'New chat'); final instructions = TextEditingController(); final result = await showDialog< - ({String title, String directory, String instructions}) + ({ + String title, + String directory, + String backend, + String instructions, + }) >( context: context, builder: (context) => AlertDialog( title: const Text('New chat'), - content: Column( - mainAxisSize: MainAxisSize.min, - children: [ - TextField( - controller: title, - decoration: const InputDecoration(labelText: 'Name'), - ), - TextField( - controller: dirs, - decoration: const InputDecoration( - labelText: 'Server directory', + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + controller: title, + decoration: const InputDecoration(labelText: 'Name'), ), - ), - TextField( - controller: instructions, - decoration: const InputDecoration(labelText: 'Instructions'), - ), - ], + ValueListenableBuilder( + valueListenable: dirs, + builder: (context, value, _) => + DropdownButtonFormField( + initialValue: value, + decoration: const InputDecoration( + labelText: 'Server directory', + ), + items: [ + for (final item in directories) + DropdownMenuItem(value: item, child: Text(item)), + ], + onChanged: (item) { + if (item != null) dirs.value = item; + }, + ), + ), + ValueListenableBuilder( + valueListenable: backend, + builder: (context, value, _) => + DropdownButtonFormField( + initialValue: value, + decoration: const InputDecoration( + labelText: 'Backend', + ), + items: [ + for (final item in backends) + DropdownMenuItem(value: item, child: Text(item)), + ], + onChanged: (item) { + if (item != null) backend.value = item; + }, + ), + ), + const Text('New chats use the server default model.'), + TextField( + controller: instructions, + decoration: const InputDecoration( + labelText: 'Instructions', + ), + ), + ], + ), ), actions: [ TextButton( @@ -154,7 +215,8 @@ class _ChatSessionsScreenState extends State { FilledButton( onPressed: () => Navigator.pop(context, ( title: title.text.trim(), - directory: dirs.text.trim(), + directory: dirs.value, + backend: backend.value, instructions: instructions.text, )), child: const Text('Create'), @@ -164,6 +226,7 @@ class _ChatSessionsScreenState extends State { ); title.dispose(); dirs.dispose(); + backend.dispose(); instructions.dispose(); if (result == null) return; if (result.title.isEmpty || result.directory.isEmpty) { @@ -174,6 +237,7 @@ class _ChatSessionsScreenState extends State { final reply = await _repository.create( title: result.title, directory: result.directory, + backend: result.backend, operationId: 'native-chat-${DateTime.now().microsecondsSinceEpoch}', instructions: result.instructions, ); @@ -188,7 +252,9 @@ class _ChatSessionsScreenState extends State { @override Widget build(BuildContext context) { final visible = filterChatSessions(_sessions, _search.text); - final starred = visible.where((s) => s['starred'] == true).toList(); + final starred = visible + .where((s) => s['starred'] == true && s['closed_at'] == null) + .toList(); final open = visible .where((s) => s['starred'] != true && s['closed_at'] == null) .toList(); @@ -238,7 +304,22 @@ class _ChatSessionsScreenState extends State { if (open.isNotEmpty) _section('Chats', open), if (closed.isNotEmpty) _section('Closed', closed), if (visible.isEmpty && !_loading) - const ListTile(title: Text('No chats found.')), + ListTile( + title: Text( + _sessions.isEmpty + ? 'No chats yet.' + : 'No chats match "${_search.text.trim()}".', + ), + trailing: _search.text.isEmpty + ? null + : TextButton( + onPressed: () { + _search.clear(); + setState(() {}); + }, + child: const Text('Clear search'), + ), + ), ], ), ), @@ -257,11 +338,13 @@ class _ChatSessionsScreenState extends State { initiallyExpanded: true, children: [ for (final group in groupChatSessions(sessions)) ...[ - if (group.directory.isNotEmpty) + if (groupChatSessions(sessions).length > 1) ListTile( dense: true, leading: const Icon(Icons.folder_outlined), - title: Text(group.directory), + title: Text( + group.directory.isEmpty ? 'No directory' : group.directory, + ), ), for (final session in group.sessions) _row(session), ], diff --git a/app/notes/C1.md b/app/notes/C1.md index 4f79091c..8a4736f1 100644 --- a/app/notes/C1.md +++ b/app/notes/C1.md @@ -1,5 +1,5 @@ # C1 — Chat sessions and repository adapter -Implemented the native Material sessions browser, search, directory grouping, starred/closed groups, standard session actions, and explicit-directory create dialog. Opening a session only invokes the supplied callback. The chat repository includes the web-compatible native message ID, prompt validation, Web permission label, and 200-message history default. +The sessions browser now requests server directory and backend catalogs before showing the create dialog, exposes both selectors and model-default guidance, and reports unavailable catalog capabilities instead of silently substituting values. Catalog envelope regressions are covered. Closed starred rows no longer appear twice; directory headings appear only when grouping multiple directories; empty and search-no-match states are distinct. -Verification: `flutter test test/features/chat` passed. Browser build/captures and mobile builds were not performed here. The fixture entry point is `tool/chat_sessions_probe_entry.dart`; a separate browser review should exercise the rendered states and capture them before claiming UI acceptance. +Verification: focused chat tests, `flutter analyze`, fixture `flutter build web -t tool/chat_sessions_probe_entry.dart`, `git diff --check`, and an isolated Chrome DevTools probe passed. Captures: `/private/var/folders/jp/q0qvjyg54fl_c5vhhk1ylz2m0000gn/T/opencode/chat-sessions-capture/chat-sessions-phone.png` and `chat-sessions-create-dialog.png` (plus desktop). The probe enabled semantics, matched the exact “New chat” label, and verified the rendered body changed to show server catalog controls. Cupertino-specific controls, controller/row/dialog decomposition under 250 lines, and wider out-of-order reply UI regression coverage remain incomplete; this is not a parity-complete delivery. Mobile builds were not performed. The fixture entry point is `tool/chat_sessions_probe_entry.dart`. diff --git a/app/test/features/chat/chat_foundation_test.dart b/app/test/features/chat/chat_foundation_test.dart index 7067c9a1..fd7b7b6a 100644 --- a/app/test/features/chat/chat_foundation_test.dart +++ b/app/test/features/chat/chat_foundation_test.dart @@ -292,5 +292,25 @@ void main() { expect(gateway.calls.single.fields['chat_query']['limit'], 200); }, ); + test( + 'reads exact directory/backend catalog envelopes without inventing fallback', + () async { + gateway.reply = { + 'chat_directories': ['~', '/work'], + }; + expect(await repo.directories(), ['~', '/work']); + expect(gateway.calls.last.type, 'chat_directories'); + expect(gateway.calls.last.fields, isEmpty); + gateway.reply = { + 'chat_backends': ['opencode', 'claude'], + }; + expect(await repo.backends(), ['opencode', 'claude']); + expect(gateway.calls.last.type, 'chat_backends'); + expect(gateway.calls.last.fields, isEmpty); + gateway.reply = {}; + await expectLater(repo.directories(), throwsStateError); + await expectLater(repo.backends(), throwsStateError); + }, + ); }); } diff --git a/app/tool/chat_sessions_probe.mjs b/app/tool/chat_sessions_probe.mjs new file mode 100644 index 00000000..7fccb3fb --- /dev/null +++ b/app/tool/chat_sessions_probe.mjs @@ -0,0 +1,94 @@ +import { createServer } from 'node:http'; +import { readFile } 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 { mkdtemp, rm } from 'node:fs/promises'; + +const root = join(process.cwd(), 'build/web'); +const mime = { '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.wasm': 'application/wasm', '.png': 'image/png', '.ico': 'image/x-icon' }; +const server = createServer(async (req, res) => { + try { + const path = resolve(root, '.' + decodeURIComponent(new URL(req.url, 'http://localhost').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' }).end(file); + } catch { res.writeHead(404).end('not found'); } +}); +server.listen(0, '127.0.0.1'); +await once(server, 'listening'); +const port = server.address().port; + const profile = await mkdtemp(join(tmpdir(), 'chat-sessions-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; }); +const waitFor = async fn => { + for (let i = 0; i < 100; i++) { const value = await fn(); if (value) return value; await delay(100); } + throw new Error('Timed out waiting for Chrome DevTools'); +}; +let ws; +try { + const endpoint = await waitFor(() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1]); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + ws.addEventListener('message', event => { + const msg = JSON.parse(event.data); + if (msg.method?.includes('detached') || msg.method?.includes('crashed')) console.error('CDP event', JSON.stringify(msg)); + if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); } + }); + const send = (method, params = {}, sessionId) => new Promise(resolve => { + const callId = ++id; pending.set(callId, resolve); + 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); + const navigation = await send('Page.navigate', { url: `http://127.0.0.1:${port}/` }, session); + if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation)); + 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)}`); + return response.result?.result?.value; + }; + await delay(3500); + const loaded = await evaluate("({url:location.href, ready:document.readyState, body:document.body.innerText, html:document.body.innerHTML.slice(0,500)})"); + if (!loaded?.url.includes(`127.0.0.1:${port}`)) throw new Error(`Fixture did not load: ${JSON.stringify(loaded)}`); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(2500); + const clickLabel = async label => evaluate(`(() => { const e=[...document.querySelectorAll('flt-semantics')].find(x => (x.getAttribute('aria-label') || x.innerText || '') === ${JSON.stringify(label)}); if (!e) return false; e.click(); return true; })()`); + const labels = await evaluate("[...document.querySelectorAll('flt-semantics')].map(x=>x.getAttribute('aria-label')||x.innerText).filter(Boolean)"); + if (!labels?.some(x => x.includes('New chat'))) throw new Error(`Chat fixture semantics unavailable: ${JSON.stringify(labels)}`); + const capture = async (name, width, height) => { + await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 }, session); + await delay(350); + const data = (await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session)).result.data; + await (await import('node:fs/promises')).writeFile(`${process.env.OPENCODE_ARTIFACT_DIR}/${name}.png`, Buffer.from(data, 'base64')); + }; + await capture('chat-sessions-phone', 390, 844); + if (!await clickLabel('New chat')) throw new Error('Could not open create dialog'); + await delay(500); + await send('Input.dispatchMouseEvent', { type: 'mouseWheel', x: 195, y: 680, deltaY: 598 }, session); + await delay(350); + const changedBody = await evaluate('document.body.innerText'); + await capture('chat-sessions-create-dialog', 390, 844); + if (!changedBody.includes('Server directory') || !changedBody.includes('Backend') || !changedBody.includes('New chats use the server default model.') || changedBody.includes('Open fixture')) throw new Error(`Create dialog did not change rendered body to catalog controls: ${changedBody}`); + await capture('chat-sessions-desktop', 1280, 800); + console.log(JSON.stringify({ labels, captures: ['chat-sessions-phone.png', 'chat-sessions-create-dialog.png', 'chat-sessions-desktop.png'], bodyChanged: true }, 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 }); +} From 13d8ddac5d8bf6b827923935c8a7f9248407717d Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:49:18 +0100 Subject: [PATCH 19/84] Tidy chat catalog error handling --- app/lib/features/chat/data/chat_repository.dart | 6 ++++-- app/lib/features/chat/ui/sessions/chat_sessions_screen.dart | 3 ++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/app/lib/features/chat/data/chat_repository.dart b/app/lib/features/chat/data/chat_repository.dart index 90f2cc4d..b97bd52a 100644 --- a/app/lib/features/chat/data/chat_repository.dart +++ b/app/lib/features/chat/data/chat_repository.dart @@ -41,8 +41,9 @@ class ChatRepository { ); Future> directories() async { final value = (await gateway.call('chat_directories'))['chat_directories']; - if (value is! List) + if (value is! List) { throw StateError('Server did not return chat directories.'); + } return value .whereType() .where((entry) => entry.trim().isNotEmpty) @@ -51,8 +52,9 @@ class ChatRepository { Future> backends() async { final value = (await gateway.call('chat_backends'))['chat_backends']; - if (value is! List) + if (value is! List) { throw StateError('Server did not return chat backends.'); + } final result = value .whereType() .where((entry) => entry.trim().isNotEmpty) diff --git a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart index e7ecd20f..b6a88d89 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart @@ -127,8 +127,9 @@ class _ChatSessionsScreenState extends State { directories = catalog[0]; backends = catalog[1]; } catch (error) { - if (mounted) + if (mounted) { setState(() => _error = 'Unable to load chat options: $error'); + } return; } if (!mounted) return; From b404232f8428f65cda54c04578ede41ce7808a46 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:50:32 +0100 Subject: [PATCH 20/84] docs(app): route chat native-controls completion through pipeline --- app/WORK.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/WORK.md b/app/WORK.md index c3c2bf90..15167087 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -13,7 +13,7 @@ All work under app/. Existing applications remain running and unchanged. | F4 | Chat models, history/live fold, request facade | run 33 / flutter/f4-chat | pipeline passed; wire omissions carried into C1 | pending C1 adapter fixes | — | | F5 | Isolated authenticated web preview tooling | run 30 + ae352bb | 6 proxy fixtures incl auth/bytes/origin/idle sockets pass | main 160ab45, ancestry verified | http://127.0.0.1:8096/ | | P1 | Pipeline list/detail/source/version browser | run 34 / flutter/p1-pipelines | running (DeepSeek V4.1 Flash) | pending | pending | -| C1 | Chat session browser and management | run 35 → resume 36 / flutter/f4-chat | pipeline passed; manager finishing native controls, grouping, selectors + captures | pending; not parity-complete | pending | +| C1 | Chat session browser and management | 35 → resume 36 → focused C1b run 42 / flutter/f4-chat | catalog/grouping fixes + inspected browser captures retained; pipeline splitting 406-line screen and adding Cupertino/tests (Flash) | held; not parity-complete | pending | | N1 | Connection settings/preferences | run 37 / flutter/n1-settings | running (Flash) | pending | pending | | R1 | Run list/detail/live timeline | run 38 → 40 → resume 41 / flutter/r1-runs-ui | 40 incomplete; smaller R1a controller + new tests now running (Luna); R1b native UI/captures next | held | pending | | D1 | Recorded changes/diff viewer | run 39 / flutter/d1-diff-viewer | running (Flash) | pending | pending | From 6b8d5ea32e1201251954eb00ec471a87ad051bfe Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:51:07 +0100 Subject: [PATCH 21/84] feat(app): complete runs UI candidate --- app/lib/features/runs/ui/run_detail_view.dart | 4 +- app/lib/features/runs/ui/runs_controller.dart | 156 +++++++++++++++--- app/lib/features/runs/ui/runs_list.dart | 8 + app/notes/R1a.md | 7 + .../runs/ui/runs_controller_test.dart | 132 +++++++++++++++ 5 files changed, 285 insertions(+), 22 deletions(-) create mode 100644 app/notes/R1a.md create mode 100644 app/test/features/runs/ui/runs_controller_test.dart diff --git a/app/lib/features/runs/ui/run_detail_view.dart b/app/lib/features/runs/ui/run_detail_view.dart index c1bd01c5..a2814712 100644 --- a/app/lib/features/runs/ui/run_detail_view.dart +++ b/app/lib/features/runs/ui/run_detail_view.dart @@ -8,7 +8,7 @@ class RunDetailView extends StatelessWidget { @override Widget build(BuildContext context) { final run = controller.detail; - if (controller.loading && run == null) { + if (controller.detailLoading && run == null) { return const Center(child: CircularProgressIndicator()); } if (run == null) { @@ -84,7 +84,7 @@ class RunDetailView extends StatelessWidget { ), ), ), - const ListTile(title: Text('Metrics'), subtitle: Text('Unavailable')), + _section(context, 'Metrics', run['usage'] is Map ? run['usage'] as Map : const {}), ], ); } diff --git a/app/lib/features/runs/ui/runs_controller.dart b/app/lib/features/runs/ui/runs_controller.dart index 02fa8bf8..9eac5db5 100644 --- a/app/lib/features/runs/ui/runs_controller.dart +++ b/app/lib/features/runs/ui/runs_controller.dart @@ -10,12 +10,19 @@ class RunsController extends ChangeNotifier { final RunsRepository repository; StreamSubscription? _subscription; List runs = []; - JsonMap? detail; + JsonMap? detail, usage; String? error; - bool loading = false; - String query = '', sort = 'newest_first'; + bool loading = false, detailLoading = false; + String query = '', + sort = 'newest_first', + scheduled = 'any', + timeRange = 'any_time'; + final Set statuses = {}; + int? pipelineId; int _selection = 0; + num? _selectedId; Timer? _refresh; + bool _refreshInFlight = false, _refreshAgain = false, _disposed = false; void listen(Stream frames) { _subscription?.cancel(); @@ -31,13 +38,18 @@ class RunsController extends ChangeNotifier { notifyListeners(); try { final result = await repository.listRuns(); - if (token != _selection) return; + if (_disposed || token != _selection) return; runs = result.runs; - if (initialId != null) await select(initialId); + usage = result.usage; + if (initialId != null) { + // Keep list and detail request generations independent: selecting the + // initial row must not make this list request's completion stale. + await select(initialId); + } } catch (e) { - if (token == _selection) error = '$e'; + if (!_disposed && token == _selection) error = '$e'; } - if (token == _selection) { + if (!_disposed && token == _selection) { loading = false; notifyListeners(); } @@ -45,25 +57,33 @@ class RunsController extends ChangeNotifier { Future select(num id) async { final token = ++_selection; - detail = null; + _refresh?.cancel(); + _refresh = null; + _refreshAgain = false; + _selectedId = id; + detailLoading = true; error = null; - loading = true; notifyListeners(); try { final value = await repository.getRun(id); - if (token == _selection) detail = value; + if (!_disposed && token == _selection) detail = value; } catch (e) { - if (token == _selection) error = '$e'; + if (!_disposed && token == _selection) error = '$e'; } - if (token == _selection) { - loading = false; + if (!_disposed && token == _selection) { + detailLoading = false; notifyListeners(); } } void back() { ++_selection; + _selectedId = null; + _refresh?.cancel(); + _refresh = null; + _refreshAgain = false; detail = null; + detailLoading = false; error = null; notifyListeners(); } @@ -73,24 +93,118 @@ class RunsController extends ChangeNotifier { notifyListeners(); } + void setStatus(String? value) { + if (value == null) { + statuses.clear(); + } else if (!statuses.add(value)) { + statuses.remove(value); + } + notifyListeners(); + } + + void setPipeline(int? value) { + pipelineId = value; + notifyListeners(); + } + + void setScheduled(String value) { + scheduled = value; + notifyListeners(); + } + + void setSort(String value) { + sort = value; + notifyListeners(); + } + void _event(JsonMap frame) { final folded = foldRunEvent(runs, frame); runs = folded.runs; if (detail?['id'] == frame['run_id']) { detail = foldRunEventDetail(detail, frame); } - if (detail != null && runDetailNeedsFullSync(frame)) { - _refresh?.cancel(); - _refresh = Timer( - const Duration(milliseconds: 150), - () => select(detail!['id'] as num), - ); + if (frame['run_id'] == null || folded.needsResync) { + _scheduleListRefresh(); + } + if (_selectedId != null && + frame['run_id'] == _selectedId && + (folded.needsResync || runDetailNeedsFullSync(frame))) { + if (_refreshInFlight) { + _refreshAgain = true; + } else { + _refresh?.cancel(); + final id = _selectedId!; + final generation = _selection; + _refresh = Timer( + const Duration(milliseconds: 150), + () => _refreshDetail(id, generation), + ); + } } notifyListeners(); } + void _scheduleListRefresh() { + if (_disposed || loading) return; + loading = true; + notifyListeners(); + unawaited(_reloadList()); + } + + Future _reloadList() async { + try { + final result = await repository.listRuns(); + if (_disposed) return; + runs = result.runs; + usage = result.usage; + error = null; + } catch (e) { + if (!_disposed) error = '$e'; + } finally { + if (!_disposed) { + loading = false; + notifyListeners(); + } + } + } + + Future _refreshDetail(num id, int generation) async { + if (_disposed || generation != _selection || _selectedId != id) return; + _refreshInFlight = true; + try { + final value = await repository.getRun(id); + if (!_disposed && generation == _selection && _selectedId == id) { + detail = value; + notifyListeners(); + } + } catch (e) { + if (!_disposed && generation == _selection && _selectedId == id) { + error = '$e'; + notifyListeners(); + } + } finally { + _refreshInFlight = false; + if (!_disposed && + _refreshAgain && + generation == _selection && + _selectedId == id) { + _refreshAgain = false; + _refresh = Timer( + const Duration(milliseconds: 150), + () => _refreshDetail(id, generation), + ); + } + } + } + List get visibleRuns => sortRuns( - runs + filterRuns( + runs, + statuses: statuses, + pipelineId: pipelineId, + scheduled: scheduled, + timeRange: timeRange, + ) .where( (r) => '${r['title'] ?? r['name'] ?? ''}'.toLowerCase().contains( query.toLowerCase(), @@ -99,8 +213,10 @@ class RunsController extends ChangeNotifier { .toList(), sort: sort, ); + @override void dispose() { + _disposed = true; _subscription?.cancel(); _refresh?.cancel(); super.dispose(); diff --git a/app/lib/features/runs/ui/runs_list.dart b/app/lib/features/runs/ui/runs_list.dart index 9ab2d1b8..f168ab89 100644 --- a/app/lib/features/runs/ui/runs_list.dart +++ b/app/lib/features/runs/ui/runs_list.dart @@ -27,6 +27,8 @@ class RunsList extends StatelessWidget { } return Column( children: [ + if (controller.usage != null) + Padding(padding: const EdgeInsets.symmetric(horizontal: 16), child: Text('Usage: ${controller.usage}')), if (controller.error != null) MaterialBanner( content: Text(controller.error!), @@ -44,6 +46,12 @@ class RunsList extends StatelessWidget { onChanged: controller.setQuery, ), ), + Wrap(spacing: 8, children: [ + DropdownButton(value: controller.sort, onChanged: (v) { if (v != null) controller.setSort(v); }, items: const [DropdownMenuItem(value: 'newest_first', child: Text('Newest')), DropdownMenuItem(value: 'oldest_first', child: Text('Oldest')), DropdownMenuItem(value: 'pipeline_name', child: Text('Pipeline')), DropdownMenuItem(value: 'status', child: Text('Status'))]), + DropdownButton(value: controller.scheduled, onChanged: (v) { if (v != null) controller.setScheduled(v); }, items: const [DropdownMenuItem(value: 'any', child: Text('Any schedule')), DropdownMenuItem(value: 'scheduled', child: Text('Scheduled')), DropdownMenuItem(value: 'unscheduled', child: Text('Unscheduled'))]), + for (final status in ['queued', 'running', 'waiting', 'succeeded', 'failed']) + FilterChip(label: Text(status), selected: controller.statuses.contains(status), onSelected: (_) => controller.setStatus(status)), + ]), Expanded( child: controller.visibleRuns.isEmpty ? const Center(child: Text('No runs found.')) diff --git a/app/notes/R1a.md b/app/notes/R1a.md new file mode 100644 index 00000000..b43992bd --- /dev/null +++ b/app/notes/R1a.md @@ -0,0 +1,7 @@ +# R1a — runs controller correctness + +Implemented in `runs_controller.dart`: selection requests now retain prior detail while loading and ignore stale/disposed replies; list and detail loading indicators are independent; Back invalidates selection and cancels scheduled refresh; selected-run refreshes use captured ID/generation and preserve detail until the reply; identity-less or unresolvable run events trigger list resynchronization. + +Added six fake-gateway regression tests in `test/features/runs/ui/runs_controller_test.dart` for stale selection, pending futures after disposal, Back cancellation, unrelated events, identity-less list resync, and full-refresh detail retention. + +Verification: `flutter test test/features/runs/ui` passed (6 tests), `flutter analyze` passed with no issues, and `flutter build web` passed. Cupertino UI/browser evidence is outside this R1a slice and remains incomplete for the overall R1 task; mobile is unverified. diff --git a/app/test/features/runs/ui/runs_controller_test.dart b/app/test/features/runs/ui/runs_controller_test.dart new file mode 100644 index 00000000..3b764422 --- /dev/null +++ b/app/test/features/runs/ui/runs_controller_test.dart @@ -0,0 +1,132 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/data/runs_repository.dart'; +import 'package:pipelines_app/features/runs/ui/runs_controller.dart'; + +class FakeGateway implements ApiGateway { + final framesController = StreamController.broadcast(); + final lists = >[]; + final details = >>{}; + int listCalls = 0; + @override + Stream get frames => framesController.stream; + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type == 'list_runs') { + listCalls++; + final request = Completer(); + lists.add(request); + return request.future; + } + final id = fields['run_id'] as num; + final request = Completer(); + details.putIfAbsent(id, () => []).add(request); + return request.future; + } + + void listReply(int index, List runs) => + lists[index].complete({'runs': runs}); + void detailReply(num id, int index, JsonMap value) => + details[id]![index].complete({'run_detail': value}); +} + +void main() { + late FakeGateway gateway; + late RunsController controller; + var disposed = false; + setUp(() { + gateway = FakeGateway(); + controller = RunsController(RunsRepository(gateway)); + disposed = false; + }); + tearDown(() { + if (!disposed) controller.dispose(); + gateway.framesController.close(); + }); + + test('late selection response cannot replace latest selection', () async { + final first = controller.select(1); + final second = controller.select(2); + gateway.detailReply(2, 0, {'id': 2}); + await second; + gateway.detailReply(1, 0, {'id': 1}); + await first; + expect(controller.detail?['id'], 2); + }); + + test('pending load and selection futures are safe after dispose', () async { + final load = controller.load(); + final select = controller.select(1); + controller.dispose(); + disposed = true; + gateway.listReply(0, []); + gateway.detailReply(1, 0, {'id': 1}); + await Future.wait([load, select]); + }); + + test('Back cancels scheduled detail refresh', () async { + final select = controller.select(1); + gateway.detailReply(1, 0, {'id': 1, 'status': 'running'}); + await select; + controller.listen(gateway.frames); + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 1, + 'status': 'succeeded', + }); + controller.back(); + await Future.delayed(const Duration(milliseconds: 220)); + expect(gateway.details[1], hasLength(1)); + expect(controller.detail, isNull); + }); + + test('unrelated run event does not refresh selected detail', () async { + final select = controller.select(1); + gateway.detailReply(1, 0, {'id': 1, 'status': 'running'}); + await select; + controller.listen(gateway.frames); + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 2, + 'status': 'succeeded', + }); + await Future.delayed(const Duration(milliseconds: 220)); + expect(gateway.details[1], hasLength(1)); + }); + + test('identity-less event reloads list', () async { + controller.listen(gateway.frames); + gateway.framesController.add({'type': 'run_event', 'status': 'running'}); + await Future.delayed(Duration.zero); + expect(gateway.listCalls, 1); + gateway.listReply(0, [ + {'id': 3}, + ]); + await Future.delayed(Duration.zero); + expect(controller.runs.single['id'], 3); + expect(controller.loading, isFalse); + }); + + test( + 'full refresh is coalesced and keeps current detail until reply', + () async { + final select = controller.select(1); + gateway.detailReply(1, 0, {'id': 1, 'status': 'running'}); + await select; + controller.listen(gateway.frames); + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 1, + 'status': 'succeeded', + }); + await Future.delayed(const Duration(milliseconds: 180)); + expect(controller.detail?['id'], 1); + expect(gateway.details[1], hasLength(2)); + gateway.detailReply(1, 1, {'id': 1, 'status': 'succeeded'}); + await Future.delayed(Duration.zero); + expect(controller.detail?['status'], 'succeeded'); + }, + ); +} From 38895a975bf14377affa56b085be6cee2507e2b3 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:53:02 +0100 Subject: [PATCH 22/84] docs(app): parallelize run-controller final fixes and native presentation --- app/WORK.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/WORK.md b/app/WORK.md index 15167087..22334a78 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -15,7 +15,7 @@ All work under app/. Existing applications remain running and unchanged. | P1 | Pipeline list/detail/source/version browser | run 34 / flutter/p1-pipelines | running (DeepSeek V4.1 Flash) | pending | pending | | C1 | Chat session browser and management | 35 → resume 36 → focused C1b run 42 / flutter/f4-chat | catalog/grouping fixes + inspected browser captures retained; pipeline splitting 406-line screen and adding Cupertino/tests (Flash) | held; not parity-complete | pending | | N1 | Connection settings/preferences | run 37 / flutter/n1-settings | running (Flash) | pending | pending | -| R1 | Run list/detail/live timeline | run 38 → 40 → resume 41 / flutter/r1-runs-ui | 40 incomplete; smaller R1a controller + new tests now running (Luna); R1b native UI/captures next | held | pending | +| R1 | Run list/detail/live timeline | 38 → 40 → resume 41; now R1b run 43 + R1c run 44 | 6 new controller tests passed; remaining independent-list-generation race sent to Flash, native UI/browser lane runs concurrently on Luna | held | pending | | D1 | Recorded changes/diff viewer | run 39 / flutter/d1-diff-viewer | running (Flash) | pending | pending | ## Next ready work From 4bc95f47bef81a2c51d8baf1f834851113848db1 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:54:52 +0100 Subject: [PATCH 23/84] fix(app): isolate runs list and detail request generations --- app/lib/features/runs/ui/runs_controller.dart | 160 ++++++++----- app/notes/R1b.md | 55 +++++ .../runs/ui/runs_controller_test.dart | 212 ++++++++++++++++++ 3 files changed, 365 insertions(+), 62 deletions(-) create mode 100644 app/notes/R1b.md diff --git a/app/lib/features/runs/ui/runs_controller.dart b/app/lib/features/runs/ui/runs_controller.dart index 9eac5db5..977d8223 100644 --- a/app/lib/features/runs/ui/runs_controller.dart +++ b/app/lib/features/runs/ui/runs_controller.dart @@ -19,10 +19,16 @@ class RunsController extends ChangeNotifier { timeRange = 'any_time'; final Set statuses = {}; int? pipelineId; - int _selection = 0; + // List and detail requests advance independent generations so neither can + // make the other's in-flight reply stale. + int _listGeneration = 0, _detailGeneration = 0; num? _selectedId; - Timer? _refresh; - bool _refreshInFlight = false, _refreshAgain = false, _disposed = false; + Timer? _detailRefresh; + bool _listResyncing = false, _listAgain = false; + bool _detailRefreshing = false, _detailAgain = false; + bool _disposed = false; + + num? get selectedRunId => _selectedId; void listen(Stream frames) { _subscription?.cancel(); @@ -32,56 +38,56 @@ class RunsController extends ChangeNotifier { } Future load([int? initialId]) async { - final token = ++_selection; + final token = ++_listGeneration; + _listAgain = false; loading = true; error = null; notifyListeners(); try { final result = await repository.listRuns(); - if (_disposed || token != _selection) return; + if (!_listOwned(token)) return; runs = result.runs; usage = result.usage; - if (initialId != null) { - // Keep list and detail request generations independent: selecting the - // initial row must not make this list request's completion stale. - await select(initialId); - } } catch (e) { - if (!_disposed && token == _selection) error = '$e'; - } - if (!_disposed && token == _selection) { - loading = false; - notifyListeners(); + if (!_listOwned(token)) return; + error = '$e'; } + if (!_listOwned(token)) return; + loading = false; + notifyListeners(); + // A run event may have arrived while the list request was in flight; one + // resync after it keeps the pushed state without dropping the event. + _resyncAgainIfNeeded(); + if (initialId != null) await select(initialId); } Future select(num id) async { - final token = ++_selection; - _refresh?.cancel(); - _refresh = null; - _refreshAgain = false; + final token = ++_detailGeneration; + _cancelDetailRefresh(); + // Keep a same-run detail while it refreshes, but never present the previous + // run as if it were the newly selected one. + if (_selectedId != id) detail = null; _selectedId = id; detailLoading = true; error = null; notifyListeners(); try { final value = await repository.getRun(id); - if (!_disposed && token == _selection) detail = value; + if (!_detailOwned(id, token)) return; + detail = value; } catch (e) { - if (!_disposed && token == _selection) error = '$e'; - } - if (!_disposed && token == _selection) { - detailLoading = false; - notifyListeners(); + if (!_detailOwned(id, token)) return; + error = '$e'; } + if (!_detailOwned(id, token)) return; + detailLoading = false; + notifyListeners(); } void back() { - ++_selection; + ++_detailGeneration; + _cancelDetailRefresh(); _selectedId = null; - _refresh?.cancel(); - _refresh = null; - _refreshAgain = false; detail = null; detailLoading = false; error = null; @@ -126,77 +132,107 @@ class RunsController extends ChangeNotifier { if (frame['run_id'] == null || folded.needsResync) { _scheduleListRefresh(); } - if (_selectedId != null && - frame['run_id'] == _selectedId && + final selected = _selectedId; + if (selected != null && + frame['run_id'] == selected && (folded.needsResync || runDetailNeedsFullSync(frame))) { - if (_refreshInFlight) { - _refreshAgain = true; - } else { - _refresh?.cancel(); - final id = _selectedId!; - final generation = _selection; - _refresh = Timer( - const Duration(milliseconds: 150), - () => _refreshDetail(id, generation), - ); - } + _scheduleDetailRefresh(selected); } notifyListeners(); } void _scheduleListRefresh() { - if (_disposed || loading) return; + if (_disposed) return; + if (_listResyncing || loading) { + _listAgain = true; + return; + } + _listResyncing = true; loading = true; notifyListeners(); unawaited(_reloadList()); } Future _reloadList() async { + final token = ++_listGeneration; + _listAgain = false; try { final result = await repository.listRuns(); - if (_disposed) return; + if (!_listOwned(token)) return; runs = result.runs; usage = result.usage; error = null; } catch (e) { - if (!_disposed) error = '$e'; + if (_listOwned(token)) error = '$e'; } finally { - if (!_disposed) { + _listResyncing = false; + if (_listOwned(token)) { loading = false; notifyListeners(); } + // A followup may have been requested while this (possibly superseded) + // request was still the one marked in flight. + _resyncAgainIfNeeded(); } } - Future _refreshDetail(num id, int generation) async { - if (_disposed || generation != _selection || _selectedId != id) return; - _refreshInFlight = true; + void _resyncAgainIfNeeded() { + if (_disposed || !_listAgain) return; + _listAgain = false; + _scheduleListRefresh(); + } + + void _scheduleDetailRefresh(num id) { + if (_disposed || _selectedId != id) return; + if (_detailRefreshing) { + _detailAgain = true; + return; + } + _detailRefresh?.cancel(); + _detailRefresh = Timer( + const Duration(milliseconds: 150), + () => _refreshDetail(id, _detailGeneration), + ); + } + + Future _refreshDetail(num id, int token) async { + _detailRefresh = null; + if (!_detailOwned(id, token)) return; + _detailRefreshing = true; try { final value = await repository.getRun(id); - if (!_disposed && generation == _selection && _selectedId == id) { + if (_detailOwned(id, token)) { detail = value; notifyListeners(); } } catch (e) { - if (!_disposed && generation == _selection && _selectedId == id) { + if (_detailOwned(id, token)) { error = '$e'; notifyListeners(); } } finally { - _refreshInFlight = false; - if (!_disposed && - _refreshAgain && - generation == _selection && - _selectedId == id) { - _refreshAgain = false; - _refresh = Timer( - const Duration(milliseconds: 150), - () => _refreshDetail(id, generation), - ); + if (_detailOwned(id, token)) { + _detailRefreshing = false; + if (_detailAgain) { + _detailAgain = false; + unawaited(_refreshDetail(id, token)); + } } } } + void _cancelDetailRefresh() { + _detailRefresh?.cancel(); + _detailRefresh = null; + _detailAgain = false; + _detailRefreshing = false; + } + + bool _listOwned(int token) => !_disposed && token == _listGeneration; + + bool _detailOwned(num id, int token) => + !_disposed && token == _detailGeneration && _selectedId == id; + List get visibleRuns => sortRuns( filterRuns( runs, @@ -218,7 +254,7 @@ class RunsController extends ChangeNotifier { void dispose() { _disposed = true; _subscription?.cancel(); - _refresh?.cancel(); + _detailRefresh?.cancel(); super.dispose(); } } diff --git a/app/notes/R1b.md b/app/notes/R1b.md new file mode 100644 index 00000000..406dec62 --- /dev/null +++ b/app/notes/R1b.md @@ -0,0 +1,55 @@ +# R1b — runs controller request independence + +Focused correctness fix on retained candidate `6b8d5ea`. Files: +`lib/features/runs/ui/runs_controller.dart`, +`test/features/runs/ui/runs_controller_test.dart`. + +## Fixes + +- List and detail requests now use independent generations (`_listGeneration`, + `_detailGeneration`). `load(initialId)` no longer bumps the detail generation + that `select(initialId)` also advances, so both `loading` and `detailLoading` + clear when the requests resolve. Manual list loads also no longer invalidate + valid detail refreshes. +- List resyncs (`_reloadList`) capture and check a list generation, so a stale + reply cannot overwrite a newer `load()`. Concurrent resync requests are + coalesced into exactly one followup; a resync requested during a manual load + runs after that load instead of being dropped. +- Detail refreshes capture the current detail generation and selected run. + Same-id refreshes keep the existing detail and are coalesced (in-flight plus + one followup). Selecting a different run clears the previous detail instead of + presenting it as the new run. Back/dispose invalidate pending replies, and + stale requests cannot clear another generation's loading flags. +- Added `num? get selectedRunId` for the native UI lane. All existing public + methods and fields are preserved. + +The existing 150 ms event debounce is retained; no polling or extra timers were +introduced. File is 260 lines; the fix stays within the controller responsibility +rather than fragmenting it. + +## Tests + +Extended `test/features/runs/ui/runs_controller_test.dart` with regressions for: + +- `load(initialId)` resolves with `loading == false` and `detailLoading == false`. +- Overlapping list loads with reversed completion order: newer reply wins. +- List resync leaves the selected detail request valid. +- Manual `load()` does not invalidate an in-flight detail refresh. +- Sparse unknown run events coalesce into one followup resync. +- A followup requested while a superseded resync is still marked in flight + starts once that stale reply arrives instead of being stranded. +- Selected refresh coalescing (in-flight plus followup) and Back ignoring the + pending reply. +- Choosing another run does not display the previous run's detail. +- Pending detail refresh is safe after dispose. + +Existing six regression tests remain and pass. + +## Verification + +- `/Users/alan/development/flutter/bin/flutter test test/features/runs/ui` — 15 tests passed. +- `/Users/alan/development/flutter/bin/flutter test test/features/runs` — 26 tests passed. +- `/Users/alan/development/flutter/bin/flutter analyze` — no issues found. +- `flutter build web` not run in this NONVISUAL controller slice; manager + integration/UI review owns rendered and build acceptance. +- Mobile remains unverified; no device or browser tools used. diff --git a/app/test/features/runs/ui/runs_controller_test.dart b/app/test/features/runs/ui/runs_controller_test.dart index 3b764422..0945f77b 100644 --- a/app/test/features/runs/ui/runs_controller_test.dart +++ b/app/test/features/runs/ui/runs_controller_test.dart @@ -129,4 +129,216 @@ void main() { expect(controller.detail?['status'], 'succeeded'); }, ); + + test('load with initial id clears list and detail loading', () async { + final load = controller.load(7); + expect(controller.loading, isTrue); + gateway.listReply(0, [ + {'id': 7}, + {'id': 8}, + ]); + await Future.delayed(Duration.zero); + expect(gateway.details[7], hasLength(1)); + expect(controller.loading, isFalse); + expect(controller.detailLoading, isTrue); + gateway.detailReply(7, 0, {'id': 7}); + await load; + expect(controller.loading, isFalse); + expect(controller.detailLoading, isFalse); + expect(controller.detail?['id'], 7); + expect(controller.selectedRunId, 7); + }); + + test('newer list load wins when replies complete out of order', () async { + final first = controller.load(); + final second = controller.load(); + gateway.listReply(1, [ + {'id': 2}, + ]); + await second; + gateway.listReply(0, [ + {'id': 1}, + ]); + await first; + expect(controller.runs.single['id'], 2); + expect(controller.loading, isFalse); + }); + + test('list resync leaves the selected detail request valid', () async { + final select = controller.select(1); + gateway.detailReply(1, 0, {'id': 1, 'status': 'running'}); + await select; + controller.listen(gateway.frames); + gateway.framesController.add({'type': 'run_event', 'status': 'running'}); + await Future.delayed(Duration.zero); + expect(gateway.listCalls, 1); + gateway.listReply(0, [ + {'id': 1, 'status': 'running'}, + ]); + await Future.delayed(Duration.zero); + expect(controller.detail?['id'], 1); + expect(controller.selectedRunId, 1); + expect(gateway.details[1], hasLength(1)); + }); + + test('manual list load keeps an in-flight detail refresh valid', () async { + final select = controller.select(1); + gateway.detailReply(1, 0, {'id': 1, 'status': 'running'}); + await select; + controller.listen(gateway.frames); + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 1, + 'status': 'succeeded', + }); + await Future.delayed(const Duration(milliseconds: 180)); + expect(gateway.details[1], hasLength(2)); + final load = controller.load(); + gateway.listReply(1, [ + {'id': 1}, + ]); + await load; + gateway.detailReply(1, 1, {'id': 1, 'status': 'succeeded'}); + await Future.delayed(Duration.zero); + expect(controller.detail?['status'], 'succeeded'); + expect(controller.detailLoading, isFalse); + gateway.listReply(0, [ + {'id': 1}, + ]); + }); + + test('event during a superseded resync still runs one followup', () async { + controller.listen(gateway.frames); + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 9, + 'status': 'running', + }); + await Future.delayed(Duration.zero); + expect(gateway.listCalls, 1); + final load = controller.load(); + expect(gateway.listCalls, 2); + gateway.listReply(1, [ + {'id': 1}, + ]); + await load; + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 10, + 'status': 'running', + }); + await Future.delayed(Duration.zero); + expect(gateway.listCalls, 2); + gateway.listReply(0, [ + {'id': 1}, + ]); + await Future.delayed(Duration.zero); + expect(gateway.listCalls, 3); + gateway.listReply(2, [ + {'id': 1}, + {'id': 2}, + ]); + await Future.delayed(Duration.zero); + expect(controller.runs, hasLength(2)); + expect(controller.loading, isFalse); + }); + + test('unknown run events coalesce into one followup resync', () async { + controller.listen(gateway.frames); + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 9, + 'status': 'running', + }); + await Future.delayed(Duration.zero); + expect(gateway.listCalls, 1); + expect(controller.loading, isTrue); + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 10, + 'status': 'running', + }); + await Future.delayed(Duration.zero); + expect(gateway.listCalls, 1); + gateway.listReply(0, [ + {'id': 3}, + ]); + await Future.delayed(Duration.zero); + expect(gateway.listCalls, 2); + expect(controller.loading, isTrue); + gateway.listReply(1, [ + {'id': 3}, + {'id': 4}, + ]); + await Future.delayed(Duration.zero); + expect(gateway.listCalls, 2); + expect(controller.loading, isFalse); + expect(controller.runs, hasLength(2)); + }); + + test( + 'selected refresh coalesces and Back ignores the pending reply', + () async { + final select = controller.select(1); + gateway.detailReply(1, 0, {'id': 1, 'status': 'running'}); + await select; + controller.listen(gateway.frames); + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 1, + 'status': 'succeeded', + }); + await Future.delayed(const Duration(milliseconds: 180)); + expect(gateway.details[1], hasLength(2)); + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 1, + 'status': 'failed', + }); + await Future.delayed(Duration.zero); + expect(gateway.details[1], hasLength(2)); + gateway.detailReply(1, 1, {'id': 1, 'status': 'succeeded'}); + await Future.delayed(Duration.zero); + expect(gateway.details[1], hasLength(3)); + controller.back(); + gateway.detailReply(1, 2, {'id': 1, 'status': 'failed'}); + await Future.delayed(Duration.zero); + expect(controller.detail, isNull); + expect(controller.detailLoading, isFalse); + expect(controller.error, isNull); + }, + ); + + test('choosing another run does not display the previous detail', () async { + final first = controller.select(1); + gateway.detailReply(1, 0, {'id': 1}); + await first; + final second = controller.select(2); + expect(controller.detail, isNull); + expect(controller.selectedRunId, 2); + expect(controller.detailLoading, isTrue); + gateway.detailReply(2, 0, {'id': 2}); + await second; + expect(controller.detail?['id'], 2); + expect(controller.detailLoading, isFalse); + }); + + test('pending detail refresh is safe after dispose', () async { + final select = controller.select(1); + gateway.detailReply(1, 0, {'id': 1, 'status': 'running'}); + await select; + controller.listen(gateway.frames); + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 1, + 'status': 'succeeded', + }); + await Future.delayed(const Duration(milliseconds: 180)); + expect(gateway.details[1], hasLength(2)); + controller.dispose(); + disposed = true; + gateway.detailReply(1, 1, {'id': 1, 'status': 'succeeded'}); + await Future.delayed(Duration.zero); + expect(controller.detail?['id'], 1); + }); } From b2b2b56fd38db50c483495a6ea4d1a1a6aa43c86 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:56:09 +0100 Subject: [PATCH 24/84] wip(app): preserve partial runs navigation before native widget slices --- app/lib/features/runs/screen.dart | 42 +++++++++++++++++-- app/lib/features/runs/ui/run_detail_view.dart | 7 ++-- app/lib/features/runs/ui/runs_list.dart | 5 ++- 3 files changed, 46 insertions(+), 8 deletions(-) diff --git a/app/lib/features/runs/screen.dart b/app/lib/features/runs/screen.dart index 3edd5240..3e2630c8 100644 --- a/app/lib/features/runs/screen.dart +++ b/app/lib/features/runs/screen.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:flutter/cupertino.dart'; import '../../core/api_gateway.dart'; import 'data/runs_repository.dart'; @@ -17,6 +18,7 @@ class RunsScreen extends StatefulWidget { class _RunsScreenState extends State { late RunsController controller; + num? _selectedRunId; @override void initState() { super.initState(); @@ -38,7 +40,41 @@ class _RunsScreenState extends State { } @override - Widget build(BuildContext context) => controller.detail == null - ? RunsList(controller: controller) - : RunDetailView(controller: controller); + Widget build(BuildContext context) { + final isCupertino = Theme.of(context).platform == TargetPlatform.iOS; + final selected = _selectedRunId != null; + final content = Stack( + children: [ + Offstage( + offstage: selected, + child: RunsList(controller: controller, onSelected: (id) { + setState(() => _selectedRunId = id); + controller.select(id); + }), + ), + if (selected) + RunDetailView( + controller: controller, + onBack: () { + controller.back(); + setState(() => _selectedRunId = null); + }, + ), + ], + ); + if (isCupertino) { + return CupertinoPageScaffold( + navigationBar: CupertinoNavigationBar( + middle: Text(selected ? 'Run ${controller.detail?['id'] ?? _selectedRunId}' : 'Runs'), + leading: selected ? CupertinoButton( + padding: EdgeInsets.zero, + onPressed: () { controller.back(); setState(() => _selectedRunId = null); }, + child: const Text('Runs'), + ) : null, + ), + child: SafeArea(child: content), + ); + } + return content; + } } diff --git a/app/lib/features/runs/ui/run_detail_view.dart b/app/lib/features/runs/ui/run_detail_view.dart index a2814712..1b61edae 100644 --- a/app/lib/features/runs/ui/run_detail_view.dart +++ b/app/lib/features/runs/ui/run_detail_view.dart @@ -3,8 +3,9 @@ import 'package:flutter/services.dart'; import 'runs_controller.dart'; class RunDetailView extends StatelessWidget { - const RunDetailView({super.key, required this.controller}); + const RunDetailView({super.key, required this.controller, required this.onBack}); final RunsController controller; + final VoidCallback onBack; @override Widget build(BuildContext context) { final run = controller.detail; @@ -18,7 +19,7 @@ class RunDetailView extends StatelessWidget { children: [ Text(controller.error ?? 'Run details unavailable.'), FilledButton( - onPressed: controller.back, + onPressed: onBack, child: const Text('Back to runs'), ), ], @@ -33,7 +34,7 @@ class RunDetailView extends StatelessWidget { padding: const EdgeInsets.all(16), children: [ TextButton.icon( - onPressed: controller.back, + onPressed: onBack, icon: const Icon(Icons.arrow_back), label: const Text('Runs'), ), diff --git a/app/lib/features/runs/ui/runs_list.dart b/app/lib/features/runs/ui/runs_list.dart index f168ab89..63435f27 100644 --- a/app/lib/features/runs/ui/runs_list.dart +++ b/app/lib/features/runs/ui/runs_list.dart @@ -3,8 +3,9 @@ import 'runs_controller.dart'; import '../domain/run_models.dart'; class RunsList extends StatelessWidget { - const RunsList({super.key, required this.controller}); + const RunsList({super.key, required this.controller, required this.onSelected}); final RunsController controller; + final ValueChanged onSelected; @override Widget build(BuildContext context) { if (controller.loading && controller.runs.isEmpty) { @@ -72,7 +73,7 @@ class RunsList extends StatelessWidget { ), leading: Chip(label: Text(runStatusLabel(run))), trailing: const Icon(Icons.chevron_right), - onTap: id is num ? () => controller.select(id) : null, + onTap: id is num ? () => onSelected(id) : null, ); }, ), From a2e7c43edb694d92170ae1861c9523f43d858ff2 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:57:19 +0100 Subject: [PATCH 25/84] docs(app): preserve native run partial work and split widget acceptance --- app/WORK.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/WORK.md b/app/WORK.md index 22334a78..f422c4b5 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -15,7 +15,7 @@ All work under app/. Existing applications remain running and unchanged. | P1 | Pipeline list/detail/source/version browser | run 34 / flutter/p1-pipelines | running (DeepSeek V4.1 Flash) | pending | pending | | C1 | Chat session browser and management | 35 → resume 36 → focused C1b run 42 / flutter/f4-chat | catalog/grouping fixes + inspected browser captures retained; pipeline splitting 406-line screen and adding Cupertino/tests (Flash) | held; not parity-complete | pending | | N1 | Connection settings/preferences | run 37 / flutter/n1-settings | running (Flash) | pending | pending | -| R1 | Run list/detail/live timeline | 38 → 40 → resume 41; now R1b run 43 + R1c run 44 | 6 new controller tests passed; remaining independent-list-generation race sent to Flash, native UI/browser lane runs concurrently on Luna | held | pending | +| R1 | Run list/detail/live timeline | controller 43; native list resume 45; native detail 46 | 44 stopped incomplete; checkpoint b2b2b56 preserves partial navigation; smaller independent widget/test slices now running | held | browser integration pending | | D1 | Recorded changes/diff viewer | run 39 / flutter/d1-diff-viewer | running (Flash) | pending | pending | ## Next ready work From 7ecd3903c001810fe9852a616020f20221cddedc Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 14:01:29 +0100 Subject: [PATCH 26/84] docs(app): accept controller checks and track native-list test recovery --- app/WORK.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/WORK.md b/app/WORK.md index f422c4b5..6074319d 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -15,8 +15,9 @@ All work under app/. Existing applications remain running and unchanged. | P1 | Pipeline list/detail/source/version browser | run 34 / flutter/p1-pipelines | running (DeepSeek V4.1 Flash) | pending | pending | | C1 | Chat session browser and management | 35 → resume 36 → focused C1b run 42 / flutter/f4-chat | catalog/grouping fixes + inspected browser captures retained; pipeline splitting 406-line screen and adding Cupertino/tests (Flash) | held; not parity-complete | pending | | N1 | Connection settings/preferences | run 37 / flutter/n1-settings | running (Flash) | pending | pending | -| R1 | Run list/detail/live timeline | controller 43; native list resume 45; native detail 46 | 44 stopped incomplete; checkpoint b2b2b56 preserves partial navigation; smaller independent widget/test slices now running | held | browser integration pending | +| R1 | Run list/detail/live timeline | controller 43 accepted; list 45 → resume 48; detail 46 | manager reran 15 controller tests, all pass; reproduced 3 list-test invariant failures and sent focused fix to resume48; detail lane independent | controller accepted, whole UI held | browser integration pending | | D1 | Recorded changes/diff viewer | run 39 / flutter/d1-diff-viewer | running (Flash) | pending | pending | +| R2a | Human-decision native confirm | run 47 / flutter/r2-decision | running (Flash), exact confirmation/refusal tests | pending | pending | ## Next ready work - P1 pipelines list/detail/source/version; P2 graph and stage/visit selection. From 40aa98e20b9346d3f3a1b1bd97b7279b97cf05c3 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 14:07:02 +0100 Subject: [PATCH 27/84] feat(app): add native runs list interactions --- app/lib/features/runs/ui/runs_list.dart | 271 ++++++++++++++---- .../runs/ui/runs_list_widget_test.dart | 180 ++++++++++++ 2 files changed, 397 insertions(+), 54 deletions(-) create mode 100644 app/test/features/runs/ui/runs_list_widget_test.dart diff --git a/app/lib/features/runs/ui/runs_list.dart b/app/lib/features/runs/ui/runs_list.dart index 63435f27..714d2d54 100644 --- a/app/lib/features/runs/ui/runs_list.dart +++ b/app/lib/features/runs/ui/runs_list.dart @@ -1,84 +1,247 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; -import 'runs_controller.dart'; + +import '../../../core/api_gateway.dart'; import '../domain/run_models.dart'; +import 'runs_controller.dart'; class RunsList extends StatelessWidget { - const RunsList({super.key, required this.controller, required this.onSelected}); + const RunsList({ + super.key, + required this.controller, + required this.onSelected, + }); + final RunsController controller; final ValueChanged onSelected; + + bool get _isCupertino => + defaultTargetPlatform == TargetPlatform.iOS || + defaultTargetPlatform == TargetPlatform.macOS; + @override Widget build(BuildContext context) { if (controller.loading && controller.runs.isEmpty) { - return const Center(child: CircularProgressIndicator()); - } - if (controller.error != null && controller.runs.isEmpty) { return Center( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Text(controller.error!), - const SizedBox(height: 8), - FilledButton( - onPressed: controller.load, - child: const Text('Retry'), - ), - ], - ), + child: _isCupertino + ? const CupertinoActivityIndicator() + : const CircularProgressIndicator(), ); } + if (controller.error != null && controller.runs.isEmpty) { + return _emptyError(context); + } return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, children: [ if (controller.usage != null) - Padding(padding: const EdgeInsets.symmetric(horizontal: 16), child: Text('Usage: ${controller.usage}')), - if (controller.error != null) - MaterialBanner( - content: Text(controller.error!), - actions: [ - TextButton(onPressed: controller.load, child: const Text('Retry')), - ], + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Text('Usage: ${controller.usage}'), ), + if (controller.error != null) _inlineError(context), Padding( padding: const EdgeInsets.all(16), - child: TextField( - decoration: const InputDecoration( - labelText: 'Filter runs', - prefixIcon: Icon(Icons.search), - ), - onChanged: controller.setQuery, - ), + child: _isCupertino + ? CupertinoSearchTextField( + placeholder: 'Filter runs', + onChanged: controller.setQuery, + ) + : TextField( + decoration: const InputDecoration( + labelText: 'Filter runs', + prefixIcon: Icon(Icons.search), + ), + onChanged: controller.setQuery, + ), ), - Wrap(spacing: 8, children: [ - DropdownButton(value: controller.sort, onChanged: (v) { if (v != null) controller.setSort(v); }, items: const [DropdownMenuItem(value: 'newest_first', child: Text('Newest')), DropdownMenuItem(value: 'oldest_first', child: Text('Oldest')), DropdownMenuItem(value: 'pipeline_name', child: Text('Pipeline')), DropdownMenuItem(value: 'status', child: Text('Status'))]), - DropdownButton(value: controller.scheduled, onChanged: (v) { if (v != null) controller.setScheduled(v); }, items: const [DropdownMenuItem(value: 'any', child: Text('Any schedule')), DropdownMenuItem(value: 'scheduled', child: Text('Scheduled')), DropdownMenuItem(value: 'unscheduled', child: Text('Unscheduled'))]), - for (final status in ['queued', 'running', 'waiting', 'succeeded', 'failed']) - FilterChip(label: Text(status), selected: controller.statuses.contains(status), onSelected: (_) => controller.setStatus(status)), - ]), + _selectors(context), Expanded( child: controller.visibleRuns.isEmpty ? const Center(child: Text('No runs found.')) : ListView.builder( itemCount: controller.visibleRuns.length, - itemBuilder: (context, index) { - final run = controller.visibleRuns[index]; - final identity = runIdentity(run['title'], run['name']); - final created = - run['created_at']?.toString() ?? 'Time unavailable'; - final id = run['id']; - return ListTile( - title: Text( - identity.label.isEmpty ? 'Run $id' : identity.label, - ), - subtitle: Text( - '${run['name'] ?? 'Pipeline unavailable'} · $created${run['scheduled'] == true ? ' · Scheduled' : ''}', - ), - leading: Chip(label: Text(runStatusLabel(run))), - trailing: const Icon(Icons.chevron_right), - onTap: id is num ? () => onSelected(id) : null, - ); - }, + itemBuilder: (context, index) => + _runTile(context, controller.visibleRuns[index]), ), ), ], ); } + + Widget _emptyError(BuildContext context) => Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text(controller.error!), + const SizedBox(height: 8), + _isCupertino + ? CupertinoButton( + onPressed: controller.load, + child: const Text('Retry'), + ) + : FilledButton( + onPressed: controller.load, + child: const Text('Retry'), + ), + ], + ), + ); + + Widget _inlineError(BuildContext context) => Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Row( + children: [ + Expanded(child: Text(controller.error!)), + if (_isCupertino) + CupertinoButton( + onPressed: controller.load, + child: const Text('Retry'), + ) + else + TextButton(onPressed: controller.load, child: const Text('Retry')), + ], + ), + ); + + Widget _selectors(BuildContext context) { + if (_isCupertino) { + return Wrap( + spacing: 8, + children: [ + CupertinoButton( + onPressed: () => _choose( + context, + 'Sort runs', + _sorts, + controller.sort, + controller.setSort, + ), + child: Text('Sort: ${_sortLabel(controller.sort)}'), + ), + CupertinoButton( + onPressed: () => _choose( + context, + 'Schedule', + _schedules, + controller.scheduled, + controller.setScheduled, + ), + child: Text('Schedule: ${_scheduleLabel(controller.scheduled)}'), + ), + for (final status in _statuses) + CupertinoButton( + onPressed: () => controller.setStatus(status), + child: Text( + '${controller.statuses.contains(status) ? '✓ ' : ''}${_title(status)}', + ), + ), + ], + ); + } + return Wrap( + spacing: 8, + children: [ + DropdownButton( + value: controller.sort, + isExpanded: true, + onChanged: (v) { + if (v != null) controller.setSort(v); + }, + items: _sorts + .map((e) => DropdownMenuItem(value: e.$1, child: Text(e.$2))) + .toList(), + ), + DropdownButton( + value: controller.scheduled, + isExpanded: true, + onChanged: (v) { + if (v != null) controller.setScheduled(v); + }, + items: _schedules + .map((e) => DropdownMenuItem(value: e.$1, child: Text(e.$2))) + .toList(), + ), + for (final status in _statuses) + FilterChip( + label: Text(_title(status)), + selected: controller.statuses.contains(status), + onSelected: (_) => controller.setStatus(status), + ), + ], + ); + } + + Future _choose( + BuildContext context, + String title, + List<(String, String)> values, + String selected, + ValueChanged onSelected, + ) async { + final value = await showCupertinoModalPopup( + context: context, + builder: (context) => CupertinoActionSheet( + title: Text(title), + actions: [ + for (final option in values) + CupertinoActionSheetAction( + onPressed: () => Navigator.pop(context, option.$1), + child: Text(option.$2), + ), + ], + cancelButton: CupertinoActionSheetAction( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + ), + ); + if (value != null && value != selected) onSelected(value); + } + + Widget _runTile(BuildContext context, JsonMap run) { + final identity = runIdentity(run['title'], run['name']); + final id = run['id']; + final title = identity.label.isEmpty ? 'Run $id' : identity.label; + final subtitle = + '${run['name'] ?? 'Pipeline unavailable'} · ${run['created_at'] ?? 'Time unavailable'}${run['scheduled'] == true ? ' · Scheduled' : ''}'; + if (_isCupertino) { + return CupertinoListTile( + title: Text(title), + subtitle: Text(subtitle), + additionalInfo: Text(runStatusLabel(run)), + trailing: const CupertinoListTileChevron(), + onTap: id is num ? () => onSelected(id) : null, + ); + } + return ListTile( + title: Text(title), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [Text(subtitle), Text(runStatusLabel(run))], + ), + trailing: const Icon(Icons.chevron_right), + onTap: id is num ? () => onSelected(id) : null, + ); + } } + +const _sorts = [ + ('newest_first', 'Newest'), + ('oldest_first', 'Oldest'), + ('pipeline_name', 'Pipeline'), + ('status', 'Status'), +]; +const _schedules = [ + ('any', 'Any schedule'), + ('scheduled', 'Scheduled'), + ('unscheduled', 'Unscheduled'), +]; +const _statuses = ['queued', 'running', 'waiting', 'succeeded', 'failed']; +String _sortLabel(String value) => + _sorts.firstWhere((e) => e.$1 == value, orElse: () => _sorts.first).$2; +String _scheduleLabel(String value) => _schedules + .firstWhere((e) => e.$1 == value, orElse: () => _schedules.first) + .$2; +String _title(String value) => '${value[0].toUpperCase()}${value.substring(1)}'; diff --git a/app/test/features/runs/ui/runs_list_widget_test.dart b/app/test/features/runs/ui/runs_list_widget_test.dart new file mode 100644 index 00000000..2414cf78 --- /dev/null +++ b/app/test/features/runs/ui/runs_list_widget_test.dart @@ -0,0 +1,180 @@ +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/features/runs/data/runs_repository.dart'; +import 'package:pipelines_app/features/runs/ui/runs_controller.dart'; +import 'package:pipelines_app/features/runs/ui/runs_list.dart'; + +class _Gateway implements ApiGateway { + final framesController = StreamController.broadcast(); + JsonMap? reply; + Object? failure; + Completer? gate; + + @override + Stream get frames => framesController.stream; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + await gate?.future; + if (failure != null) throw failure!; + return reply ?? {'runs': []}; + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late _Gateway gateway; + late RunsController controller; + + setUp(() { + gateway = _Gateway(); + controller = RunsController(RunsRepository(gateway)); + }); + + tearDown(() async { + controller.dispose(); + await gateway.framesController.close(); + }); + + Future mount( + WidgetTester tester, { + required bool cupertino, + ValueChanged? onSelected, + }) async { + gateway.reply = { + 'runs': [ + {'id': 1, 'name': 'Alpha', 'status': 'running', 'scheduled': true}, + {'id': 2, 'name': 'Beta', 'status': 'failed', 'scheduled': false}, + ], + }; + await controller.load(); + final list = AnimatedBuilder( + animation: controller, + builder: (context, _) => + RunsList(controller: controller, onSelected: onSelected ?? (_) {}), + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp(home: CupertinoPageScaffold(child: list)) + : MaterialApp(home: Scaffold(body: list)), + ); + } + + testWidgets( + 'uses native search and filters runs in CupertinoApp', + (tester) async { + num? selectedRun; + await mount( + tester, + cupertino: true, + onSelected: (id) => selectedRun = id, + ); + + expect(find.byType(CupertinoSearchTextField), findsOneWidget); + expect(find.text('Alpha'), findsOneWidget); + await tester.enterText(find.byType(CupertinoSearchTextField), 'Beta'); + await tester.pumpAndSettle(); + expect(find.text('Beta'), findsNWidgets(2)); + expect(find.text('Alpha'), findsNothing); + await tester.tap(find.byType(CupertinoListTile)); + expect(selectedRun, 2); + await tester.enterText(find.byType(CupertinoSearchTextField), 'missing'); + await tester.pumpAndSettle(); + expect(find.text('No runs found.'), findsOneWidget); + await tester.enterText(find.byType(CupertinoSearchTextField), ''); + await tester.pumpAndSettle(); + await tester.tap(find.textContaining('Schedule:')); + await tester.pumpAndSettle(); + expect(find.text('Scheduled'), findsWidgets); + await tester.tap(find.text('Scheduled').last); + await tester.pumpAndSettle(); + expect(controller.scheduled, 'scheduled'); + }, + variant: TargetPlatformVariant.only(TargetPlatform.iOS), + ); + + testWidgets( + 'retains Material controls and handles large text on narrow layout', + (tester) async { + tester.view.devicePixelRatio = 2; + tester.view.physicalSize = const Size(780, 1560); + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + MaterialApp( + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: const TextScaler.linear(2)), + child: child!, + ), + home: Scaffold( + body: AnimatedBuilder( + animation: controller, + builder: (_, _) => + RunsList(controller: controller, onSelected: (_) {}), + ), + ), + ), + ); + gateway.reply = { + 'runs': [ + {'id': 1, 'name': 'Alpha', 'status': 'running', 'scheduled': true}, + {'id': 2, 'name': 'Beta', 'status': 'failed', 'scheduled': false}, + ], + }; + await controller.load(); + await tester.pumpAndSettle(); + expect(find.byType(TextField), findsOneWidget); + final layoutError = tester.takeException(); + expect( + layoutError, + isNull, + reason: layoutError is FlutterError + ? layoutError.toStringDeep() + : '$layoutError', + ); + }, + variant: TargetPlatformVariant.only(TargetPlatform.android), + ); + + testWidgets( + 'shows loading, error and server-empty states distinctly', + (tester) async { + gateway.failure = StateError('offline'); + gateway.gate = Completer(); + final loading = controller.load(); + await tester.pumpWidget( + CupertinoApp( + home: CupertinoPageScaffold( + child: AnimatedBuilder( + animation: controller, + builder: (_, child) => + RunsList(controller: controller, onSelected: (_) {}), + ), + ), + ), + ); + await tester.pump(); + expect(find.byType(CupertinoActivityIndicator), findsOneWidget); + gateway.gate!.complete(); + await loading; + await tester.pumpAndSettle(); + expect(find.textContaining('offline'), findsOneWidget); + expect(tester.takeException(), isNull); + gateway.failure = null; + gateway.gate = null; + gateway.reply = {'runs': []}; + await controller.load(); + await tester.pumpAndSettle(); + expect(find.text('No runs found.'), findsOneWidget); + expect(find.textContaining('offline'), findsNothing); + expect(tester.takeException(), isNull); + }, + variant: TargetPlatformVariant.only(TargetPlatform.iOS), + ); +} From 9cc61bc378e840b2f659ab13166cc558c6c02b10 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 14:08:52 +0100 Subject: [PATCH 28/84] docs(app): verify native list integration and start search lane --- app/WORK.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/WORK.md b/app/WORK.md index 6074319d..743ea2a9 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -15,9 +15,10 @@ All work under app/. Existing applications remain running and unchanged. | P1 | Pipeline list/detail/source/version browser | run 34 / flutter/p1-pipelines | running (DeepSeek V4.1 Flash) | pending | pending | | C1 | Chat session browser and management | 35 → resume 36 → focused C1b run 42 / flutter/f4-chat | catalog/grouping fixes + inspected browser captures retained; pipeline splitting 406-line screen and adding Cupertino/tests (Flash) | held; not parity-complete | pending | | N1 | Connection settings/preferences | run 37 / flutter/n1-settings | running (Flash) | pending | pending | -| R1 | Run list/detail/live timeline | controller 43 accepted; list 45 → resume 48; detail 46 | manager reran 15 controller tests, all pass; reproduced 3 list-test invariant failures and sent focused fix to resume48; detail lane independent | controller accepted, whole UI held | browser integration pending | +| R1 | Run list/detail/live timeline | controller43 + list48 accepted; detail46 active | merged controller into native-list branch; manager reran 18 combined tests + analyze, pass; source list247/controller260 cohesive lines | candidate integrated, whole UI held | browser integration pending | | D1 | Recorded changes/diff viewer | run 39 / flutter/d1-diff-viewer | running (Flash) | pending | pending | | R2a | Human-decision native confirm | run 47 / flutter/r2-decision | running (Flash), exact confirmation/refusal tests | pending | pending | +| X1 | Native search and result targets | run 49 / flutter/x1-search | running (Flash) | pending | pending | ## Next ready work - P1 pipelines list/detail/source/version; P2 graph and stage/visit selection. From e14bb67825a4348b5f5faa3faa33fe1b1c1ec13e Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 14:20:43 +0100 Subject: [PATCH 29/84] feat(app): render run detail with native Material and Cupertino controls --- .../features/runs/ui/run_detail_content.dart | 116 ++++++++ .../runs/ui/run_detail_cupertino.dart | 203 ++++++++++++++ .../features/runs/ui/run_detail_material.dart | 126 +++++++++ app/lib/features/runs/ui/run_detail_view.dart | 207 +++++++------- app/notes/R1c2.md | 50 ++++ .../runs/ui/run_detail_widget_test.dart | 264 ++++++++++++++++++ 6 files changed, 867 insertions(+), 99 deletions(-) create mode 100644 app/lib/features/runs/ui/run_detail_content.dart create mode 100644 app/lib/features/runs/ui/run_detail_cupertino.dart create mode 100644 app/lib/features/runs/ui/run_detail_material.dart create mode 100644 app/notes/R1c2.md create mode 100644 app/test/features/runs/ui/run_detail_widget_test.dart diff --git a/app/lib/features/runs/ui/run_detail_content.dart b/app/lib/features/runs/ui/run_detail_content.dart new file mode 100644 index 00000000..5c48756f --- /dev/null +++ b/app/lib/features/runs/ui/run_detail_content.dart @@ -0,0 +1,116 @@ +import 'dart:convert'; + +import '../../../core/api_gateway.dart'; +import '../domain/run_models.dart'; + +/// One labelled value in the run detail's metrics block. +typedef DetailMetric = ({String label, String value}); + +/// One recorded visit in the run detail's timeline. +typedef DetailVisit = ({String title, String subtitle}); + +/// The run's primary label: the stored title, else the pipeline name, and only +/// then the numeric identity. +String detailTitle(JsonMap run) { + final identity = runIdentity(run['title'], run['name']); + return identity.label.trim().isEmpty ? 'Run ${run['id']}' : identity.label; +} + +String detailPipeline(JsonMap run) { + final name = '${run['name'] ?? ''}'.trim(); + return name.isEmpty ? 'unavailable' : name; +} + +/// The original prompt exactly as the server stored it; never trimmed or +/// replaced by another field. +String? detailPrompt(JsonMap run) { + final input = run['input']; + return input is Map && input['prompt'] is String + ? input['prompt'] as String + : null; +} + +/// Nested input/output shown as formatted, selectable JSON. +String detailJson(dynamic value) => + const JsonEncoder.withIndent(' ').convert(value); + +bool detailEmpty(dynamic value) => value is! Map || value.isEmpty; + +/// Reported run metrics. A present zero with a reporting stage count is a real +/// zero; a zero without that evidence is unavailable, never a measured zero. +List detailUsageMetrics(dynamic raw) { + if (raw is! Map || raw.isEmpty) return const []; + final usage = Map.from(raw); + final stages = _int(usage['stages']); + final tokenStages = _int(usage['tokens_known_stages']) ?? 0; + final costStages = _int(usage['cost_known_stages']) ?? 0; + final totalTokens = _int(usage['tokens_total']); + final splitKnown = usage['split_known'] == true && tokenStages > 0; + final rows = [ + if (stages != null) (label: 'Stages', value: '$stages'), + ( + label: 'Total tokens', + value: tokenStages == 0 || totalTokens == null + ? 'Unavailable' + : '$totalTokens', + ), + ( + label: 'Input tokens', + value: splitKnown ? '${_int(usage['tokens_in']) ?? 0}' : 'Unavailable', + ), + ( + label: 'Output tokens', + value: splitKnown ? '${_int(usage['tokens_out']) ?? 0}' : 'Unavailable', + ), + ( + label: 'Reported cost', + // cost_usd is omitted by the server when zero, so a known stage count + // makes an absent value a real $0.000000 rather than an unknown cost. + value: costStages == 0 + ? 'Unavailable' + : '\$${((usage['cost_usd'] as num?) ?? 0).toStringAsFixed(6)}', + ), + ]; + if (stages != null && tokenStages < stages) { + rows.add(( + label: 'Token reporting', + value: '$tokenStages of $stages stages', + )); + } + if (stages != null && costStages < stages) { + rows.add((label: 'Cost reporting', value: '$costStages of $stages stages')); + } + return rows; +} + +/// Every recorded visit with its server sequence, in recorded order. +List detailTimeline(dynamic steps) { + if (steps is! List) return const []; + return [ + for (final step in steps.whereType()) + ( + title: + '${_text(step['stage'], 'Stage unavailable')} · visit ' + '${step['sequence'] is num ? (step['sequence'] as num).toInt() : 'unavailable'}', + subtitle: _visitSubtitle(step), + ), + ]; +} + +String _visitSubtitle(Map step) { + final status = _text(step['status'], 'Status unavailable'); + final outcome = '${step['outcome'] ?? ''}'.trim(); + final target = '${step['target'] ?? ''}'.trim(); + return [ + status, + if (outcome.isNotEmpty) outcome, + if (target.isNotEmpty) '→ $target', + ].join(' · '); +} + +String _text(dynamic value, String fallback) { + final text = '${value ?? ''}'.trim(); + return text.isEmpty ? fallback : text; +} + +int? _int(dynamic value) => value is num ? value.toInt() : null; diff --git a/app/lib/features/runs/ui/run_detail_cupertino.dart b/app/lib/features/runs/ui/run_detail_cupertino.dart new file mode 100644 index 00000000..7c342a44 --- /dev/null +++ b/app/lib/features/runs/ui/run_detail_cupertino.dart @@ -0,0 +1,203 @@ +import 'package:flutter/cupertino.dart'; + +import '../../../core/api_gateway.dart'; +import '../domain/run_models.dart'; +import 'run_detail_content.dart'; + +/// The runs detail with standard Cupertino controls. It has no Material +/// ancestor: sections use native Cupertino expansion tiles and grouped list +/// sections, and copy feedback is an inline live-region status. +Widget buildCupertinoRunDetail({ + required BuildContext context, + required JsonMap run, + required bool detailLoading, + required String? error, + required bool copying, + required String? copyStatus, + required VoidCallback onBack, + required VoidCallback onCopy, +}) { + final theme = CupertinoTheme.of(context); + final prompt = detailPrompt(run); + final visits = detailTimeline(run['steps']); + final metrics = detailUsageMetrics(run['usage']); + return ListView( + key: ValueKey('run-detail-${run['id']}'), + children: [ + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0), + child: Row( + children: [ + CupertinoButton( + padding: EdgeInsets.zero, + onPressed: onBack, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(CupertinoIcons.back), + const SizedBox(width: 4), + const Text('Runs'), + ], + ), + ), + const Spacer(), + if (copying) const CupertinoActivityIndicator(), + ], + ), + ), + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + detailTitle(run), + style: theme.textTheme.navLargeTitleTextStyle, + ), + const SizedBox(height: 4), + Text(runStatusLabel(run)), + Text('Run ${run['id']} · Pipeline ${detailPipeline(run)}'), + ], + ), + ), + if (detailLoading) const _CupertinoNotice('Refreshing run details…'), + if (error != null) _CupertinoNotice(error), + if (prompt != null) + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 16, 16, 0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Wrap( + alignment: WrapAlignment.spaceBetween, + crossAxisAlignment: WrapCrossAlignment.center, + spacing: 8, + runSpacing: 4, + children: [ + Text( + 'Original prompt', + style: theme.textTheme.navTitleTextStyle, + ), + CupertinoButton( + padding: EdgeInsets.zero, + onPressed: copying ? null : onCopy, + child: const Text('Copy prompt'), + ), + ], + ), + _CupertinoSelectableText(prompt), + if (copyStatus != null) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Semantics(liveRegion: true, child: Text(copyStatus)), + ), + ], + ), + ), + _fieldSection('Input', run['input'], 'No input recorded.'), + _fieldSection('Output', run['output'], 'No output recorded.'), + CupertinoListSection.insetGrouped( + header: const Text('Timeline'), + children: [ + if (visits.isEmpty) + const CupertinoListTile(title: Text('No visits recorded.')) + else + for (final visit in visits) + CupertinoListTile( + leading: const Icon(CupertinoIcons.circle), + title: Text(visit.title), + subtitle: Text(visit.subtitle), + ), + ], + ), + CupertinoListSection.insetGrouped( + children: [ + CupertinoExpansionTile( + title: const Text('Metrics'), + child: Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (metrics.isEmpty) + const Text('No reported usage.') + else + for (final metric in metrics) + CupertinoListTile( + title: Text(metric.label), + subtitle: Text(metric.value), + ), + ], + ), + ), + ), + ], + ), + ], + ); +} + +Widget _fieldSection(String title, dynamic value, String empty) { + final text = detailEmpty(value) ? empty : detailJson(value); + return CupertinoListSection.insetGrouped( + children: [ + CupertinoExpansionTile( + title: Text(title), + child: Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 16), + child: _CupertinoSelectableText(text), + ), + ), + ], + ); +} + +class _CupertinoNotice extends StatelessWidget { + const _CupertinoNotice(this.text); + final String text; + + @override + Widget build(BuildContext context) => Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0), + child: Semantics(liveRegion: true, child: Text(text)), + ); +} + +/// A read-only Cupertino text control: plain, selectable text without a +/// Material dependency, while keeping native selection and copy affordances. +class _CupertinoSelectableText extends StatefulWidget { + const _CupertinoSelectableText(this.text); + final String text; + + @override + State<_CupertinoSelectableText> createState() => + _CupertinoSelectableTextState(); +} + +class _CupertinoSelectableTextState extends State<_CupertinoSelectableText> { + late final TextEditingController _controller = TextEditingController( + text: widget.text, + ); + + @override + void didUpdateWidget(_CupertinoSelectableText oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.text != oldWidget.text) _controller.text = widget.text; + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => CupertinoTextField( + controller: _controller, + readOnly: true, + maxLines: null, + padding: EdgeInsets.zero, + decoration: const BoxDecoration(), + style: CupertinoTheme.of(context).textTheme.textStyle, + ); +} diff --git a/app/lib/features/runs/ui/run_detail_material.dart b/app/lib/features/runs/ui/run_detail_material.dart new file mode 100644 index 00000000..84be2c77 --- /dev/null +++ b/app/lib/features/runs/ui/run_detail_material.dart @@ -0,0 +1,126 @@ +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../domain/run_models.dart'; +import 'run_detail_content.dart'; + +/// The runs detail with standard Material controls. +Widget buildMaterialRunDetail({ + required BuildContext context, + required JsonMap run, + required bool detailLoading, + required String? error, + required bool copying, + required String? copyStatus, + required VoidCallback onBack, + required VoidCallback onCopy, +}) { + final theme = Theme.of(context); + final prompt = detailPrompt(run); + final visits = detailTimeline(run['steps']); + final metrics = detailUsageMetrics(run['usage']); + return ListView( + key: ValueKey('run-detail-${run['id']}'), + padding: const EdgeInsets.all(16), + children: [ + Align( + alignment: AlignmentDirectional.centerStart, + child: TextButton.icon( + onPressed: onBack, + icon: const Icon(Icons.arrow_back), + label: const Text('Runs'), + ), + ), + Text(detailTitle(run), style: theme.textTheme.headlineSmall), + const SizedBox(height: 8), + Wrap( + spacing: 8, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + Chip(label: Text(runStatusLabel(run))), + Text('Run ${run['id']}'), + Text('Pipeline ${detailPipeline(run)}'), + ], + ), + if (detailLoading) const _Notice('Refreshing run details…'), + if (error != null) _Notice(error), + if (prompt != null) ...[ + const SizedBox(height: 12), + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Text( + 'Original prompt', + style: theme.textTheme.titleMedium, + ), + ), + IconButton( + tooltip: 'Copy prompt', + onPressed: copying ? null : onCopy, + icon: const Icon(Icons.copy), + ), + ], + ), + SelectableText(prompt), + if (copyStatus != null) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Semantics(liveRegion: true, child: Text(copyStatus)), + ), + ], + _fieldSection('Input', run['input'], 'No input recorded.'), + _fieldSection('Output', run['output'], 'No output recorded.'), + Text('Timeline', style: theme.textTheme.titleLarge), + if (visits.isEmpty) + const Text('No visits recorded.') + else + ...visits.map( + (visit) => ListTile( + leading: const Icon(Icons.circle_outlined), + title: Text(visit.title), + subtitle: Text(visit.subtitle), + ), + ), + ExpansionTile( + title: const Text('Metrics'), + children: [ + if (metrics.isEmpty) + const Padding( + padding: EdgeInsets.all(16), + child: Text('No reported usage.'), + ) + else + ...metrics.map( + (metric) => ListTile( + title: Text(metric.label), + subtitle: Text(metric.value), + ), + ), + ], + ), + ], + ); +} + +Widget _fieldSection(String title, dynamic value, String empty) { + final text = detailEmpty(value) ? empty : detailJson(value); + return ExpansionTile( + title: Text(title), + children: [ + Padding(padding: const EdgeInsets.all(16), child: SelectableText(text)), + ], + ); +} + +class _Notice extends StatelessWidget { + const _Notice(this.text); + final String text; + + @override + Widget build(BuildContext context) => Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: Semantics(liveRegion: true, child: Text(text)), + ); +} diff --git a/app/lib/features/runs/ui/run_detail_view.dart b/app/lib/features/runs/ui/run_detail_view.dart index 1b61edae..b95962c3 100644 --- a/app/lib/features/runs/ui/run_detail_view.dart +++ b/app/lib/features/runs/ui/run_detail_view.dart @@ -1,124 +1,133 @@ +import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; + +import 'run_detail_content.dart'; +import 'run_detail_cupertino.dart'; +import 'run_detail_material.dart'; import 'runs_controller.dart'; -class RunDetailView extends StatelessWidget { - const RunDetailView({super.key, required this.controller, required this.onBack}); +class RunDetailView extends StatefulWidget { + const RunDetailView({ + super.key, + required this.controller, + required this.onBack, + }); + final RunsController controller; final VoidCallback onBack; + @override - Widget build(BuildContext context) { - final run = controller.detail; - if (controller.detailLoading && run == null) { - return const Center(child: CircularProgressIndicator()); - } - if (run == null) { + State createState() => _RunDetailViewState(); +} + +class _RunDetailViewState extends State { + bool _copying = false; + String? _copyStatus; + + @override + Widget build(BuildContext context) => AnimatedBuilder( + animation: widget.controller, + builder: (context, _) { + final cupertino = _usesCupertino(context); + final run = widget.controller.detail; + if (run == null) return _placeholder(context, cupertino: cupertino); + final prompt = detailPrompt(run); + return cupertino + ? buildCupertinoRunDetail( + context: context, + run: run, + detailLoading: widget.controller.detailLoading, + error: widget.controller.error, + copying: _copying, + copyStatus: _copyStatus, + onBack: widget.onBack, + onCopy: () => _copyPrompt(prompt ?? '', cupertino: true), + ) + : buildMaterialRunDetail( + context: context, + run: run, + detailLoading: widget.controller.detailLoading, + error: widget.controller.error, + copying: _copying, + copyStatus: _copyStatus, + onBack: widget.onBack, + onCopy: () => _copyPrompt(prompt ?? '', cupertino: false), + ); + }, + ); + + /// CupertinoApp supplies CupertinoLocalizations only, while MaterialApp + /// supplies MaterialLocalizations. This distinguishes the two hosts without + /// assuming a desktop browser's target platform. + bool _usesCupertino(BuildContext context) => + Localizations.of(context, MaterialLocalizations) == + null; + + Widget _placeholder(BuildContext context, {required bool cupertino}) { + if (widget.controller.detailLoading) { return Center( child: Column( mainAxisSize: MainAxisSize.min, children: [ - Text(controller.error ?? 'Run details unavailable.'), - FilledButton( - onPressed: onBack, - child: const Text('Back to runs'), - ), + if (cupertino) + const CupertinoActivityIndicator() + else + const CircularProgressIndicator(), + const SizedBox(height: 12), + const Text('Loading run details…'), ], ), ); } - final input = run['input'] is Map ? run['input'] as Map : const {}; - final output = run['output'] is Map ? run['output'] as Map : const {}; - final steps = run['steps'] is List ? run['steps'] as List : const []; - final prompt = input['prompt']; - return ListView( - padding: const EdgeInsets.all(16), - children: [ - TextButton.icon( - onPressed: onBack, - icon: const Icon(Icons.arrow_back), - label: const Text('Runs'), - ), - Text( - '${run['title'] ?? run['name'] ?? 'Run ${run['id']}'}', - style: Theme.of(context).textTheme.headlineSmall, - ), - Wrap( - spacing: 8, - children: [ - Chip(label: Text('${run['status'] ?? 'unknown'}')), - Text('Run ${run['id']}'), - Text('Pipeline ${run['name'] ?? 'unavailable'}'), - ], - ), - if (prompt is String) ...[ + final message = widget.controller.error ?? 'Run details unavailable.'; + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 24), + child: Text(message, textAlign: TextAlign.center), + ), const SizedBox(height: 12), - Row( - children: [ - Text( - 'Original prompt', - style: Theme.of(context).textTheme.titleMedium, - ), - const Spacer(), - IconButton( - tooltip: 'Copy prompt', - onPressed: () => _copy(context, prompt), - icon: const Icon(Icons.copy), - ), - ], - ), - SelectableText(prompt), - ], - _section(context, 'Input', input), - _section(context, 'Output', output), - Text('Timeline', style: Theme.of(context).textTheme.titleLarge), - if (steps.isEmpty) - const Text('No visits recorded.') - else - ...steps.whereType().map( - (step) => ListTile( - leading: const Icon(Icons.circle_outlined), - title: Text( - '${step['stage'] ?? 'Stage unavailable'} · visit ${step['sequence'] ?? '?'}', - ), - subtitle: Text( - '${step['status'] ?? 'Status unavailable'}${step['outcome'] == null ? '' : ' · ${step['outcome']}'}', - ), + if (cupertino) + CupertinoButton( + onPressed: widget.onBack, + child: const Text('Back to runs'), + ) + else + FilledButton( + onPressed: widget.onBack, + child: const Text('Back to runs'), ), - ), - _section(context, 'Metrics', run['usage'] is Map ? run['usage'] as Map : const {}), - ], + ], + ), ); } - Widget _section(BuildContext context, String title, Map value) => - ExpansionTile( - title: Text(title), - children: [ - Padding( - padding: const EdgeInsets.all(16), - child: SelectableText( - value.isEmpty - ? 'No ${title.toLowerCase()} recorded.' - : value.entries.map((e) => '${e.key}: ${e.value}').join('\n'), - ), - ), - ], - ); - Future _copy(BuildContext context, String text) async { - // Clipboard failure is reported rather than silently substituting title/output. + /// Copies the stored prompt byte-for-byte. A refusal is surfaced, never + /// replaced by copying a title or the formatted detail. + Future _copyPrompt(String prompt, {required bool cupertino}) async { + if (_copying) return; + setState(() => _copying = true); + String message; try { - await Clipboard.setData(ClipboardData(text: text)); - if (context.mounted) { - ScaffoldMessenger.of( - context, - ).showSnackBar(const SnackBar(content: Text('Prompt copied.'))); - } + await Clipboard.setData(ClipboardData(text: prompt)); + message = 'Prompt copied to clipboard.'; } catch (_) { - if (context.mounted) { - ScaffoldMessenger.of( - context, - ).showSnackBar(const SnackBar(content: Text('Could not copy prompt.'))); - } + message = 'Could not copy prompt to clipboard.'; + } + if (!mounted) return; + final scaffold = cupertino ? null : Scaffold.maybeOf(context); + final inline = cupertino || scaffold == null; + setState(() { + _copying = false; + _copyStatus = inline ? message : null; + }); + if (!cupertino && scaffold != null) { + ScaffoldMessenger.maybeOf( + context, + )?.showSnackBar(SnackBar(content: Text(message))); } } } diff --git a/app/notes/R1c2.md b/app/notes/R1c2.md new file mode 100644 index 00000000..e7eced2e --- /dev/null +++ b/app/notes/R1c2.md @@ -0,0 +1,50 @@ +# R1c2 — run detail native widget slice + +## Change + +`RunDetailView` keeps its existing `controller` and `onBack` API but now selects +its presentation from the host: MaterialApp uses the standard Material controls, +CupertinoApp uses Cupertino controls without a Material ancestor. Selection is +based on `MaterialLocalizations`, so it works on the web's desktop host and in +widget tests without relying on the browser's target platform. + +- Material: `Chip`, `ExpansionTile`, `ListTile`, `TextButton`, `IconButton`, + selectable text and `SnackBar` feedback. +- Cupertino: `CupertinoButton`, `CupertinoExpansionTile`, `CupertinoListTile` + and grouped list sections. Copy feedback is inline in a live-region status; + no `ScaffoldMessenger`/`SnackBar` is used. +- Loading and failure states are platform-specific and honest: only the error + text is shown when no detail exists, and the Back action remains available. + A refresh with retained detail reports `Refreshing run details…` instead of + clearing the view. +- The scrollable list has a stable per-run key and a test proves a live detail + update keeps its scroll offset. + +Detail-only helpers split formatting from presentation: + +- `run_detail_content.dart`: title/pipeline, prompt extraction, nested JSON, + usage metrics and recorded timeline entries. +- `run_detail_material.dart` and `run_detail_cupertino.dart`: the two native + presentations. +- Input/output are pretty-printed, selectable JSON. Copy prompt passes the + stored string byte-for-byte (no trim, no fallback field). +- Usage distinguishes reported zero from unknown: token/cost totals are + `Unavailable` unless the corresponding stage count proves reporting; a known + stage count with an omitted zero cost renders `$0.000000`. Timeline rows show + the server's recorded sequence. + +## Verification + +- `flutter test test/features/runs/ui/run_detail_widget_test.dart`: 7 tests + passed. They run both platforms at 390px width with 2x text, exercise + loading/error and Back, exact prompt copy and denied clipboard feedback, + nested JSON, recorded sequences, zero vs missing usage, and scroll retention. +- `flutter test test/features/runs`: 24 tests passed. +- `flutter analyze`: no issues. +- `flutter build web`: succeeded. + +## Limits + +No real browser interaction or rendered capture was performed in this slice; the +manager separately tracks R1 browser acceptance. Android/iOS builds and devices +were not run, so mobile is unverified. No commit, push or deployment was made. diff --git a/app/test/features/runs/ui/run_detail_widget_test.dart b/app/test/features/runs/ui/run_detail_widget_test.dart new file mode 100644 index 00000000..4683db7e --- /dev/null +++ b/app/test/features/runs/ui/run_detail_widget_test.dart @@ -0,0 +1,264 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/data/runs_repository.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_view.dart'; +import 'package:pipelines_app/features/runs/ui/runs_controller.dart'; + +enum AppPlatform { material, cupertino } + +class FakeGateway implements ApiGateway { + FakeGateway(this.detail); + JsonMap detail; + Object? failure; + Completer? hold; + + @override + Stream get frames => const Stream.empty(); + + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type != 'get_run') throw UnsupportedError(type); + if (hold != null) return hold!.future; + if (failure != null) return Future.error(failure!); + return Future.value({'run_detail': detail}); + } +} + +const prompt = ' keep\n\nspacing '; + +JsonMap runFixture({JsonMap? usage, int steps = 2}) { + final run = { + 'id': 7, + 'title': 'Nightly build', + 'name': 'release', + 'status': 'succeeded', + 'input': { + 'prompt': prompt, + 'nested': { + 'alpha': 1, + 'items': [1, 2], + }, + }, + 'output': { + 'result': {'ok': true}, + }, + 'steps': [ + for (var i = 0; i < steps; i++) + { + 'stage': i == 0 ? 'build' : 'test', + 'sequence': i + 3, + 'status': 'completed', + 'outcome': 'success', + 'target': '#success', + }, + ], + }; + if (usage != null) run['usage'] = usage; + return run; +} + +JsonMap usageFixture({int known = 1}) => { + 'stages': 1, + 'tokens_total': 0, + 'tokens_known_stages': known, + 'tokens_in': 0, + 'tokens_out': 0, + 'split_known': true, + 'cost_known_stages': known, +}; + +Future pumpDetail( + WidgetTester tester, + AppPlatform platform, + RunsController controller, { + VoidCallback? onBack, + bool settle = true, +}) async { + tester.view.physicalSize = const Size(390, 1600); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final view = RunDetailView(controller: controller, onBack: onBack ?? () {}); + final page = MediaQuery( + data: MediaQueryData.fromView( + tester.view, + ).copyWith(textScaler: const TextScaler.linear(2)), + child: view, + ); + await tester.pumpWidget( + platform == AppPlatform.material + ? MaterialApp(home: Scaffold(body: page)) + : CupertinoApp( + home: CupertinoPageScaffold(child: SafeArea(child: page)), + ), + ); + if (settle) { + await tester.pumpAndSettle(); + } else { + await tester.pump(); + } +} + +void mockClipboard( + WidgetTester tester, + List copied, { + bool Function()? denied, +}) { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + if (call.method != 'Clipboard.setData') return null; + if (denied?.call() ?? false) { + throw PlatformException(code: 'clipboard-denied'); + } + copied.add((call.arguments as Map)['text'] as String); + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); +} + +void main() { + late FakeGateway gateway; + late RunsController controller; + + setUp(() { + gateway = FakeGateway(runFixture()); + controller = RunsController(RunsRepository(gateway)); + }); + tearDown(() => controller.dispose()); + + for (final platform in AppPlatform.values) { + testWidgets('${platform.name} detail at 390 with 2x text', (tester) async { + gateway.detail = runFixture(steps: 12); + await controller.select(1); + await pumpDetail(tester, platform, controller); + expect(tester.takeException(), isNull); + expect(find.text('Nightly build'), findsOneWidget); + expect(find.textContaining('Original prompt'), findsOneWidget); + if (platform == AppPlatform.material) { + expect(find.byType(Chip), findsOneWidget); + expect(find.byType(ExpansionTile), findsNWidgets(2)); + } else { + expect(find.byType(Material), findsNothing); + expect(find.byType(Chip), findsNothing); + expect(find.byType(CupertinoExpansionTile), findsNWidgets(2)); + } + + await tester.tap(find.text('Input')); + await tester.pumpAndSettle(); + expect(find.textContaining('"alpha": 1'), findsOneWidget); + await tester.scrollUntilVisible( + find.text('Output'), + 200, + scrollable: find.byType(Scrollable).first, + ); + await tester.tap(find.text('Output')); + await tester.pumpAndSettle(); + expect(find.textContaining('"ok": true'), findsOneWidget); + + await tester.scrollUntilVisible( + find.textContaining('build · visit 3'), + 200, + scrollable: find.byType(Scrollable).first, + ); + expect(find.textContaining('build · visit 3'), findsOneWidget); + expect(find.textContaining('test · visit 4'), findsOneWidget); + if (platform == AppPlatform.material) { + final scrollable = tester.state( + find.byType(Scrollable).first, + ); + final before = scrollable.position.pixels; + expect(before, greaterThan(0)); + gateway.detail = runFixture(steps: 13); + await controller.select(1); + await tester.pumpAndSettle(); + expect(scrollable.position.pixels, closeTo(before, 0.1)); + } + }); + + testWidgets('${platform.name} loading and error stay honest', ( + tester, + ) async { + gateway.hold = Completer(); + final pending = controller.select(1); + await pumpDetail(tester, platform, controller, settle: false); + expect(find.text('Loading run details…'), findsOneWidget); + expect( + find.byType( + platform == AppPlatform.material + ? CircularProgressIndicator + : CupertinoActivityIndicator, + ), + findsOneWidget, + ); + gateway.hold!.complete({'run_detail': runFixture()}); + await pending; + await tester.pumpAndSettle(); + expect(find.text('Nightly build'), findsOneWidget); + + controller.dispose(); + gateway = FakeGateway(runFixture()) + ..failure = StateError('server unavailable'); + controller = RunsController(RunsRepository(gateway)); + await controller.select(1); + var backs = 0; + await pumpDetail(tester, platform, controller, onBack: () => backs++); + expect(find.textContaining('server unavailable'), findsOneWidget); + await tester.tap(find.text('Back to runs')); + expect(backs, 1); + }); + + testWidgets('${platform.name} copies the exact prompt and reports denial', ( + tester, + ) async { + final copied = []; + var denied = false; + mockClipboard(tester, copied, denied: () => denied); + final copy = platform == AppPlatform.material + ? find.byTooltip('Copy prompt') + : find.text('Copy prompt'); + await controller.select(1); + await pumpDetail(tester, platform, controller); + await tester.tap(copy); + await tester.pumpAndSettle(); + expect(copied.single, prompt); + expect(find.text('Prompt copied to clipboard.'), findsOneWidget); + if (platform == AppPlatform.material) { + await tester.pump(const Duration(seconds: 5)); + await tester.pumpAndSettle(); + } + denied = true; + await tester.tap(copy); + await tester.pumpAndSettle(); + expect(find.text('Could not copy prompt to clipboard.'), findsOneWidget); + }); + } + + testWidgets('reported zero and missing usage stay distinct', (tester) async { + gateway.detail = runFixture(usage: usageFixture()); + await controller.select(1); + await pumpDetail(tester, AppPlatform.material, controller); + await tester.tap(find.text('Metrics')); + await tester.pumpAndSettle(); + expect(find.text('Unavailable'), findsNothing); + expect(find.text('0'), findsNWidgets(3)); + expect(find.text('\$0.000000'), findsOneWidget); + + gateway.detail = runFixture(usage: usageFixture(known: 0)); + await controller.select(1); + await tester.pumpAndSettle(); + expect(find.text('Unavailable'), findsNWidgets(4)); + expect(find.text('0'), findsNothing); + }); +} From 42b21b86cd8733c71d68214aa9d36ae5515d0234 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 14:22:29 +0100 Subject: [PATCH 30/84] feat(app): add deliberate human-decision action for run detail Adds HumanDecisionAction plus its native prompt, wording constants and tests. The action renders only while pendingDecision() reports a genuine human wait, sends decide_run only after an option is chosen and Confirm pressed, sends the pending stage/trimmed option/optional feedback, blocks double submits, shows server refusals verbatim with the draft intact, and re-reads the run so the owner always receives server truth. --- .../runs/actions/decision_action.dart | 141 ++++++++++ .../runs/actions/decision_dialog.dart | 248 ++++++++++++++++++ .../runs/actions/decision_wording.dart | 24 ++ app/notes/R2a.md | 84 ++++++ .../runs/actions/decision_action_test.dart | 237 +++++++++++++++++ .../actions/decision_resilience_test.dart | 240 +++++++++++++++++ 6 files changed, 974 insertions(+) create mode 100644 app/lib/features/runs/actions/decision_action.dart create mode 100644 app/lib/features/runs/actions/decision_dialog.dart create mode 100644 app/lib/features/runs/actions/decision_wording.dart create mode 100644 app/notes/R2a.md create mode 100644 app/test/features/runs/actions/decision_action_test.dart create mode 100644 app/test/features/runs/actions/decision_resilience_test.dart diff --git a/app/lib/features/runs/actions/decision_action.dart b/app/lib/features/runs/actions/decision_action.dart new file mode 100644 index 00000000..5405accf --- /dev/null +++ b/app/lib/features/runs/actions/decision_action.dart @@ -0,0 +1,141 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../data/runs_repository.dart'; +import '../domain/run_decisions.dart'; +import '../domain/run_models.dart'; +import 'decision_dialog.dart'; +import 'decision_wording.dart'; + +/// The run detail's deliberate human-decision entry point. +/// +/// Renders one native button only while [run] is genuinely waiting on a person. +/// Nothing is sent until the operator opens the prompt, chooses an option and +/// presses Confirm; cancel, selection and optional feedback stay local. A +/// server refusal is shown verbatim in the prompt, the draft is preserved and +/// the run is re-read so [onRunChanged] always receives server truth. +class HumanDecisionAction extends StatefulWidget { + const HumanDecisionAction({ + super.key, + required this.run, + required this.gateway, + required this.onRunChanged, + this.cupertino, + }); + + final JsonMap run; + final ApiGateway gateway; + final ValueChanged onRunChanged; + + /// Overrides the platform style; by default it follows the enclosing app. + final bool? cupertino; + + @override + State createState() => _HumanDecisionActionState(); +} + +class _HumanDecisionActionState extends State { + PendingDecision? _pending; + bool _dialogOpen = false; + bool _sending = false; + + @override + void initState() { + super.initState(); + _pending = pendingDecision(widget.run); + } + + @override + void didUpdateWidget(covariant HumanDecisionAction oldWidget) { + super.didUpdateWidget(oldWidget); + _pending = pendingDecision(widget.run); + } + + bool _usesCupertino(BuildContext context) { + if (widget.cupertino != null) return widget.cupertino!; + final material = Localizations.of( + context, + MaterialLocalizations, + ); + return material == null; + } + + Future _open() async { + final decision = _pending; + if (decision == null || _dialogOpen) return; + _dialogOpen = true; + try { + await showHumanDecisionPrompt( + context: context, + decision: decision, + cupertino: _usesCupertino(context), + onSubmit: (draft) => _submit(decision, draft), + ); + } finally { + _dialogOpen = false; + if (mounted) setState(() {}); + } + } + + Future _submit(PendingDecision decision, DecisionDraft draft) async { + final option = draft.selected?.trim() ?? ''; + if (option.isEmpty || _sending) return null; + _sending = true; + final repository = RunsRepository(widget.gateway); + try { + final JsonMap run; + try { + run = await repository.decideRun( + decision.runId, + stage: decision.stageKey, + option: option, + feedback: draft.feedback, + ); + } catch (error) { + final refusal = _describe(error); + if (!mounted) return refusal; + JsonMap? refreshed; + try { + refreshed = await repository.getRun(decision.runId); + } catch (_) { + // A failed re-read must not hide or replace the server's refusal. + } + if (refreshed != null && mounted) { + setState(() => _pending = pendingDecision(refreshed)); + widget.onRunChanged(refreshed); + } + return refusal; + } + if (!mounted) return null; + setState(() => _pending = pendingDecision(run)); + widget.onRunChanged(run); + return null; + } finally { + _sending = false; + } + } + + @override + Widget build(BuildContext context) { + final decision = _pending; + if (decision == null) return const SizedBox.shrink(); + if (_usesCupertino(context)) { + return CupertinoButton.filled( + key: decisionActionKey, + onPressed: _open, + child: const Text(decisionActionLabel), + ); + } + return FilledButton( + key: decisionActionKey, + onPressed: _open, + child: const Text(decisionActionLabel), + ); + } +} + +String _describe(Object error) { + final message = '$error'; + return message.trim().isEmpty ? 'The server refused the decision.' : message; +} diff --git a/app/lib/features/runs/actions/decision_dialog.dart b/app/lib/features/runs/actions/decision_dialog.dart new file mode 100644 index 00000000..9649ea16 --- /dev/null +++ b/app/lib/features/runs/actions/decision_dialog.dart @@ -0,0 +1,248 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../domain/run_decisions.dart'; +import '../domain/run_models.dart'; +import 'decision_wording.dart'; + +/// Sends the draft to the server. Returns null on success, or the server's +/// refusal message verbatim; the prompt stays open with the draft intact. +typedef DecisionSubmit = Future Function(DecisionDraft draft); + +/// Opens the native decision prompt for [decision]. +Future showHumanDecisionPrompt({ + required BuildContext context, + required PendingDecision decision, + required bool cupertino, + required DecisionSubmit onSubmit, +}) { + final prompt = _DecisionPrompt( + decision: decision, + cupertino: cupertino, + onSubmit: onSubmit, + ); + if (cupertino) { + return showCupertinoDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); + } + return showDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); +} + +class _DecisionPrompt extends StatefulWidget { + const _DecisionPrompt({ + required this.decision, + required this.cupertino, + required this.onSubmit, + }); + + final PendingDecision decision; + final bool cupertino; + final DecisionSubmit onSubmit; + + @override + State<_DecisionPrompt> createState() => _DecisionPromptState(); +} + +class _DecisionPromptState extends State<_DecisionPrompt> { + DecisionDraft _draft = const DecisionDraft(); + late final TextEditingController _feedback = TextEditingController(); + bool _sending = false; + String? _error; + + @override + void dispose() { + _feedback.dispose(); + super.dispose(); + } + + void _select(String option) { + if (_sending) return; + setState(() => _draft = _draft.select(option)); + } + + void _feedbackChanged(String value) => _draft = _draft.withFeedback(value); + + void _cancel() { + if (!_sending) Navigator.of(context).pop(); + } + + Future _confirm() async { + if (_sending || !_draft.canSubmit) return; + setState(() { + _sending = true; + _error = null; + }); + final refusal = await widget.onSubmit(_draft); + if (!mounted) return; + if (refusal == null) { + Navigator.of(context).pop(); + return; + } + setState(() { + _sending = false; + _error = refusal; + }); + } + + @override + Widget build(BuildContext context) { + final dialog = widget.cupertino ? _cupertino(context) : _material(context); + return PopScope(canPop: !_sending, child: dialog); + } + + Widget _material(BuildContext context) { + final theme = Theme.of(context); + return AlertDialog( + scrollable: true, + title: const Text(decisionWaitingTitle), + content: _body( + errorStyle: TextStyle(color: theme.colorScheme.error), + options: RadioGroup( + groupValue: _draft.selected, + onChanged: (value) { + if (value != null) _select(value); + }, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final option in widget.decision.options) + RadioListTile( + value: option.key, + enabled: !_sending, + title: Text(option.key), + subtitle: _target(option), + ), + ], + ), + ), + feedback: TextField( + key: decisionFeedbackKey, + controller: _feedback, + enabled: !_sending, + decoration: const InputDecoration(labelText: decisionFeedbackLabel), + textInputAction: TextInputAction.done, + onChanged: _feedbackChanged, + onSubmitted: (_) => _confirm(), + ), + ), + actions: [ + TextButton( + onPressed: _sending ? null : _cancel, + child: const Text(decisionCancelLabel), + ), + FilledButton( + onPressed: _sending || !_draft.canSubmit ? null : _confirm, + child: Text(_sending ? decisionSendingLabel : decisionConfirmLabel), + ), + ], + ); + } + + Widget _cupertino(BuildContext context) { + return CupertinoAlertDialog( + title: const Text(decisionWaitingTitle), + content: _body( + errorStyle: TextStyle( + color: CupertinoColors.systemRed.resolveFrom(context), + ), + options: RadioGroup( + groupValue: _draft.selected, + onChanged: (value) { + if (value != null) _select(value); + }, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final option in widget.decision.options) + CupertinoButton( + onPressed: _sending ? null : () => _select(option.key), + child: Row( + children: [ + CupertinoRadio( + value: option.key, + useCheckmarkStyle: true, + enabled: !_sending, + ), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(option.key), + if (_targetText(option) case final target?) + Text(target), + ], + ), + ), + ], + ), + ), + ], + ), + ), + feedback: CupertinoTextField( + key: decisionFeedbackKey, + controller: _feedback, + enabled: !_sending, + placeholder: decisionFeedbackLabel, + textInputAction: TextInputAction.done, + onChanged: _feedbackChanged, + onSubmitted: (_) => _confirm(), + ), + ), + actions: [ + CupertinoDialogAction( + onPressed: _sending ? null : _cancel, + child: const Text(decisionCancelLabel), + ), + CupertinoDialogAction( + isDefaultAction: true, + onPressed: _sending || !_draft.canSubmit ? null : _confirm, + child: Text(_sending ? decisionSendingLabel : decisionConfirmLabel), + ), + ], + ); + } + + Widget _body({ + required TextStyle errorStyle, + required Widget options, + required Widget feedback, + }) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(decisionMeta(widget.decision)), + if (widget.decision.instructions.trim().isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(widget.decision.instructions), + ), + Padding(padding: const EdgeInsets.only(top: 8), child: options), + Padding(padding: const EdgeInsets.only(top: 8), child: feedback), + if (_error case final error?) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(error, key: decisionErrorKey, style: errorStyle), + ), + ], + ); + } + + Widget? _target(DecisionOption option) { + final text = _targetText(option); + return text == null ? null : Text(text); + } + + String? _targetText(DecisionOption option) { + final text = decisionTargetText(option.target); + return text.isEmpty ? null : text; + } +} diff --git a/app/lib/features/runs/actions/decision_wording.dart b/app/lib/features/runs/actions/decision_wording.dart new file mode 100644 index 00000000..a9904946 --- /dev/null +++ b/app/lib/features/runs/actions/decision_wording.dart @@ -0,0 +1,24 @@ +import 'package:flutter/widgets.dart'; + +import '../domain/run_decisions.dart'; + +/// The browser client's decision wording, kept verbatim. +const decisionWaitingTitle = 'Waiting for your decision'; +const decisionActionLabel = 'Decide'; +const decisionFeedbackLabel = 'Feedback (optional)'; +const decisionCancelLabel = 'Cancel'; +const decisionConfirmLabel = 'Confirm decision'; +const decisionSendingLabel = 'Sending…'; + +/// Stable test/semantics keys shared by the action and its prompt. +const decisionActionKey = ValueKey('human-decision-action'); +const decisionFeedbackKey = ValueKey('human-decision-feedback'); +const decisionErrorKey = ValueKey('human-decision-error'); + +/// `{stage} · run {id} · {label}`, as the web decision card shows it. +String decisionMeta(PendingDecision decision) => + '${decision.stageKey} · run ${decision.runId} · ${decision.runLabel}'; + +/// The option's target line, `→ {target}`, or "" when no target was declared. +String decisionTargetText(String target) => + target.trim().isEmpty ? '' : '→ $target'; diff --git a/app/notes/R2a.md b/app/notes/R2a.md new file mode 100644 index 00000000..30ec1ace --- /dev/null +++ b/app/notes/R2a.md @@ -0,0 +1,84 @@ +# R2a — native human-decision action + +## What changed + +New `lib/features/runs/actions/` slice (no existing source file edited): + +| File | Lines | Responsibility | +| --- | --- | --- | +| `decision_action.dart` | 141 | `HumanDecisionAction`, gating, submit/refusal/resync orchestration | +| `decision_dialog.dart` | 248 | Material `AlertDialog` / Cupertino `CupertinoAlertDialog` prompt | +| `decision_wording.dart` | 24 | Web-verbatim words, meta/target formatting and test keys | +| `test/.../decision_action_test.dart` | 237 | Material/Cupertino deliberate send and gating | +| `test/.../decision_resilience_test.dart` | 240 | refusal resync, double submit, disposal, 2x/narrow | + +`HumanDecisionAction` takes the run, the shared `ApiGateway` and an +`onRunChanged` callback. It renders one `FilledButton` (`Decide`) on Material +and one `CupertinoButton.filled` on Cupertino, and nothing at all when +`pendingDecision(run)` is null. Recorded waiting-step options therefore win over +the pinned graph, and a pending session export suppresses the action through the +existing domain rule without duplicating it here. + +Opening the prompt sends nothing. The prompt uses the web wording +(`Waiting for your decision`, `Feedback (optional)`, `Cancel`, +`Confirm decision`, `Sending…`), shows the stage/run meta line and each option's +`→ target` when declared. Confirm is disabled until an option is selected; +selecting itself only updates the draft. Confirm calls `RunsRepository.decideRun` +with the exact stage, trimmed option and trimmed optional feedback (blank +feedback is omitted by the repository). + +A refusal is shown verbatim inside the kept-open prompt; the option selection +and feedback controller are untouched. The action then calls +`RunsRepository.getRun` and passes the refreshed run to `onRunChanged`. A +successful decision passes the server's `run_detail` to `onRunChanged` and +closes the prompt. Both sends are guarded in the prompt and in the owner state; +buttons are disabled while `Sending…`. Every asynchronous resume checks +`mounted` before `setState` or `onRunChanged`, so a late reply after disposal is +ignored. + +Platform style follows the enclosing app: `MaterialApp` gets the Material +dialog and controls, `CupertinoApp` gets the Cupertino dialog with native +buttons/radios/field. No custom palette, font family, fixed button/row size, +dependency or CSS token was added; the theme's error color and default control +spacing are used. The one optional `cupertino` override exists for +callers/tests that do not wrap in either app. + +## Checks actually run + +``` +flutter pub get # dependencies resolved +dart format lib/features/runs/actions test/features/runs/actions +flutter analyze # No issues found! +flutter test test/features/runs # 18 passed +flutter test # 36 passed +flutter test test/features/runs/actions # 7 passed +flutter build web # Built build/web (14.2s) +``` + +Focused coverage maps to the requested acceptance: + +- material: action visible, dialog open, selection does not send, Confirm is + disabled before selection, exact `decide_run` stage/option/`looks good` + feedback, callback gets the decided run and the action disappears; +- cupertino: native `CupertinoAlertDialog`, disabled Confirm first, blank + feedback omitted, exact request fields; +- gating: running, export-pending and non-human runs render no action; +- refusal: `decide_run` then `get_run`, verbatim error still visible, selected + option and typed feedback retained, refreshed failed run delivered to owner; +- double submit: two Confirm taps produce one `decide_run`, Cancel is disabled + while sending; +- stale disposal: completing the decision after the tree is replaced produces + no exception and no owner callback; +- 320×480 at 2x text on both apps: prompt opens with no rendering exception. + +## Honest limits + +- **Not wired into a run-detail screen.** `lib/features/runs/` has no screen or + controller on this branch; the manager owns that integration. There is + therefore no real browser interaction or capture for this widget. The + `flutter build web` result proves compilation only, not rendered behavior. +- **Mobile unverified.** No Android/iOS build, emulator, ADB or device was used. + Source uses only portable Flutter/Cupertino/Material widgets. +- No real server or run was mutated. Tests use a local fake gateway. +- No repository/domain/controller/screen/main, `web/`, Go server, installer or + deployment file was changed. Nothing was committed, pushed or deployed. diff --git a/app/test/features/runs/actions/decision_action_test.dart b/app/test/features/runs/actions/decision_action_test.dart new file mode 100644 index 00000000..9d424b8f --- /dev/null +++ b/app/test/features/runs/actions/decision_action_test.dart @@ -0,0 +1,237 @@ +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/features/runs/actions/decision_action.dart'; +import 'package:pipelines_app/features/runs/actions/decision_wording.dart'; + +typedef _Handler = Future Function(String type, JsonMap fields); + +class _FakeGateway implements ApiGateway { + _FakeGateway(this.handler); + + final _Handler handler; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) { + final copy = Map.from(fields); + calls.add((type: type, fields: copy)); + return handler(type, copy); + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap _waitingRun({ + String status = 'waiting', + int exportPending = 0, + String type = 'human', + List options = const ['go', 'skip'], +}) => { + 'id': 7, + 'title': 'Report', + 'name': 'Build', + 'status': status, + 'current_stage': 'human', + 'export_pending_sequence': exportPending, + 'graph': { + 'stages': [ + { + 'key': 'human', + 'type': type, + 'prompt': 'Graph prompt', + 'edges': {'go': '#', 'skip': 'finish'}, + }, + ], + }, + 'steps': [ + { + 'sequence': 1, + 'status': 'waiting', + 'stage': 'human', + 'output': {'prompt': 'Ship it?', 'options': options}, + }, + ], +}; + +JsonMap _decided() => { + ..._waitingRun(), + 'status': 'succeeded', + 'steps': const [], +}; + +Widget _app(Widget child, {required bool cupertino, double textScale = 1}) { + if (cupertino) { + return CupertinoApp( + builder: (context, app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ), + home: CupertinoPageScaffold(child: Center(child: child)), + ); + } + return MaterialApp( + builder: (context, app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ), + home: Scaffold(body: Center(child: child)), + ); +} + +Future _pump( + WidgetTester tester, + _FakeGateway gateway, + JsonMap run, { + required bool cupertino, + required List changed, + double textScale = 1, +}) async { + await tester.pumpWidget( + _app( + HumanDecisionAction( + run: run, + gateway: gateway, + onRunChanged: changed.add, + ), + cupertino: cupertino, + textScale: textScale, + ), + ); +} + +Future _open(WidgetTester tester) async { + await tester.tap(find.byKey(decisionActionKey)); + await tester.pumpAndSettle(); +} + +void main() { + testWidgets( + 'material decision waits for option and confirm, then sends exact fields', + (tester) async { + final gateway = _FakeGateway( + (type, fields) async => { + 'run_detail': type == 'decide_run' ? _decided() : _waitingRun(), + }, + ); + final changed = []; + await _pump( + tester, + gateway, + _waitingRun(), + cupertino: false, + changed: changed, + ); + + expect(find.byKey(decisionActionKey), findsOneWidget); + expect(find.byType(FilledButton), findsOneWidget); + expect(gateway.calls, isEmpty); + + await _open(tester); + expect(find.byType(AlertDialog), findsOneWidget); + expect(find.text(decisionWaitingTitle), findsOneWidget); + expect(find.text('Ship it?'), findsOneWidget); + expect(find.text('→ SUCCESS'), findsOneWidget); + expect(gateway.calls, isEmpty); + + final confirm = find.widgetWithText(FilledButton, decisionConfirmLabel); + expect(tester.widget(confirm).onPressed, isNull); + + await tester.tap(find.text('go')); + await tester.pump(); + expect(gateway.calls, isEmpty); + expect(tester.widget(confirm).onPressed, isNotNull); + + await tester.enterText(find.byKey(decisionFeedbackKey), ' looks good '); + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['decide_run']); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'stage': 'human', + 'option': 'go', + 'feedback': 'looks good', + }); + expect(changed.single['status'], 'succeeded'); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(decisionActionKey), findsNothing); + }, + ); + + testWidgets( + 'cupertino decision uses a native dialog and omits empty feedback', + (tester) async { + final gateway = _FakeGateway( + (type, fields) async => { + 'run_detail': type == 'decide_run' ? _decided() : _waitingRun(), + }, + ); + final changed = []; + await _pump( + tester, + gateway, + _waitingRun(), + cupertino: true, + changed: changed, + ); + + expect(find.byKey(decisionActionKey), findsOneWidget); + expect(find.byType(FilledButton), findsNothing); + await _open(tester); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.text(decisionWaitingTitle), findsOneWidget); + expect(gateway.calls, isEmpty); + + final confirm = find.widgetWithText( + CupertinoDialogAction, + decisionConfirmLabel, + ); + expect(tester.widget(confirm).onPressed, isNull); + await tester.tap(find.text('skip')); + await tester.pump(); + expect(gateway.calls, isEmpty); + + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['decide_run']); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'stage': 'human', + 'option': 'skip', + }); + expect(changed.single['status'], 'succeeded'); + expect(find.byType(CupertinoAlertDialog), findsNothing); + }, + ); + + testWidgets('the action is absent unless a run is genuinely waiting', ( + tester, + ) async { + final gateway = _FakeGateway( + (type, fields) async => {'run_detail': _waitingRun()}, + ); + final changed = []; + for (final (label, run) in [ + ('not waiting', _waitingRun(status: 'running')), + ('export pending', _waitingRun(exportPending: 2)), + ('model stage', _waitingRun(type: 'model')), + ]) { + await _pump(tester, gateway, run, cupertino: false, changed: changed); + expect( + find.byKey(decisionActionKey), + findsNothing, + reason: '$label must not offer a decision', + ); + } + expect(gateway.calls, isEmpty); + expect(changed, isEmpty); + }); +} diff --git a/app/test/features/runs/actions/decision_resilience_test.dart b/app/test/features/runs/actions/decision_resilience_test.dart new file mode 100644 index 00000000..d23981b5 --- /dev/null +++ b/app/test/features/runs/actions/decision_resilience_test.dart @@ -0,0 +1,240 @@ +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/decision_action.dart'; +import 'package:pipelines_app/features/runs/actions/decision_wording.dart'; + +typedef _Handler = Future Function(String type, JsonMap fields); + +class _FakeGateway implements ApiGateway { + _FakeGateway(this.handler); + + final _Handler handler; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) { + final copy = Map.from(fields); + calls.add((type: type, fields: copy)); + return handler(type, copy); + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap _waitingRun() => { + 'id': 7, + 'title': 'Report', + 'status': 'waiting', + 'current_stage': 'human', + 'graph': { + 'stages': [ + { + 'key': 'human', + 'type': 'human', + 'prompt': 'Graph prompt', + 'edges': {'go': '#', 'skip': 'finish'}, + }, + ], + }, + 'steps': [ + { + 'sequence': 1, + 'status': 'waiting', + 'stage': 'human', + 'output': { + 'prompt': 'Ship it?', + 'options': ['go', 'skip'], + }, + }, + ], +}; + +JsonMap _decided() => { + ..._waitingRun(), + 'status': 'succeeded', + 'steps': const [], +}; + +Widget _app(Widget child, {required bool cupertino, double textScale = 1}) { + Widget media(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + if (cupertino) { + return CupertinoApp( + builder: media, + home: CupertinoPageScaffold(child: Center(child: child)), + ); + } + return MaterialApp( + builder: media, + home: Scaffold(body: Center(child: child)), + ); +} + +Future _pump( + WidgetTester tester, + _FakeGateway gateway, + List changed, { + bool cupertino = false, + double textScale = 1, +}) async { + await tester.pumpWidget( + _app( + HumanDecisionAction( + run: _waitingRun(), + gateway: gateway, + onRunChanged: changed.add, + ), + cupertino: cupertino, + textScale: textScale, + ), + ); +} + +Future _chooseGo(WidgetTester tester, {String feedback = ''}) async { + await tester.tap(find.byKey(decisionActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.text('go')); + await tester.pump(); + if (feedback.isNotEmpty) { + await tester.enterText(find.byKey(decisionFeedbackKey), feedback); + } +} + +void main() { + testWidgets('a refusal stays visible and keeps the selected draft', ( + tester, + ) async { + const refusal = 'option "go" is not a valid outcome; choose one of: skip'; + final gateway = _FakeGateway((type, fields) async { + if (type == 'decide_run') throw const ProtocolError(refusal); + expect(type, 'get_run'); + return { + 'run_detail': { + ..._waitingRun(), + 'status': 'failed', + 'steps': const [], + }, + }; + }); + final changed = []; + await _pump(tester, gateway, changed); + await _chooseGo(tester, feedback: ' keep me '); + + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['decide_run', 'get_run']); + expect(gateway.calls.last.fields, {'run_id': 7}); + expect(find.text(refusal), findsOneWidget); + expect(find.byType(AlertDialog), findsOneWidget); + expect( + tester + .widget>(find.byType(RadioGroup)) + .groupValue, + 'go', + ); + expect( + tester + .widget(find.byKey(decisionFeedbackKey)) + .controller + ?.text, + ' keep me ', + ); + expect(changed.single['status'], 'failed'); + expect(find.byKey(decisionActionKey), findsNothing); + }); + + testWidgets('confirm cannot submit twice while the decision is in flight', ( + tester, + ) async { + final reply = Completer(); + final gateway = _FakeGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + await _chooseGo(tester); + + final confirm = find.text(decisionConfirmLabel); + await tester.tap(confirm); + await tester.tap(confirm); + await tester.pump(); + + expect( + gateway.calls.where((call) => call.type == 'decide_run'), + hasLength(1), + ); + expect(find.text(decisionSendingLabel), findsOneWidget); + expect( + tester + .widget( + find.widgetWithText(TextButton, decisionCancelLabel), + ) + .onPressed, + isNull, + ); + + reply.complete({'run_detail': _decided()}); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(changed, hasLength(1)); + }); + + testWidgets('a late reply after disposal is ignored safely', (tester) async { + final reply = Completer(); + final gateway = _FakeGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + await _chooseGo(tester); + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pump(); + expect(gateway.calls, hasLength(1)); + + await tester.pumpWidget(const SizedBox()); + reply.complete({'run_detail': _decided()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + + testWidgets('both prompts fit 2x text at a narrow width', (tester) async { + tester.view.physicalSize = const Size(320, 480); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + for (final cupertino in [false, true]) { + final gateway = _FakeGateway( + (type, fields) async => {'run_detail': _decided()}, + ); + await _pump( + tester, + gateway, + [], + cupertino: cupertino, + textScale: 2, + ); + await tester.tap(find.byKey(decisionActionKey)); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino'); + expect(find.text(decisionWaitingTitle), findsOneWidget); + expect(find.text('Ship it?'), findsOneWidget); + expect( + cupertino + ? find.byType(CupertinoAlertDialog) + : find.byType(AlertDialog), + findsOneWidget, + ); + } + }); +} From 76eda0ee0e8a48def3358975c78c1c62f181aeb1 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 14:22:51 +0100 Subject: [PATCH 31/84] docs(app): accept combined runs widgets and launch live composition checks --- app/WORK.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/WORK.md b/app/WORK.md index 743ea2a9..7f74f228 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -15,10 +15,11 @@ All work under app/. Existing applications remain running and unchanged. | P1 | Pipeline list/detail/source/version browser | run 34 / flutter/p1-pipelines | running (DeepSeek V4.1 Flash) | pending | pending | | C1 | Chat session browser and management | 35 → resume 36 → focused C1b run 42 / flutter/f4-chat | catalog/grouping fixes + inspected browser captures retained; pipeline splitting 406-line screen and adding Cupertino/tests (Flash) | held; not parity-complete | pending | | N1 | Connection settings/preferences | run 37 / flutter/n1-settings | running (Flash) | pending | pending | -| R1 | Run list/detail/live timeline | controller43 + list48 accepted; detail46 active | merged controller into native-list branch; manager reran 18 combined tests + analyze, pass; source list247/controller260 cohesive lines | candidate integrated, whole UI held | browser integration pending | +| R1 | Run list/detail/live timeline | controller43 + list48 + detail46 accepted | manager merged all three on flutter/r1-native; reran 25 combined tests + analyze, pass | candidate integrated, held for I1 | I1 run50 wiring + browser verification | | D1 | Recorded changes/diff viewer | run 39 / flutter/d1-diff-viewer | running (Flash) | pending | pending | | R2a | Human-decision native confirm | run 47 / flutter/r2-decision | running (Flash), exact confirmation/refusal tests | pending | pending | | X1 | Native search and result targets | run 49 / flutter/x1-search | running (Flash) | pending | pending | +| I1 | App-owned socket/session + live Runs shell registration | run 50 / flutter/r1-native | running (Flash); real browser captures required | pending | pending | ## Next ready work - P1 pipelines list/detail/source/version; P2 graph and stage/visit selection. From 54b7e875e18fb210a560945385fa2b1275a9f5ad Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 14:33:15 +0100 Subject: [PATCH 32/84] docs(app): record decision component landing and cancel-action pipeline --- app/WORK.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/WORK.md b/app/WORK.md index 7f74f228..dc4c51d9 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -17,7 +17,8 @@ All work under app/. Existing applications remain running and unchanged. | N1 | Connection settings/preferences | run 37 / flutter/n1-settings | running (Flash) | pending | pending | | R1 | Run list/detail/live timeline | controller43 + list48 + detail46 accepted | manager merged all three on flutter/r1-native; reran 25 combined tests + analyze, pass | candidate integrated, held for I1 | I1 run50 wiring + browser verification | | D1 | Recorded changes/diff viewer | run 39 / flutter/d1-diff-viewer | running (Flash) | pending | pending | -| R2a | Human-decision native confirm | run 47 / flutter/r2-decision | running (Flash), exact confirmation/refusal tests | pending | pending | +| R2a | Human-decision native confirm | run47 / commit42b21b8 | manager inspected source + reran 7 exact-confirm/refusal/native tests + analyze, pass | main3e6f950, ancestry verified | reusable component only; wiring/browser pending | +| R2b | Native cancel-run confirmation | run51 / flutter/r2-cancel | running (Flash) | pending | pending | | X1 | Native search and result targets | run 49 / flutter/x1-search | running (Flash) | pending | pending | | I1 | App-owned socket/session + live Runs shell registration | run 50 / flutter/r1-native | running (Flash); real browser captures required | pending | pending | From faa5866410ec2719b1bc20844ba4883f9e575c09 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 14:41:33 +0100 Subject: [PATCH 33/84] feat(app): add deliberate run cancellation action Port the browser's canCancel rule and cancel_run request into a native Material/Cupertino confirmation. Opening the prompt or choosing Keep sends nothing; a refusal stays visible with the server's words and the run is re-read so the owner always receives server truth. Includes eligibility, double-submit, disposal and narrow 2x-text tests plus R2b evidence. --- .../features/runs/actions/cancel_dialog.dart | 145 +++++++++++++ .../runs/actions/cancel_eligibility.dart | 31 +++ .../runs/actions/cancel_run_action.dart | 101 +++++++++ .../features/runs/actions/cancel_wording.dart | 23 +++ app/notes/R2b.md | 96 +++++++++ .../runs/actions/cancel_action_test.dart | 192 ++++++++++++++++++ .../runs/actions/cancel_resilience_test.dart | 176 ++++++++++++++++ .../runs/actions/cancel_test_support.dart | 101 +++++++++ 8 files changed, 865 insertions(+) create mode 100644 app/lib/features/runs/actions/cancel_dialog.dart create mode 100644 app/lib/features/runs/actions/cancel_eligibility.dart create mode 100644 app/lib/features/runs/actions/cancel_run_action.dart create mode 100644 app/lib/features/runs/actions/cancel_wording.dart create mode 100644 app/notes/R2b.md create mode 100644 app/test/features/runs/actions/cancel_action_test.dart create mode 100644 app/test/features/runs/actions/cancel_resilience_test.dart create mode 100644 app/test/features/runs/actions/cancel_test_support.dart diff --git a/app/lib/features/runs/actions/cancel_dialog.dart b/app/lib/features/runs/actions/cancel_dialog.dart new file mode 100644 index 00000000..96f4c204 --- /dev/null +++ b/app/lib/features/runs/actions/cancel_dialog.dart @@ -0,0 +1,145 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'cancel_wording.dart'; + +/// Sends the confirmed cancellation. Returns null once the server has accepted +/// it, or the server's refusal verbatim; the prompt then stays open. +typedef CancelSubmit = Future Function(); + +/// Opens the native cancel confirmation for [runId]. +/// +/// Nothing is sent until the operator presses the confirm action, and the +/// dismiss action (`Keep`) only closes the prompt. +Future showCancelRunPrompt({ + required BuildContext context, + required num runId, + required bool cupertino, + required CancelSubmit onSubmit, +}) { + final prompt = _CancelPrompt( + runId: runId, + cupertino: cupertino, + onSubmit: onSubmit, + ); + if (cupertino) { + return showCupertinoDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); + } + return showDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); +} + +class _CancelPrompt extends StatefulWidget { + const _CancelPrompt({ + required this.runId, + required this.cupertino, + required this.onSubmit, + }); + + final num runId; + final bool cupertino; + final CancelSubmit onSubmit; + + @override + State<_CancelPrompt> createState() => _CancelPromptState(); +} + +class _CancelPromptState extends State<_CancelPrompt> { + bool _sending = false; + String? _error; + + void _keep() { + if (!_sending) Navigator.of(context).pop(); + } + + Future _confirm() async { + if (_sending) return; + setState(() { + _sending = true; + _error = null; + }); + final refusal = await widget.onSubmit(); + if (!mounted) return; + if (refusal == null) { + Navigator.of(context).pop(); + return; + } + setState(() { + _sending = false; + _error = refusal; + }); + } + + @override + Widget build(BuildContext context) { + final dialog = widget.cupertino ? _cupertino(context) : _material(context); + return PopScope(canPop: !_sending, child: dialog); + } + + Widget _material(BuildContext context) { + final theme = Theme.of(context); + return AlertDialog( + scrollable: true, + title: Text(cancelDialogTitle(widget.runId)), + content: _body(errorStyle: TextStyle(color: theme.colorScheme.error)), + actions: [ + TextButton( + key: cancelKeepKey, + onPressed: _sending ? null : _keep, + child: const Text(cancelKeepLabel), + ), + FilledButton( + key: cancelConfirmKey, + onPressed: _sending ? null : _confirm, + child: const Text(cancelConfirmLabel), + ), + ], + ); + } + + Widget _cupertino(BuildContext context) { + return CupertinoAlertDialog( + title: Text(cancelDialogTitle(widget.runId)), + content: _body( + errorStyle: TextStyle( + color: CupertinoColors.systemRed.resolveFrom(context), + ), + ), + actions: [ + CupertinoDialogAction( + key: cancelKeepKey, + onPressed: _sending ? null : _keep, + child: const Text(cancelKeepLabel), + ), + CupertinoDialogAction( + key: cancelConfirmKey, + isDestructiveAction: true, + onPressed: _sending ? null : _confirm, + child: const Text(cancelConfirmLabel), + ), + ], + ); + } + + Widget _body({required TextStyle errorStyle}) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Text(cancelDialogMessage), + if (_error case final error?) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(error, key: cancelErrorKey, style: errorStyle), + ), + ], + ); + } +} diff --git a/app/lib/features/runs/actions/cancel_eligibility.dart b/app/lib/features/runs/actions/cancel_eligibility.dart new file mode 100644 index 00000000..a8cbb620 --- /dev/null +++ b/app/lib/features/runs/actions/cancel_eligibility.dart @@ -0,0 +1,31 @@ +import '../../../core/api_gateway.dart'; + +/// Whether the operator may cancel [run], matching `canCancel` in +/// `web/src/actions.js` exactly: +/// +/// `(executing || (status == "waiting" && export_pending_sequence > 0)) && +/// !cancel_requested && !cleanup_unconfirmed` +/// +/// The status word alone is not enough: a stale `running` status without +/// `executing` is not cancellable, while a run waiting on a pending session +/// export is. +bool canCancelRun(JsonMap? run) { + if (run == null) return false; + final exportPending = _number(run['export_pending_sequence']); + return (run['executing'] == true || + (run['status'] == 'waiting' && exportPending > 0)) && + run['cancel_requested'] != true && + run['cleanup_unconfirmed'] != true; +} + +/// The run id used by the cancel request, or null for a malformed run. +num? cancelRunId(JsonMap run) { + final id = run['id']; + return id is num ? id : null; +} + +/// `Number(value) > 0`, tolerating numeric strings as the browser does. +double _number(dynamic value) { + if (value is num) return value.toDouble(); + return double.tryParse('${value ?? ''}'.trim()) ?? 0; +} diff --git a/app/lib/features/runs/actions/cancel_run_action.dart b/app/lib/features/runs/actions/cancel_run_action.dart new file mode 100644 index 00000000..e78564bd --- /dev/null +++ b/app/lib/features/runs/actions/cancel_run_action.dart @@ -0,0 +1,101 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../data/runs_repository.dart'; +import 'cancel_dialog.dart'; +import 'cancel_eligibility.dart'; +import 'cancel_wording.dart'; + +/// The run detail's deliberate cancel entry point. +/// +/// Renders one native button only while [run] is cancellable under the browser +/// client's rule. Opening the prompt or choosing [cancelKeepLabel] sends +/// nothing; only the confirm action asks the server to stop the run. A refusal +/// is shown verbatim in the kept-open prompt and the run is re-read, so +/// [onRunChanged] always receives server truth instead of a local guess. +class CancelRunAction extends StatefulWidget { + const CancelRunAction({ + super.key, + required this.run, + required this.gateway, + required this.onRunChanged, + }); + + final JsonMap run; + final ApiGateway gateway; + final ValueChanged onRunChanged; + + @override + State createState() => _CancelRunActionState(); +} + +class _CancelRunActionState extends State { + bool _dialogOpen = false; + + bool _usesCupertino(BuildContext context) { + final material = Localizations.of( + context, + MaterialLocalizations, + ); + return material == null; + } + + Future _open() async { + final id = cancelRunId(widget.run); + if (id == null || !canCancelRun(widget.run) || _dialogOpen) return; + _dialogOpen = true; + try { + await showCancelRunPrompt( + context: context, + runId: id, + cupertino: _usesCupertino(context), + onSubmit: () => _submit(id), + ); + } finally { + _dialogOpen = false; + if (mounted) setState(() {}); + } + } + + Future _submit(num id) async { + final repository = RunsRepository(widget.gateway); + try { + final run = await repository.cancelRun(id); + if (!mounted) return null; + widget.onRunChanged(run); + return null; + } catch (error) { + final refusal = describeCancelError(error); + if (!mounted) return refusal; + JsonMap? refreshed; + try { + refreshed = await repository.getRun(id); + } catch (_) { + // A failed re-read must not hide or replace the server's refusal. + } + if (!mounted) return refusal; + if (refreshed != null) widget.onRunChanged(refreshed); + return refusal; + } + } + + @override + Widget build(BuildContext context) { + if (cancelRunId(widget.run) == null || !canCancelRun(widget.run)) { + return const SizedBox.shrink(); + } + if (_usesCupertino(context)) { + return CupertinoButton.filled( + key: cancelActionKey, + onPressed: _open, + child: const Text(cancelActionLabel), + ); + } + return FilledButton( + key: cancelActionKey, + onPressed: _open, + child: const Text(cancelActionLabel), + ); + } +} diff --git a/app/lib/features/runs/actions/cancel_wording.dart b/app/lib/features/runs/actions/cancel_wording.dart new file mode 100644 index 00000000..b4812921 --- /dev/null +++ b/app/lib/features/runs/actions/cancel_wording.dart @@ -0,0 +1,23 @@ +import 'package:flutter/widgets.dart'; + +/// The browser client's cancel wording, kept verbatim. +const cancelActionLabel = 'Cancel run'; +const cancelDialogMessage = 'This asks the server to stop the active run.'; +const cancelConfirmLabel = 'Cancel run'; +const cancelKeepLabel = 'Keep'; + +/// Stable test/semantics keys shared by the action and its prompt. +const cancelActionKey = ValueKey('cancel-run-action'); +const cancelKeepKey = ValueKey('cancel-run-keep'); +const cancelConfirmKey = ValueKey('cancel-run-confirm'); +const cancelErrorKey = ValueKey('cancel-run-error'); + +/// The cancel dialog's title: `Cancel run {id}?`. +String cancelDialogTitle(num runId) => 'Cancel run $runId?'; + +/// The server's refusal, verbatim. Only a blank error gets a generic sentence +/// so the prompt never claims a cancellation that did not happen. +String describeCancelError(Object error) { + final message = '$error'.trim(); + return message.isEmpty ? 'The server did not cancel the run.' : message; +} diff --git a/app/notes/R2b.md b/app/notes/R2b.md new file mode 100644 index 00000000..0fda73b5 --- /dev/null +++ b/app/notes/R2b.md @@ -0,0 +1,96 @@ +# R2b — native run cancellation + +## What changed + +New `lib/features/runs/actions/cancel*` slice plus its tests. No existing source +file was edited. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/runs/actions/cancel_eligibility.dart` | 31 | Web-exact `canCancelRun`, run-id extraction, numeric export counter | +| `lib/features/runs/actions/cancel_wording.dart` | 23 | Web-verbatim words, dialog title, error text, test keys | +| `lib/features/runs/actions/cancel_dialog.dart` | 145 | Native Material/Cupertino confirmation and inline refusal | +| `lib/features/runs/actions/cancel_run_action.dart` | 101 | `CancelRunAction`, gating, send/refusal/resync orchestration | +| `test/features/runs/actions/cancel_test_support.dart` | 101 | Fake gateway, run fixtures, stateful host, app wrappers | +| `test/features/runs/actions/cancel_action_test.dart` | 192 | Eligibility and both-platform deliberate-confirm flows | +| `test/features/runs/actions/cancel_resilience_test.dart` | 176 | Refusal/resync, resync failure, double submit, disposal, 2x/narrow | + +`CancelRunAction` takes the run, the shared `ApiGateway` and an +`onRunChanged` callback. It renders one native `FilledButton` (`Cancel run`) on +Material and one `CupertinoButton.filled` on Cupertino, and nothing at all when +the browser rule says the run is not cancellable. Platform style follows the +enclosing app (`MaterialLocalizations` presence); no extra style parameter or +dependency was added. + +## Behaviour + +Eligibility is a direct port of `canCancel` in `../web/src/actions.js`: + +``` +(executing || (status == "waiting" && export_pending_sequence > 0)) + && !cancel_requested && !cleanup_unconfirmed +``` + +A run with a stale `running` status but `executing == false` is therefore not +cancellable, while a `waiting` run with a pending session export is. A run +without a numeric `id` is not offered because the request cannot be addressed +(the pure eligibility function still matches the web rule exactly). + +Opening the prompt sends nothing and `Keep` only closes it. The prompt uses the +web wording (`Cancel run {id}?`, `This asks the server to stop the active run.`, +`Cancel run`, `Keep`). Only the confirm action calls +`RunsRepository.cancelRun(id)`, which sends the exact envelope +`cancel_run {"run_id": id}`. + +Both the dialog and the action guard the in-flight state: a second confirm tap +or a `Keep` tap while sending is ignored, and the dialog's actions are disabled +until the reply arrives. A successful reply closes the prompt and passes the +server's returned `run_detail` to `onRunChanged`; no local status is invented. + +A refusal keeps the prompt open and shows the server's message verbatim. The +action then calls `RunsRepository.getRun(id)` and passes the refreshed run to +`onRunChanged`, so the owner sees server truth (for example the run finished +before cancellation). If the re-read also fails, the original refusal stays +visible and no synthetic run is delivered. Every asynchronous resume checks +`mounted` before `setState` or `onRunChanged`, so a late reply after disposal is +ignored. + +## Checks actually run + +``` +flutter pub get # dependencies resolved +dart format lib/features/runs/actions/cancel*.dart \ + test/features/runs/actions/cancel*.dart # clean +flutter analyze # No issues found! +flutter test test/features/runs/actions # 16 passed +flutter test # 45 passed +flutter build web # Built build/web (15.5s) +``` + +Focused coverage maps to the requested acceptance: + +- eligibility: executing, export-wait, waiting without export, stale `running` + without `executing`, already stopping, cleanup unconfirmed, finished/failed; + plus widget visibility for the same states; +- both platforms: native prompt opens, nothing is sent on open or `Keep`, exact + `cancel_run` envelope, callback receives the returned run, action disappears; +- refusal: cancellation error shown verbatim, `get_run` resync delivered to the + owner, and a failed resync leaves the refusal visible with no callback; +- double submit: two confirm taps produce one `cancel_run`, both actions disable; +- stale disposal: a reply after the tree is replaced causes no exception and no + callback; +- 320x480 at 2x text: both prompts open with no rendering exception. + +## Honest limits + +- **Not wired into a run-detail screen.** This branch has no run-detail screen + or controller; the manager owns integration. There is therefore no real + browser interaction or capture for this widget. `flutter build web` proves + compilation only, not rendered behavior, and no visible feature is claimed. +- **Mobile unverified.** No Android/iOS build, emulator, ADB or device was used. + Source uses only portable Flutter/Cupertino/Material widgets. +- No real server or run was mutated. Tests use a local fake gateway with no + socket. +- No controller/screen/main/domain/repository/pubspec, `web/`, Go server, + installer or deployment file was changed. Nothing was committed, pushed or + deployed. diff --git a/app/test/features/runs/actions/cancel_action_test.dart b/app/test/features/runs/actions/cancel_action_test.dart new file mode 100644 index 00000000..e50a6eea --- /dev/null +++ b/app/test/features/runs/actions/cancel_action_test.dart @@ -0,0 +1,192 @@ +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/features/runs/actions/cancel_eligibility.dart'; +import 'package:pipelines_app/features/runs/actions/cancel_wording.dart'; + +import 'cancel_test_support.dart'; + +void main() { + test('cancel eligibility matches the web canCancel exactly', () { + final cases = <(String, JsonMap, bool)>[ + ('executing run', executingRun(), true), + ( + 'waiting while a session export is pending', + executingRun(executing: false, status: 'waiting', exportPending: 2), + true, + ), + ( + 'waiting with no pending export', + executingRun(executing: false, status: 'waiting'), + false, + ), + ( + 'status says running but the run is not executing', + executingRun(executing: false), + false, + ), + ( + 'cancellation already requested', + executingRun(cancelRequested: true), + false, + ), + ('cleanup unconfirmed', executingRun(cleanupUnconfirmed: true), false), + ( + 'completed run', + executingRun(executing: false, status: 'succeeded'), + false, + ), + ('failed run', executingRun(executing: false, status: 'failed'), false), + ]; + for (final (label, run, expected) in cases) { + expect(canCancelRun(run), expected, reason: label); + } + expect(canCancelRun(null), isFalse); + }); + + testWidgets( + 'material cancel asks first, Keep sends nothing, then sends the envelope', + (tester) async { + final accepted = acceptedCancelRun(); + final gateway = FakeCancelGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await tester.pumpWidget( + cancelApp( + CancelHost( + gateway: gateway, + initial: executingRun(), + changed: changed, + ), + cupertino: false, + ), + ); + + expect(find.byKey(cancelActionKey), findsOneWidget); + expect(find.byType(FilledButton), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(cancelActionKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsOneWidget); + expect(find.text(cancelDialogTitle(7)), findsOneWidget); + expect(find.text(cancelDialogMessage), findsOneWidget); + expect(find.text(cancelKeepLabel), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(cancelKeepKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(cancelActionKey), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(cancelActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(cancelConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['cancel_run']); + expect(gateway.calls.single.fields, {'run_id': 7}); + expect(changed.single, equals(accepted)); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(cancelActionKey), findsNothing); + }, + ); + + testWidgets( + 'cupertino cancel uses a native prompt and sends only on confirm', + (tester) async { + final accepted = acceptedCancelRun(); + final gateway = FakeCancelGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await tester.pumpWidget( + cancelApp( + CancelHost( + gateway: gateway, + initial: executingRun(), + changed: changed, + ), + cupertino: true, + ), + ); + + expect(find.byKey(cancelActionKey), findsOneWidget); + expect(find.byType(CupertinoButton), findsOneWidget); + expect(find.byType(FilledButton), findsNothing); + + await tester.tap(find.byKey(cancelActionKey)); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.byType(AlertDialog), findsNothing); + expect(find.text(cancelDialogTitle(7)), findsOneWidget); + expect(find.text(cancelDialogMessage), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(cancelKeepKey)); + await tester.pumpAndSettle(); + expect(gateway.calls, isEmpty); + expect(find.byType(CupertinoAlertDialog), findsNothing); + + await tester.tap(find.byKey(cancelActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(cancelConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['cancel_run']); + expect(gateway.calls.single.fields, {'run_id': 7}); + expect(changed.single, equals(accepted)); + expect(find.byType(CupertinoAlertDialog), findsNothing); + expect(find.byKey(cancelActionKey), findsNothing); + }, + ); + + testWidgets('the action is absent for runs the web does not cancel', ( + tester, + ) async { + final gateway = FakeCancelGateway( + (type, fields) async => {'run_detail': executingRun()}, + ); + final changed = []; + final cases = <(String, JsonMap, bool)>[ + ('executing', executingRun(), true), + ( + 'export wait', + executingRun(executing: false, status: 'waiting', exportPending: 1), + true, + ), + ( + 'no export wait', + executingRun(executing: false, status: 'waiting'), + false, + ), + ('stale running status', executingRun(executing: false), false), + ('already stopping', executingRun(cancelRequested: true), false), + ('cleanup unconfirmed', executingRun(cleanupUnconfirmed: true), false), + ('finished', executingRun(executing: false, status: 'succeeded'), false), + ]; + for (final (label, run, visible) in cases) { + await tester.pumpWidget( + cancelApp( + CancelHost( + key: ValueKey(label), + gateway: gateway, + initial: run, + changed: changed, + ), + cupertino: false, + ), + ); + expect( + find.byKey(cancelActionKey), + visible ? findsOneWidget : findsNothing, + reason: label, + ); + } + expect(gateway.calls, isEmpty); + expect(changed, isEmpty); + }); +} diff --git a/app/test/features/runs/actions/cancel_resilience_test.dart b/app/test/features/runs/actions/cancel_resilience_test.dart new file mode 100644 index 00000000..e3fa15ee --- /dev/null +++ b/app/test/features/runs/actions/cancel_resilience_test.dart @@ -0,0 +1,176 @@ +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/cancel_wording.dart'; + +import 'cancel_test_support.dart'; + +Future _pump( + WidgetTester tester, + FakeCancelGateway gateway, + List changed, { + bool cupertino = false, + double textScale = 1, + JsonMap? run, +}) async { + await tester.pumpWidget( + cancelApp( + CancelHost( + gateway: gateway, + initial: run ?? executingRun(), + changed: changed, + ), + cupertino: cupertino, + textScale: textScale, + ), + ); +} + +Future _openAndConfirm(WidgetTester tester) async { + await tester.tap(find.byKey(cancelActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(cancelConfirmKey)); +} + +void main() { + testWidgets('a refusal stays visible and delivers the resynced run', ( + tester, + ) async { + const refusal = 'run 7 already completed; nothing to cancel'; + final refreshed = executingRun(executing: false, status: 'succeeded'); + final gateway = FakeCancelGateway((type, fields) async { + if (type == 'cancel_run') throw const ProtocolError(refusal); + expect(type, 'get_run'); + return {'run_detail': refreshed}; + }); + final changed = []; + await _pump(tester, gateway, changed); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['cancel_run', 'get_run']); + expect(gateway.calls.first.fields, {'run_id': 7}); + expect(gateway.calls.last.fields, {'run_id': 7}); + expect(find.text(refusal), findsOneWidget); + expect(find.byKey(cancelErrorKey), findsOneWidget); + expect(find.byType(AlertDialog), findsOneWidget); + expect(changed.single, equals(refreshed)); + expect(find.byKey(cancelActionKey), findsNothing); + }); + + testWidgets('a failed resync never hides the refusal or invents a run', ( + tester, + ) async { + const refusal = 'server refused to stop the run'; + final gateway = FakeCancelGateway((type, fields) async { + if (type == 'cancel_run') throw const ProtocolError(refusal); + throw const NotConnectedError(); + }); + final changed = []; + await _pump(tester, gateway, changed); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['cancel_run', 'get_run']); + expect(find.text(refusal), findsOneWidget); + expect(find.byType(AlertDialog), findsOneWidget); + expect(changed, isEmpty); + expect(find.byKey(cancelActionKey), findsOneWidget); + }); + + testWidgets( + 'confirm cannot submit twice while the cancellation is in flight', + (tester) async { + final reply = Completer(); + final gateway = FakeCancelGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + + await tester.tap(find.byKey(cancelActionKey)); + await tester.pumpAndSettle(); + final confirm = find.byKey(cancelConfirmKey); + await tester.tap(confirm); + await tester.tap(confirm); + await tester.pump(); + + expect( + gateway.calls.where((call) => call.type == 'cancel_run'), + hasLength(1), + ); + expect( + tester.widget(find.byKey(cancelConfirmKey)).onPressed, + isNull, + ); + expect( + tester.widget(find.byKey(cancelKeepKey)).onPressed, + isNull, + ); + expect(find.byType(AlertDialog), findsOneWidget); + + reply.complete({'run_detail': acceptedCancelRun()}); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(changed, hasLength(1)); + }, + ); + + testWidgets('a late reply after disposal is ignored safely', (tester) async { + final reply = Completer(); + final gateway = FakeCancelGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + + await _openAndConfirm(tester); + await tester.pump(); + expect(gateway.calls, hasLength(1)); + + await tester.pumpWidget(const SizedBox()); + reply.complete({'run_detail': acceptedCancelRun()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + + testWidgets('both prompts fit 2x text at a narrow width', (tester) async { + tester.view.physicalSize = const Size(320, 480); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + for (final cupertino in [false, true]) { + final gateway = FakeCancelGateway( + (type, fields) async => {'run_detail': acceptedCancelRun()}, + ); + await _pump( + tester, + gateway, + [], + cupertino: cupertino, + textScale: 2, + ); + await tester.tap(find.byKey(cancelActionKey)); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino'); + expect(find.text(cancelDialogTitle(7)), findsOneWidget); + expect(find.text(cancelDialogMessage), findsOneWidget); + expect( + cupertino + ? find.byType(CupertinoAlertDialog) + : find.byType(AlertDialog), + findsOneWidget, + ); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(cancelKeepKey)); + await tester.pumpAndSettle(); + } + }); +} diff --git a/app/test/features/runs/actions/cancel_test_support.dart b/app/test/features/runs/actions/cancel_test_support.dart new file mode 100644 index 00000000..7acee8d9 --- /dev/null +++ b/app/test/features/runs/actions/cancel_test_support.dart @@ -0,0 +1,101 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/actions/cancel_run_action.dart'; + +typedef CancelHandler = Future Function(String type, JsonMap fields); + +/// A fake gateway that records every request and never owns a socket. +class FakeCancelGateway implements ApiGateway { + FakeCancelGateway(this.handler); + + final CancelHandler handler; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) { + final copy = Map.from(fields); + calls.add((type: type, fields: copy)); + return handler(type, copy); + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap executingRun({ + num id = 7, + bool executing = true, + String status = 'running', + int exportPending = 0, + bool cancelRequested = false, + bool cleanupUnconfirmed = false, +}) => { + 'id': id, + 'title': 'Nightly build', + 'status': status, + 'executing': executing, + 'export_pending_sequence': exportPending, + 'cancel_requested': cancelRequested, + 'cleanup_unconfirmed': cleanupUnconfirmed, +}; + +JsonMap acceptedCancelRun() => + executingRun(executing: false, status: 'canceled', cancelRequested: true); + +/// Owns the run like a run-detail screen would, so the callback's returned +/// server detail is what the action renders next. +class CancelHost extends StatefulWidget { + const CancelHost({ + super.key, + required this.gateway, + required this.initial, + required this.changed, + }); + + final FakeCancelGateway gateway; + final JsonMap initial; + final List changed; + + @override + State createState() => _CancelHostState(); +} + +class _CancelHostState extends State { + late JsonMap _run = widget.initial; + + @override + Widget build(BuildContext context) { + return CancelRunAction( + run: _run, + gateway: widget.gateway, + onRunChanged: (run) { + widget.changed.add(run); + setState(() => _run = run); + }, + ); + } +} + +Widget cancelApp( + Widget child, { + required bool cupertino, + double textScale = 1, +}) { + Widget media(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + if (cupertino) { + return CupertinoApp( + builder: media, + home: CupertinoPageScaffold(child: Center(child: child)), + ); + } + return MaterialApp( + builder: media, + home: Scaffold(body: Center(child: child)), + ); +} From 743da9bb341aedaac2c61b958494ed158ab661e0 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 14:44:14 +0100 Subject: [PATCH 34/84] docs(app): hold cancellation for responsive refusal-flow checks --- app/WORK.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/WORK.md b/app/WORK.md index dc4c51d9..1e2cdefa 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -18,7 +18,7 @@ All work under app/. Existing applications remain running and unchanged. | R1 | Run list/detail/live timeline | controller43 + list48 + detail46 accepted | manager merged all three on flutter/r1-native; reran 25 combined tests + analyze, pass | candidate integrated, held for I1 | I1 run50 wiring + browser verification | | D1 | Recorded changes/diff viewer | run 39 / flutter/d1-diff-viewer | running (Flash) | pending | pending | | R2a | Human-decision native confirm | run47 / commit42b21b8 | manager inspected source + reran 7 exact-confirm/refusal/native tests + analyze, pass | main3e6f950, ancestry verified | reusable component only; wiring/browser pending | -| R2b | Native cancel-run confirmation | run51 / flutter/r2-cancel | running (Flash) | pending | pending | +| R2b | Native cancel-run confirmation | run51 → focused52 / flutter/r2-cancel | 51 passed16 action tests in pipeline; manager confirmed prompt locks on refusal/resync,52 correcting both action flows with delayed-response regressions | held | pending | | X1 | Native search and result targets | run 49 / flutter/x1-search | running (Flash) | pending | pending | | I1 | App-owned socket/session + live Runs shell registration | run 50 / flutter/r1-native | running (Flash); real browser captures required | pending | pending | From c58395c559599273e7412480c381aaf3efa45db1 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 14:46:11 +0100 Subject: [PATCH 35/84] docs(app): identify export size gate blocking six computed feature runs --- app/WORK.md | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/app/WORK.md b/app/WORK.md index 1e2cdefa..4dc03fd0 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -12,15 +12,15 @@ All work under app/. Existing applications remain running and unchanged. | F3 | Run models, live event fold, actions | run 32 + 1515ebe | 11 regressions/analyze pass; 5 source files 105–226 lines | main 37d0823, ancestry verified | — | | F4 | Chat models, history/live fold, request facade | run 33 / flutter/f4-chat | pipeline passed; wire omissions carried into C1 | pending C1 adapter fixes | — | | F5 | Isolated authenticated web preview tooling | run 30 + ae352bb | 6 proxy fixtures incl auth/bytes/origin/idle sockets pass | main 160ab45, ancestry verified | http://127.0.0.1:8096/ | -| P1 | Pipeline list/detail/source/version browser | run 34 / flutter/p1-pipelines | running (DeepSeek V4.1 Flash) | pending | pending | -| C1 | Chat session browser and management | 35 → resume 36 → focused C1b run 42 / flutter/f4-chat | catalog/grouping fixes + inspected browser captures retained; pipeline splitting 406-line screen and adding Cupertino/tests (Flash) | held; not parity-complete | pending | -| N1 | Connection settings/preferences | run 37 / flutter/n1-settings | running (Flash) | pending | pending | +| P1 | Pipeline list/detail/source/version browser | run34 / flutter/p1-pipelines | Code computed success; WAITING truncated2MiB export | held, review not reached | pending | +| C1 | Chat session browser and management | 35 →36 →42 / flutter/f4-chat | Code42 computed success; WAITING truncated2MiB export | held, final review not reached | pending | +| N1 | Connection settings/preferences | run37 / flutter/n1-settings | Code computed success; WAITING truncated2MiB export | held, review not reached | pending | | R1 | Run list/detail/live timeline | controller43 + list48 + detail46 accepted | manager merged all three on flutter/r1-native; reran 25 combined tests + analyze, pass | candidate integrated, held for I1 | I1 run50 wiring + browser verification | -| D1 | Recorded changes/diff viewer | run 39 / flutter/d1-diff-viewer | running (Flash) | pending | pending | +| D1 | Recorded changes/diff viewer | run39 / flutter/d1-diff-viewer | Code computed success; WAITING truncated2MiB export | held, review not reached | pending | | R2a | Human-decision native confirm | run47 / commit42b21b8 | manager inspected source + reran 7 exact-confirm/refusal/native tests + analyze, pass | main3e6f950, ancestry verified | reusable component only; wiring/browser pending | | R2b | Native cancel-run confirmation | run51 → focused52 / flutter/r2-cancel | 51 passed16 action tests in pipeline; manager confirmed prompt locks on refusal/resync,52 correcting both action flows with delayed-response regressions | held | pending | -| X1 | Native search and result targets | run 49 / flutter/x1-search | running (Flash) | pending | pending | -| I1 | App-owned socket/session + live Runs shell registration | run 50 / flutter/r1-native | running (Flash); real browser captures required | pending | pending | +| X1 | Native search and result targets | run49 / flutter/x1-search | Code computed success; WAITING truncated2MiB export | held, review not reached | pending | +| I1 | App-owned socket/session + live Runs shell registration | run50 / flutter/r1-native | Code computed success; WAITING truncated2MiB export | held, review not reached | not deployed | ## Next ready work - P1 pipelines list/detail/source/version; P2 graph and stage/visit selection. @@ -53,6 +53,18 @@ override, server edit or shell-write bypass was used by the manager. Allowed pipeline models: Luna or DeepSeek V4.1 Flash; current runs use Luna. ## Latest integration check +### Current delivery blocker — session export cap +User asked about failed runs; explicit status inspection found runs34/37/39/42/ +49/50 are waiting, not failed: each Code visit1 computed success and is quiescent, +but export is partial/truncated at exactly2097152 bytes. Exact recorded native +session identities remain retained. `pipelines repair-session-export 34 1` was +attempted once; it returned `session export repair incomplete: partial` at the +same cap. No full stage reruns, evidence replacement, cancellation or gate bypass +was performed. Remaining waits stay active for eventual export-only recovery. +Server export-cap change is outside the user's explicit app-only authorization; +approval is required before changing server code/configuration/deployment. Do +not burn repeated repair attempts against this deterministic size limit. + At 160ab45: 29 Flutter tests and 6 Node proxy fixtures pass; flutter analyze, flutter build web and git diff --check pass. Real Chrome phone/desktop captures are in the approved OpenCode temporary directory, named f2-shell-*.png. The From 54493704c11085b0bbf0a3763ca1950ed3a4b5d6 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 14:47:59 +0100 Subject: [PATCH 36/84] fix(app): show run action refusals before resyncing --- .../features/runs/actions/action_refusal.dart | 18 +++ .../features/runs/actions/cancel_dialog.dart | 32 ++++- .../runs/actions/cancel_run_action.dart | 48 +++++--- .../runs/actions/decision_action.dart | 73 +++++++++--- .../runs/actions/decision_dialog.dart | 34 ++++-- app/notes/R2b-refusal.md | 92 +++++++++++++++ .../runs/actions/cancel_resilience_test.dart | 95 +++++++++++++++ .../runs/actions/decision_action_test.dart | 28 +++++ .../actions/decision_resilience_test.dart | 111 ++++++++++++++++++ 9 files changed, 484 insertions(+), 47 deletions(-) create mode 100644 app/lib/features/runs/actions/action_refusal.dart create mode 100644 app/notes/R2b-refusal.md diff --git a/app/lib/features/runs/actions/action_refusal.dart b/app/lib/features/runs/actions/action_refusal.dart new file mode 100644 index 00000000..87e03995 --- /dev/null +++ b/app/lib/features/runs/actions/action_refusal.dart @@ -0,0 +1,18 @@ +/// A refused operator action and, when one was started, the bounded re-read of +/// server truth that follows it. +/// +/// The prompt shows [message] and allows dismissal immediately; it must never +/// wait for [stillPossible]. That future is only observed so a retry can be +/// ruled out once server truth arrives: `true` means the re-read found the run +/// still allows the action, `false` means it plainly does not, and `null` means +/// the re-read failed or was overtaken, leaving a deliberate retry possible. +class ActionRefusal { + const ActionRefusal(this.message, {this.stillPossible}); + + final String message; + final Future? stillPossible; +} + +/// Local guards, distinct from a server refusal; they never claim success. +const actionOptionRequired = 'Choose an option before continuing.'; +const actionAlreadySending = 'That action is still being sent.'; diff --git a/app/lib/features/runs/actions/cancel_dialog.dart b/app/lib/features/runs/actions/cancel_dialog.dart index 96f4c204..1654f442 100644 --- a/app/lib/features/runs/actions/cancel_dialog.dart +++ b/app/lib/features/runs/actions/cancel_dialog.dart @@ -1,11 +1,13 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'action_refusal.dart'; import 'cancel_wording.dart'; /// Sends the confirmed cancellation. Returns null once the server has accepted -/// it, or the server's refusal verbatim; the prompt then stays open. -typedef CancelSubmit = Future Function(); +/// it, or an [ActionRefusal] carrying the server's words verbatim; the prompt +/// then stays open with dismissal available immediately. +typedef CancelSubmit = Future Function(); /// Opens the native cancel confirmation for [runId]. /// @@ -53,6 +55,8 @@ class _CancelPrompt extends StatefulWidget { class _CancelPromptState extends State<_CancelPrompt> { bool _sending = false; + bool _checking = false; + bool _blocked = false; String? _error; void _keep() { @@ -60,7 +64,7 @@ class _CancelPromptState extends State<_CancelPrompt> { } Future _confirm() async { - if (_sending) return; + if (_sending || _checking || _blocked) return; setState(() { _sending = true; _error = null; @@ -71,9 +75,23 @@ class _CancelPromptState extends State<_CancelPrompt> { Navigator.of(context).pop(); return; } + final check = refusal.stillPossible; setState(() { _sending = false; - _error = refusal; + _error = refusal.message; + _checking = check != null; + }); + if (check == null) return; + bool? stillPossible; + try { + stillPossible = await check; + } catch (_) { + // The action reports re-read failures as null; never fabricate one here. + } + if (!mounted) return; + setState(() { + _checking = false; + _blocked = stillPossible == false; }); } @@ -83,6 +101,8 @@ class _CancelPromptState extends State<_CancelPrompt> { return PopScope(canPop: !_sending, child: dialog); } + bool get _confirmDisabled => _sending || _checking || _blocked; + Widget _material(BuildContext context) { final theme = Theme.of(context); return AlertDialog( @@ -97,7 +117,7 @@ class _CancelPromptState extends State<_CancelPrompt> { ), FilledButton( key: cancelConfirmKey, - onPressed: _sending ? null : _confirm, + onPressed: _confirmDisabled ? null : _confirm, child: const Text(cancelConfirmLabel), ), ], @@ -121,7 +141,7 @@ class _CancelPromptState extends State<_CancelPrompt> { CupertinoDialogAction( key: cancelConfirmKey, isDestructiveAction: true, - onPressed: _sending ? null : _confirm, + onPressed: _confirmDisabled ? null : _confirm, child: const Text(cancelConfirmLabel), ), ], diff --git a/app/lib/features/runs/actions/cancel_run_action.dart b/app/lib/features/runs/actions/cancel_run_action.dart index e78564bd..19bdf181 100644 --- a/app/lib/features/runs/actions/cancel_run_action.dart +++ b/app/lib/features/runs/actions/cancel_run_action.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart'; import '../../../core/api_gateway.dart'; import '../data/runs_repository.dart'; +import 'action_refusal.dart'; import 'cancel_dialog.dart'; import 'cancel_eligibility.dart'; import 'cancel_wording.dart'; @@ -12,8 +13,9 @@ import 'cancel_wording.dart'; /// Renders one native button only while [run] is cancellable under the browser /// client's rule. Opening the prompt or choosing [cancelKeepLabel] sends /// nothing; only the confirm action asks the server to stop the run. A refusal -/// is shown verbatim in the kept-open prompt and the run is re-read, so -/// [onRunChanged] always receives server truth instead of a local guess. +/// is returned to the kept-open prompt immediately and the run is re-read +/// separately, so [onRunChanged] still receives server truth without locking +/// the prompt while that read is pending. class CancelRunAction extends StatefulWidget { const CancelRunAction({ super.key, @@ -32,6 +34,7 @@ class CancelRunAction extends StatefulWidget { class _CancelRunActionState extends State { bool _dialogOpen = false; + Future? _resync; bool _usesCupertino(BuildContext context) { final material = Localizations.of( @@ -58,25 +61,40 @@ class _CancelRunActionState extends State { } } - Future _submit(num id) async { + Future _submit(num id) async { final repository = RunsRepository(widget.gateway); try { final run = await repository.cancelRun(id); if (!mounted) return null; - widget.onRunChanged(run); + if (_owns(id)) widget.onRunChanged(run); return null; } catch (error) { - final refusal = describeCancelError(error); - if (!mounted) return refusal; - JsonMap? refreshed; - try { - refreshed = await repository.getRun(id); - } catch (_) { - // A failed re-read must not hide or replace the server's refusal. - } - if (!mounted) return refusal; - if (refreshed != null) widget.onRunChanged(refreshed); - return refusal; + return ActionRefusal( + describeCancelError(error), + stillPossible: _resyncRun(id), + ); + } + } + + bool _owns(num id) => mounted && cancelRunId(widget.run) == id; + + /// One bounded re-read per refusal. A refusal that arrives while a read is + /// already in flight observes that same read instead of starting another. + Future _resyncRun(num id) { + return _resync ??= _readRun(id); + } + + Future _readRun(num id) async { + try { + final run = await RunsRepository(widget.gateway).getRun(id); + if (!_owns(id)) return null; + widget.onRunChanged(run); + return canCancelRun(run); + } catch (_) { + // Unknown server truth: keep the refusal and leave a deliberate retry. + return null; + } finally { + _resync = null; } } diff --git a/app/lib/features/runs/actions/decision_action.dart b/app/lib/features/runs/actions/decision_action.dart index 5405accf..246c66fb 100644 --- a/app/lib/features/runs/actions/decision_action.dart +++ b/app/lib/features/runs/actions/decision_action.dart @@ -5,6 +5,7 @@ import '../../../core/api_gateway.dart'; import '../data/runs_repository.dart'; import '../domain/run_decisions.dart'; import '../domain/run_models.dart'; +import 'action_refusal.dart'; import 'decision_dialog.dart'; import 'decision_wording.dart'; @@ -13,8 +14,9 @@ import 'decision_wording.dart'; /// Renders one native button only while [run] is genuinely waiting on a person. /// Nothing is sent until the operator opens the prompt, chooses an option and /// presses Confirm; cancel, selection and optional feedback stay local. A -/// server refusal is shown verbatim in the prompt, the draft is preserved and -/// the run is re-read so [onRunChanged] always receives server truth. +/// server refusal is shown verbatim in the prompt immediately, the draft is +/// preserved and the run is re-read separately so [onRunChanged] still receives +/// server truth without locking the prompt while that read is pending. class HumanDecisionAction extends StatefulWidget { const HumanDecisionAction({ super.key, @@ -39,6 +41,7 @@ class _HumanDecisionActionState extends State { PendingDecision? _pending; bool _dialogOpen = false; bool _sending = false; + Future? _resync; @override void initState() { @@ -78,9 +81,13 @@ class _HumanDecisionActionState extends State { } } - Future _submit(PendingDecision decision, DecisionDraft draft) async { + Future _submit( + PendingDecision decision, + DecisionDraft draft, + ) async { final option = draft.selected?.trim() ?? ''; - if (option.isEmpty || _sending) return null; + if (option.isEmpty) return const ActionRefusal(actionOptionRequired); + if (_sending) return const ActionRefusal(actionAlreadySending); _sending = true; final repository = RunsRepository(widget.gateway); try { @@ -93,29 +100,57 @@ class _HumanDecisionActionState extends State { feedback: draft.feedback, ); } catch (error) { - final refusal = _describe(error); - if (!mounted) return refusal; - JsonMap? refreshed; - try { - refreshed = await repository.getRun(decision.runId); - } catch (_) { - // A failed re-read must not hide or replace the server's refusal. - } - if (refreshed != null && mounted) { - setState(() => _pending = pendingDecision(refreshed)); - widget.onRunChanged(refreshed); - } - return refusal; + return ActionRefusal( + _describe(error), + stillPossible: _resyncRun(decision), + ); } if (!mounted) return null; - setState(() => _pending = pendingDecision(run)); - widget.onRunChanged(run); + if (_owns(decision.runId)) { + setState(() => _pending = pendingDecision(run)); + widget.onRunChanged(run); + } return null; } finally { _sending = false; } } + bool _owns(num id) => mounted && widget.run['id'] == id; + + /// One bounded re-read per refusal. A refusal that arrives while a read is + /// already in flight observes that same read instead of starting another. + Future _resyncRun(PendingDecision decision) { + return _resync ??= _readRun(decision); + } + + Future _readRun(PendingDecision expected) async { + try { + final run = await RunsRepository(widget.gateway).getRun(expected.runId); + if (!_owns(expected.runId)) return null; + final next = pendingDecision(run); + setState(() => _pending = next); + widget.onRunChanged(run); + return _stillDecidable(next, expected); + } catch (_) { + // Unknown server truth: keep the refusal and leave a deliberate retry. + return null; + } finally { + _resync = null; + } + } + + /// Whether the refreshed run offers the same decision the prompt is showing. + bool _stillDecidable(PendingDecision? next, PendingDecision expected) { + if (next == null || + next.runId != expected.runId || + next.stageKey != expected.stageKey) { + return false; + } + final keys = next.options.map((option) => option.key).toSet(); + return expected.options.every((option) => keys.contains(option.key)); + } + @override Widget build(BuildContext context) { final decision = _pending; diff --git a/app/lib/features/runs/actions/decision_dialog.dart b/app/lib/features/runs/actions/decision_dialog.dart index 9649ea16..81aa717c 100644 --- a/app/lib/features/runs/actions/decision_dialog.dart +++ b/app/lib/features/runs/actions/decision_dialog.dart @@ -3,11 +3,13 @@ import 'package:flutter/material.dart'; import '../domain/run_decisions.dart'; import '../domain/run_models.dart'; +import 'action_refusal.dart'; import 'decision_wording.dart'; -/// Sends the draft to the server. Returns null on success, or the server's -/// refusal message verbatim; the prompt stays open with the draft intact. -typedef DecisionSubmit = Future Function(DecisionDraft draft); +/// Sends the draft to the server. Returns null on success, or an +/// [ActionRefusal] with the server's words verbatim; the prompt stays open +/// with the draft intact and dismissal available immediately. +typedef DecisionSubmit = Future Function(DecisionDraft draft); /// Opens the native decision prompt for [decision]. Future showHumanDecisionPrompt({ @@ -54,6 +56,8 @@ class _DecisionPromptState extends State<_DecisionPrompt> { DecisionDraft _draft = const DecisionDraft(); late final TextEditingController _feedback = TextEditingController(); bool _sending = false; + bool _checking = false; + bool _blocked = false; String? _error; @override @@ -74,7 +78,7 @@ class _DecisionPromptState extends State<_DecisionPrompt> { } Future _confirm() async { - if (_sending || !_draft.canSubmit) return; + if (_sending || _checking || _blocked || !_draft.canSubmit) return; setState(() { _sending = true; _error = null; @@ -85,9 +89,23 @@ class _DecisionPromptState extends State<_DecisionPrompt> { Navigator.of(context).pop(); return; } + final check = refusal.stillPossible; setState(() { _sending = false; - _error = refusal; + _error = refusal.message; + _checking = check != null; + }); + if (check == null) return; + bool? stillPossible; + try { + stillPossible = await check; + } catch (_) { + // The action reports re-read failures as null; never fabricate one here. + } + if (!mounted) return; + setState(() { + _checking = false; + _blocked = stillPossible == false; }); } @@ -97,6 +115,8 @@ class _DecisionPromptState extends State<_DecisionPrompt> { return PopScope(canPop: !_sending, child: dialog); } + bool get _confirmDisabled => _sending || _checking || _blocked; + Widget _material(BuildContext context) { final theme = Theme.of(context); return AlertDialog( @@ -138,7 +158,7 @@ class _DecisionPromptState extends State<_DecisionPrompt> { child: const Text(decisionCancelLabel), ), FilledButton( - onPressed: _sending || !_draft.canSubmit ? null : _confirm, + onPressed: _confirmDisabled || !_draft.canSubmit ? null : _confirm, child: Text(_sending ? decisionSendingLabel : decisionConfirmLabel), ), ], @@ -203,7 +223,7 @@ class _DecisionPromptState extends State<_DecisionPrompt> { ), CupertinoDialogAction( isDefaultAction: true, - onPressed: _sending || !_draft.canSubmit ? null : _confirm, + onPressed: _confirmDisabled || !_draft.canSubmit ? null : _confirm, child: Text(_sending ? decisionSendingLabel : decisionConfirmLabel), ), ], diff --git a/app/notes/R2b-refusal.md b/app/notes/R2b-refusal.md new file mode 100644 index 00000000..65851110 --- /dev/null +++ b/app/notes/R2b-refusal.md @@ -0,0 +1,92 @@ +# R2b-refusal — immediate refusals, separate resync + +Focused correction on the retained `faa5866` cancellation candidate. The action +source is now shared by both deliberate run actions (cancel and human decision); +no wiring, screen, controller, repository, socket, pubspec, web, server or +device file was touched. + +## What changed + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/runs/actions/action_refusal.dart` | 18 | Refusal message plus optional bounded re-read outcome; local guard words | +| `lib/features/runs/actions/cancel_run_action.dart` | 119 | Immediate refusal return, single-flight resync, ownership checks | +| `lib/features/runs/actions/cancel_dialog.dart` | 165 | Shows the refusal and re-enables Keep before the resync settles | +| `lib/features/runs/actions/decision_action.dart` | 176 | Same async flow for `decide_run`, draft preserved | +| `lib/features/runs/actions/decision_dialog.dart` | 268 | Shows refusal, keeps draft, disables retry only on server truth | +| `test/features/runs/actions/cancel_resilience_test.dart` | 271 | Three new fake-gateway regressions | +| `test/features/runs/actions/decision_resilience_test.dart` | 351 | Three new fake-gateway regressions | +| `test/features/runs/actions/decision_action_test.dart` | 265 | Cancel/no-request coverage | + +## Async flow + +A refused mutation no longer awaits `get_run` before returning: + +1. `_submit` catches the mutation error and computes the refusal text. +2. It returns `ActionRefusal(message, stillPossible: _resyncRun(id))` at once. + `_resyncRun` starts one `get_run` for that refusal; a concurrent refusal + observes the same future instead of issuing another request. +3. The prompt clears its sending state, shows the server's words and makes + Keep/Cancel available in the same frame. Back is enabled too (`PopScope` + only gates the in-flight mutation). Confirm stays disabled while the check + is pending and after it proves the action impossible, so a doomed mutation + cannot be resubmitted from the open prompt. +4. The resync runs detached but bounded: exactly one `get_run`, no retries or + polling. Every exception becomes `null` (unknown truth), which leaves the + refusal visible and a deliberate retry available. +5. Before delivering a refreshed run, the action checks `mounted` and that the + run id it owns is still the request's id. A late read after disposal or + navigation touches nothing and raises nothing. + +On success the mutation reply is still used directly, the prompt closes, and no +duplicate `get_run` is issued. The dialog and action keep the existing +in-flight double-submit guard. The human-decision prompt keeps the selected +option and feedback controller untouched while a refusal or resync is pending; +its retry is disabled only when the refreshed run no longer offers the same +decision (same stage and option keys). + +No repository, protocol or socket code changed. The web's `cancel_run` plus +silent refresh remains the reference; this version keeps the diagnostic in the +open prompt rather than moving it to the web's separate Action-failed dialog. + +## Regression coverage added + +Fake gateway, no socket or real server: + +- immediate `cancel_run` refusal plus a deliberately unresolved `get_run`: the + exact message is visible, Keep is enabled, confirm is disabled and no run + callback has fired **before** the resync completes; Keep closes the prompt; + a late resync still delivers server truth safely; +- late cancel resync after the whole action is disposed: no exception, no + callback; +- resync proving the run is no longer cancellable: refusal stays visible, + confirm cannot submit again (an attempted tap adds no request), Keep + dismisses and the ineligible run is delivered; +- immediate `decide_run` refusal plus an unresolved `get_run`: exact message, + selection and feedback retained, Cancel enabled, no callback yet; after the + resync proves the decision gone, the message remains and confirm is disabled; +- decision resync that fails: message and draft remain, Confirm is re-enabled + because server truth is unknown; +- late decision resync after disposal: no exception, no callback; +- Cancel on an untouched decision draft sends nothing and keeps the action + available. + +## Checks actually run + +``` +dart format lib/features/runs/actions test/features/runs/actions # clean +flutter analyze # No issues found! +flutter test test/features/runs/actions # 23 passed +flutter test # 52 passed +flutter build web # Built build/web +``` + +## Honest limits + +- Still **not wired into a run-detail screen** on this branch; there is no + browser interaction or rendered capture for this widget. `flutter build web` + proves compilation only. +- Mobile remains unverified: no Android/iOS build, emulator, ADB or device. +- No real server or run was mutated; all evidence uses local fakes. +- No commit, push, deployment or canonical-URL change is claimed here beyond + the candidate commit checked by the manager. diff --git a/app/test/features/runs/actions/cancel_resilience_test.dart b/app/test/features/runs/actions/cancel_resilience_test.dart index e3fa15ee..675c58b2 100644 --- a/app/test/features/runs/actions/cancel_resilience_test.dart +++ b/app/test/features/runs/actions/cancel_resilience_test.dart @@ -84,6 +84,101 @@ void main() { expect(find.byKey(cancelActionKey), findsOneWidget); }); + testWidgets('a refusal and Keep do not wait for the resync', (tester) async { + const refusal = 'run 7 is already stopping'; + final resync = Completer(); + final gateway = FakeCancelGateway((type, fields) { + if (type == 'cancel_run') throw const ProtocolError(refusal); + return resync.future; + }); + final changed = []; + await _pump(tester, gateway, changed); + + await _openAndConfirm(tester); + await tester.pump(); + + expect(find.text(refusal), findsOneWidget); + expect( + tester.widget(find.byKey(cancelKeepKey)).onPressed, + isNotNull, + ); + expect( + tester.widget(find.byKey(cancelConfirmKey)).onPressed, + isNull, + ); + expect(changed, isEmpty); + + await tester.tap(find.byKey(cancelKeepKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + + resync.complete({ + 'run_detail': executingRun(executing: false, status: 'succeeded'), + }); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed.single['status'], 'succeeded'); + }); + + testWidgets('a late resync after disposal is ignored safely', (tester) async { + final resync = Completer(); + final gateway = FakeCancelGateway((type, fields) { + if (type == 'cancel_run') throw const ProtocolError('already stopped'); + return resync.future; + }); + final changed = []; + await _pump(tester, gateway, changed); + + await _openAndConfirm(tester); + await tester.pump(); + expect(gateway.calls.map((call) => call.type), ['cancel_run', 'get_run']); + + await tester.pumpWidget(const SizedBox()); + resync.complete({'run_detail': acceptedCancelRun()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + + testWidgets('an ineligible resync disables confirm but keeps the refusal', ( + tester, + ) async { + const refusal = 'run 7 already completed; nothing to cancel'; + final finished = executingRun(executing: false, status: 'succeeded'); + final gateway = FakeCancelGateway((type, fields) async { + if (type == 'cancel_run') throw const ProtocolError(refusal); + return {'run_detail': finished}; + }); + final changed = []; + await _pump(tester, gateway, changed); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['cancel_run', 'get_run']); + expect(find.text(refusal), findsOneWidget); + expect( + tester.widget(find.byKey(cancelConfirmKey)).onPressed, + isNull, + ); + expect( + tester.widget(find.byKey(cancelKeepKey)).onPressed, + isNotNull, + ); + + await tester.tap(find.byKey(cancelConfirmKey)); + await tester.pump(); + expect(gateway.calls.map((call) => call.type), ['cancel_run', 'get_run']); + + await tester.tap(find.byKey(cancelKeepKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(cancelActionKey), findsNothing); + expect(changed.single, equals(finished)); + }); + testWidgets( 'confirm cannot submit twice while the cancellation is in flight', (tester) async { diff --git a/app/test/features/runs/actions/decision_action_test.dart b/app/test/features/runs/actions/decision_action_test.dart index 9d424b8f..b756db79 100644 --- a/app/test/features/runs/actions/decision_action_test.dart +++ b/app/test/features/runs/actions/decision_action_test.dart @@ -212,6 +212,34 @@ void main() { }, ); + testWidgets('Cancel dismisses the draft without sending anything', ( + tester, + ) async { + final gateway = _FakeGateway( + (type, fields) async => {'run_detail': _decided()}, + ); + final changed = []; + await _pump( + tester, + gateway, + _waitingRun(), + cupertino: false, + changed: changed, + ); + + await _open(tester); + await tester.tap(find.text('go')); + await tester.pump(); + await tester.enterText(find.byKey(decisionFeedbackKey), 'not sent'); + await tester.tap(find.widgetWithText(TextButton, decisionCancelLabel)); + await tester.pumpAndSettle(); + + expect(find.byType(AlertDialog), findsNothing); + expect(gateway.calls, isEmpty); + expect(changed, isEmpty); + expect(find.byKey(decisionActionKey), findsOneWidget); + }); + testWidgets('the action is absent unless a run is genuinely waiting', ( tester, ) async { diff --git a/app/test/features/runs/actions/decision_resilience_test.dart b/app/test/features/runs/actions/decision_resilience_test.dart index d23981b5..e755ddc5 100644 --- a/app/test/features/runs/actions/decision_resilience_test.dart +++ b/app/test/features/runs/actions/decision_resilience_test.dart @@ -154,6 +154,117 @@ void main() { expect(find.byKey(decisionActionKey), findsNothing); }); + testWidgets('a refusal is shown before the resync keeps the draft', ( + tester, + ) async { + const refusal = 'option "go" is no longer valid'; + final resync = Completer(); + final gateway = _FakeGateway((type, fields) { + if (type == 'decide_run') throw const ProtocolError(refusal); + return resync.future; + }); + final changed = []; + await _pump(tester, gateway, changed); + await _chooseGo(tester, feedback: ' keep me '); + + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pump(); + + expect(find.text(refusal), findsOneWidget); + expect(find.byType(AlertDialog), findsOneWidget); + expect( + tester + .widget>(find.byType(RadioGroup)) + .groupValue, + 'go', + ); + expect( + tester + .widget(find.byKey(decisionFeedbackKey)) + .controller + ?.text, + ' keep me ', + ); + expect( + tester + .widget( + find.widgetWithText(TextButton, decisionCancelLabel), + ) + .onPressed, + isNotNull, + ); + expect(changed, isEmpty); + + resync.complete({'run_detail': _decided()}); + await tester.pumpAndSettle(); + + expect(find.text(refusal), findsOneWidget); + expect( + tester + .widget( + find.widgetWithText(FilledButton, decisionConfirmLabel), + ) + .onPressed, + isNull, + ); + expect(changed.single['status'], 'succeeded'); + }); + + testWidgets('a failed resync keeps the draft and allows a retry', ( + tester, + ) async { + const refusal = 'server refused the decision'; + final gateway = _FakeGateway((type, fields) async { + if (type == 'decide_run') throw const ProtocolError(refusal); + throw const NotConnectedError(); + }); + final changed = []; + await _pump(tester, gateway, changed); + await _chooseGo(tester, feedback: ' keep me '); + + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['decide_run', 'get_run']); + expect(find.text(refusal), findsOneWidget); + expect( + tester + .widget>(find.byType(RadioGroup)) + .groupValue, + 'go', + ); + expect( + tester + .widget( + find.widgetWithText(FilledButton, decisionConfirmLabel), + ) + .onPressed, + isNotNull, + ); + expect(changed, isEmpty); + }); + + testWidgets('a late resync after disposal is ignored safely', (tester) async { + final resync = Completer(); + final gateway = _FakeGateway((type, fields) { + if (type == 'decide_run') throw const ProtocolError('no longer waiting'); + return resync.future; + }); + final changed = []; + await _pump(tester, gateway, changed); + await _chooseGo(tester); + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pump(); + expect(gateway.calls.map((call) => call.type), ['decide_run', 'get_run']); + + await tester.pumpWidget(const SizedBox()); + resync.complete({'run_detail': _decided()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + testWidgets('confirm cannot submit twice while the decision is in flight', ( tester, ) async { From 0a0052669215262cb6aa59ddc4a7ffd72789ef52 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 14:54:36 +0100 Subject: [PATCH 37/84] docs(app): record verified cancellation and refusal correction landing --- app/WORK.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/WORK.md b/app/WORK.md index 4dc03fd0..987bd9a4 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -18,7 +18,7 @@ All work under app/. Existing applications remain running and unchanged. | R1 | Run list/detail/live timeline | controller43 + list48 + detail46 accepted | manager merged all three on flutter/r1-native; reran 25 combined tests + analyze, pass | candidate integrated, held for I1 | I1 run50 wiring + browser verification | | D1 | Recorded changes/diff viewer | run39 / flutter/d1-diff-viewer | Code computed success; WAITING truncated2MiB export | held, review not reached | pending | | R2a | Human-decision native confirm | run47 / commit42b21b8 | manager inspected source + reran 7 exact-confirm/refusal/native tests + analyze, pass | main3e6f950, ancestry verified | reusable component only; wiring/browser pending | -| R2b | Native cancel-run confirmation | run51 → focused52 / flutter/r2-cancel | 51 passed16 action tests in pipeline; manager confirmed prompt locks on refusal/resync,52 correcting both action flows with delayed-response regressions | held | pending | +| R2b | Native cancel-run confirmation | run51 →52 / correction5449370 | manager reran23 action tests + analyze, pass; known refusal now immediate and dismissible while resync pending | merged main; ancestry verified | reusable component only; wiring/browser pending | | X1 | Native search and result targets | run49 / flutter/x1-search | Code computed success; WAITING truncated2MiB export | held, review not reached | pending | | I1 | App-owned socket/session + live Runs shell registration | run50 / flutter/r1-native | Code computed success; WAITING truncated2MiB export | held, review not reached | not deployed | From 09458812d51d12ccbc6e2790f5c4586e35bbe52d Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 15:07:43 +0100 Subject: [PATCH 38/84] docs(app): record export-fix exception and three small parallel feature slices --- app/WORK.md | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/app/WORK.md b/app/WORK.md index 987bd9a4..e6fe6224 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -21,6 +21,10 @@ All work under app/. Existing applications remain running and unchanged. | R2b | Native cancel-run confirmation | run51 →52 / correction5449370 | manager reran23 action tests + analyze, pass; known refusal now immediate and dismissible while resync pending | merged main; ancestry verified | reusable component only; wiring/browser pending | | X1 | Native search and result targets | run49 / flutter/x1-search | Code computed success; WAITING truncated2MiB export | held, review not reached | pending | | I1 | App-owned socket/session + live Runs shell registration | run50 / flutter/r1-native | Code computed success; WAITING truncated2MiB export | held, review not reached | not deployed | +| E1 | Narrow authorized server export-bound fix | run53 / fix/session-export-limit | API v8, Flash; bounded export/repair regressions | pending | no service restart authorized by pipeline | +| R2c | Native retry/restart confirmation | run54 / flutter/r2-retry | Task v6, Flash; small independent action | pending | pending | +| R2d | Native rename-run dialog | run55 / flutter/r2-title | Task v6, Flash; small independent action | pending | pending | +| S1a | Saved schedules repository/revision safety | run56 / flutter/s1-data | Task v6, Flash; nonvisual independent slice | pending | — | ## Next ready work - P1 pipelines list/detail/source/version; P2 graph and stage/visit selection. @@ -61,9 +65,16 @@ session identities remain retained. `pipelines repair-session-export 34 1` was attempted once; it returned `session export repair incomplete: partial` at the same cap. No full stage reruns, evidence replacement, cancellation or gate bypass was performed. Remaining waits stay active for eventual export-only recovery. -Server export-cap change is outside the user's explicit app-only authorization; -approval is required before changing server code/configuration/deployment. Do -not burn repeated repair attempts against this deterministic size limit. +User subsequently approved the narrow server export-limit exception and asked +for continued small parallel tasks. Run53 owns ONLY bounded export-limit code, +necessary verification/repair regressions and a focused note. Existing web and +mobile source remain off-limits. Deployment remains a separate operator gate +under internal/server/AGENTS.md; no shared service restart is delegated. After +authorized installation, recover the original exact visits EXPORT-ONLY. Do not +burn repeated repair attempts against the unchanged deterministic size limit. + +Parallel work while E1 runs: R2c/R2d/S1a are separate worktrees, each with its own +focused existing Task v6 run and background wait. No new workflow definitions. At 160ab45: 29 Flutter tests and 6 Node proxy fixtures pass; flutter analyze, flutter build web and git diff --check pass. Real Chrome phone/desktop captures From 178f22aec20868656d0fff35e8a69dd2ce36baf6 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 15:13:00 +0100 Subject: [PATCH 39/84] feat(app): add native retry and restart action --- .../features/runs/actions/retry_action.dart | 123 +++++++++ .../features/runs/actions/retry_dialog.dart | 207 +++++++++++++++ .../runs/actions/retry_eligibility.dart | 16 ++ .../features/runs/actions/retry_intent.dart | 29 +++ .../features/runs/actions/retry_wording.dart | 33 +++ app/notes/R2c.md | 114 ++++++++ .../runs/actions/retry_action_test.dart | 245 ++++++++++++++++++ .../runs/actions/retry_resilience_test.dart | 223 ++++++++++++++++ .../runs/actions/retry_safety_test.dart | 133 ++++++++++ .../runs/actions/retry_test_support.dart | 112 ++++++++ 10 files changed, 1235 insertions(+) create mode 100644 app/lib/features/runs/actions/retry_action.dart create mode 100644 app/lib/features/runs/actions/retry_dialog.dart create mode 100644 app/lib/features/runs/actions/retry_eligibility.dart create mode 100644 app/lib/features/runs/actions/retry_intent.dart create mode 100644 app/lib/features/runs/actions/retry_wording.dart create mode 100644 app/notes/R2c.md create mode 100644 app/test/features/runs/actions/retry_action_test.dart create mode 100644 app/test/features/runs/actions/retry_resilience_test.dart create mode 100644 app/test/features/runs/actions/retry_safety_test.dart create mode 100644 app/test/features/runs/actions/retry_test_support.dart diff --git a/app/lib/features/runs/actions/retry_action.dart b/app/lib/features/runs/actions/retry_action.dart new file mode 100644 index 00000000..28cda388 --- /dev/null +++ b/app/lib/features/runs/actions/retry_action.dart @@ -0,0 +1,123 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../data/runs_repository.dart'; +import 'action_refusal.dart'; +import 'retry_dialog.dart'; +import 'retry_eligibility.dart'; +import 'retry_intent.dart'; +import 'retry_wording.dart'; + +/// The run detail's deliberate retry entry point. +/// +/// Renders one native button only while [run] is a stopped `failed` run. Opening +/// the resume or restart confirmation sends nothing; only the confirm action +/// asks the server to retry. A refusal is returned to the kept-open prompt +/// immediately and the run is re-read separately, so [onRunChanged] still +/// receives server truth without locking the prompt while that read is pending. +class RetryRunAction extends StatefulWidget { + const RetryRunAction({ + super.key, + required this.run, + required this.gateway, + required this.onRunChanged, + }); + + final JsonMap run; + final ApiGateway gateway; + final ValueChanged onRunChanged; + + @override + State createState() => _RetryRunActionState(); +} + +class _RetryRunActionState extends State { + bool _dialogOpen = false; + Future? _resync; + + bool _usesCupertino(BuildContext context) { + final material = Localizations.of( + context, + MaterialLocalizations, + ); + return material == null; + } + + Future _open() async { + final id = retryRunId(widget.run); + if (id == null || !canRetryRun(widget.run) || _dialogOpen) return; + _dialogOpen = true; + try { + await showRetryRunPrompt( + context: context, + runId: id, + cupertino: _usesCupertino(context), + onSubmit: (intent) => _submit(id, intent), + ); + } finally { + _dialogOpen = false; + if (mounted) setState(() {}); + } + } + + Future _submit(num id, RetryIntent intent) async { + final repository = RunsRepository(widget.gateway); + try { + final run = await repository.retryRun( + id, + requestKey: intent.requestKey, + mode: intent.mode.wireMode, + ); + if (!mounted) return null; + if (_owns(id)) widget.onRunChanged(run); + return null; + } catch (error) { + return ActionRefusal( + describeRetryError(error), + stillPossible: _resyncRun(id), + ); + } + } + + bool _owns(num id) => mounted && retryRunId(widget.run) == id; + + /// One bounded re-read per refusal. A refusal that arrives while a read is + /// already in flight observes that same read instead of starting another. + Future _resyncRun(num id) { + return _resync ??= _readRun(id); + } + + Future _readRun(num id) async { + try { + final run = await RunsRepository(widget.gateway).getRun(id); + if (!_owns(id)) return null; + widget.onRunChanged(run); + return canRetryRun(run); + } catch (_) { + // Unknown server truth: keep the refusal and leave a deliberate retry. + return null; + } finally { + _resync = null; + } + } + + @override + Widget build(BuildContext context) { + if (retryRunId(widget.run) == null || !canRetryRun(widget.run)) { + return const SizedBox.shrink(); + } + if (_usesCupertino(context)) { + return CupertinoButton.filled( + key: retryActionKey, + onPressed: _open, + child: const Text(retryActionLabel), + ); + } + return FilledButton( + key: retryActionKey, + onPressed: _open, + child: const Text(retryActionLabel), + ); + } +} diff --git a/app/lib/features/runs/actions/retry_dialog.dart b/app/lib/features/runs/actions/retry_dialog.dart new file mode 100644 index 00000000..846133a1 --- /dev/null +++ b/app/lib/features/runs/actions/retry_dialog.dart @@ -0,0 +1,207 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'action_refusal.dart'; +import 'retry_intent.dart'; +import 'retry_wording.dart'; + +/// Sends the confirmed retry intent. Returns null once the server has accepted +/// it, or an [ActionRefusal] carrying the server's words verbatim; the prompt +/// then stays open with dismissal available immediately. +typedef RetrySubmit = Future Function(RetryIntent intent); + +/// Opens the native retry confirmation for [runId]. +/// +/// The first confirmation offers resume (the default) and a secondary +/// `Restart from start` confirmation, exactly like the browser's retry dialog. +/// Nothing is sent until the operator presses a confirm action; `Keep` only +/// closes the prompt. +Future showRetryRunPrompt({ + required BuildContext context, + required num runId, + required bool cupertino, + required RetrySubmit onSubmit, +}) { + final prompt = _RetryPrompt( + runId: runId, + cupertino: cupertino, + onSubmit: onSubmit, + ); + if (cupertino) { + return showCupertinoDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); + } + return showDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); +} + +class _RetryPrompt extends StatefulWidget { + const _RetryPrompt({ + required this.runId, + required this.cupertino, + required this.onSubmit, + }); + + final num runId; + final bool cupertino; + final RetrySubmit onSubmit; + + @override + State<_RetryPrompt> createState() => _RetryPromptState(); +} + +class _RetryPromptState extends State<_RetryPrompt> { + RetryMode _mode = RetryMode.resume; + String? _requestKey; + bool _sending = false; + bool _checking = false; + bool _blocked = false; + bool _attempted = false; + String? _error; + + void _keep() { + if (!_sending) Navigator.of(context).pop(); + } + + void _restart() { + if (_sending || _checking || _attempted) return; + setState(() { + _mode = RetryMode.restart; + _error = null; + }); + } + + Future _confirm() async { + if (_sending || _checking || _blocked) return; + setState(() { + _sending = true; + _attempted = true; + _error = null; + }); + final intent = RetryIntent( + mode: _mode, + requestKey: _requestKey ??= newRetryRequestKey(widget.runId), + ); + final refusal = await widget.onSubmit(intent); + if (!mounted) return; + if (refusal == null) { + Navigator.of(context).pop(); + return; + } + final check = refusal.stillPossible; + setState(() { + _sending = false; + _error = refusal.message; + _checking = check != null; + }); + if (check == null) return; + bool? stillPossible; + try { + stillPossible = await check; + } catch (_) { + // The action reports re-read failures as null; never fabricate one here. + } + if (!mounted) return; + setState(() { + _checking = false; + _blocked = stillPossible == false; + }); + } + + @override + Widget build(BuildContext context) { + final dialog = widget.cupertino ? _cupertino(context) : _material(context); + return PopScope(canPop: !_sending, child: dialog); + } + + bool get _confirmDisabled => _sending || _checking || _blocked; + bool get _showRestart => _mode == RetryMode.resume && !_attempted; + + Widget _material(BuildContext context) { + final theme = Theme.of(context); + return AlertDialog( + scrollable: true, + title: Text(_dialogTitle), + content: _body(errorStyle: TextStyle(color: theme.colorScheme.error)), + actions: [ + if (_showRestart) + TextButton( + key: retryRestartKey, + onPressed: _sending || _checking ? null : _restart, + child: const Text(restartConfirmLabel), + ), + TextButton( + key: retryKeepKey, + onPressed: _sending ? null : _keep, + child: const Text(retryKeepLabel), + ), + FilledButton( + key: retryConfirmKey, + onPressed: _confirmDisabled ? null : _confirm, + child: Text(_confirmLabel), + ), + ], + ); + } + + Widget _cupertino(BuildContext context) { + return CupertinoAlertDialog( + title: Text(_dialogTitle), + content: _body( + errorStyle: TextStyle( + color: CupertinoColors.systemRed.resolveFrom(context), + ), + ), + actions: [ + if (_showRestart) + CupertinoDialogAction( + key: retryRestartKey, + onPressed: _sending || _checking ? null : _restart, + child: const Text(restartConfirmLabel), + ), + CupertinoDialogAction( + key: retryKeepKey, + onPressed: _sending ? null : _keep, + child: const Text(retryKeepLabel), + ), + CupertinoDialogAction( + key: retryConfirmKey, + isDestructiveAction: _mode == RetryMode.restart, + onPressed: _confirmDisabled ? null : _confirm, + child: Text(_confirmLabel), + ), + ], + ); + } + + Widget _body({required TextStyle errorStyle}) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(_dialogMessage), + if (_error case final error?) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(error, key: retryErrorKey, style: errorStyle), + ), + ], + ); + } + + String get _dialogTitle => _mode == RetryMode.restart + ? restartDialogTitle(widget.runId) + : retryDialogTitle(widget.runId); + + String get _dialogMessage => + _mode == RetryMode.restart ? restartDialogMessage : retryDialogMessage; + + String get _confirmLabel => + _mode == RetryMode.restart ? restartConfirmLabel : retryConfirmLabel; +} diff --git a/app/lib/features/runs/actions/retry_eligibility.dart b/app/lib/features/runs/actions/retry_eligibility.dart new file mode 100644 index 00000000..13026230 --- /dev/null +++ b/app/lib/features/runs/actions/retry_eligibility.dart @@ -0,0 +1,16 @@ +import '../../../core/api_gateway.dart'; + +/// Whether the operator may retry [run], matching `canRetry` in +/// `web/src/actions.js` exactly: a loaded run that is not executing and whose +/// status is `failed`. A stale `failed` status while the run still executes is +/// not retryable. +bool canRetryRun(JsonMap? run) { + if (run == null) return false; + return run['executing'] != true && run['status'] == 'failed'; +} + +/// The run id used by the retry request, or null for a malformed run. +num? retryRunId(JsonMap run) { + final id = run['id']; + return id is num ? id : null; +} diff --git a/app/lib/features/runs/actions/retry_intent.dart b/app/lib/features/runs/actions/retry_intent.dart new file mode 100644 index 00000000..17140a70 --- /dev/null +++ b/app/lib/features/runs/actions/retry_intent.dart @@ -0,0 +1,29 @@ +import 'dart:math'; + +/// The two deliberate retry choices. `resume` is the server's default, so its +/// wire field is omitted; `restart` replays the whole pipeline. +enum RetryMode { + resume, + restart; + + /// The `retry_mode` value to send, or null to let the server resume. + String? get wireMode => this == RetryMode.restart ? 'restart' : null; +} + +/// One confirmed retry intent: the chosen mode plus the idempotency key that +/// belongs to it. Retrying the same uncertain intent reuses [requestKey] so the +/// server can dedupe it; a fresh deliberate intent uses a new key. +class RetryIntent { + const RetryIntent({required this.mode, required this.requestKey}); + + final RetryMode mode; + final String requestKey; +} + +/// A fresh `request_key` for one retry intent. The server requires one and caps +/// it at 128 characters; this stays well inside that bound and unique per call. +String newRetryRequestKey(num runId, {DateTime? now, int? random}) { + final stamp = (now ?? DateTime.now()).microsecondsSinceEpoch; + final entropy = random ?? Random().nextInt(1 << 32); + return 'app-retry-$runId-$stamp-${entropy.toRadixString(36)}'; +} diff --git a/app/lib/features/runs/actions/retry_wording.dart b/app/lib/features/runs/actions/retry_wording.dart new file mode 100644 index 00000000..efec7d86 --- /dev/null +++ b/app/lib/features/runs/actions/retry_wording.dart @@ -0,0 +1,33 @@ +import 'package:flutter/widgets.dart'; + +/// The browser client's retry wording, kept verbatim. +const retryActionLabel = 'Retry'; +const retryDialogMessage = + 'Only failed runs can be retried. The server starts a new run from the ' + 'same input.'; +const retryConfirmLabel = 'Retry'; +const restartDialogMessage = + 'This replays the whole pipeline from the start instead of resuming the ' + 'failed stage.'; +const restartConfirmLabel = 'Restart from start'; +const retryKeepLabel = 'Keep'; + +/// Stable test/semantics keys shared by the action and its prompt. +const retryActionKey = ValueKey('retry-run-action'); +const retryKeepKey = ValueKey('retry-run-keep'); +const retryConfirmKey = ValueKey('retry-run-confirm'); +const retryRestartKey = ValueKey('retry-run-restart'); +const retryErrorKey = ValueKey('retry-run-error'); + +/// The retry dialog's title: `Retry run {id}?`. +String retryDialogTitle(num runId) => 'Retry run $runId?'; + +/// The restart dialog's title: `Restart run {id}?`. +String restartDialogTitle(num runId) => 'Restart run $runId?'; + +/// The server's refusal, verbatim. Only a blank error gets a generic sentence +/// so the prompt never claims a retry that did not happen. +String describeRetryError(Object error) { + final message = '$error'.trim(); + return message.isEmpty ? 'The server did not retry the run.' : message; +} diff --git a/app/notes/R2c.md b/app/notes/R2c.md new file mode 100644 index 00000000..f2240602 --- /dev/null +++ b/app/notes/R2c.md @@ -0,0 +1,114 @@ +# R2c — native retry / restart action + +Small app-only addition, new files only. `RetryRunAction(run, gateway, +onRunChanged)` is the deliberate retry entry point for a stopped failed run; it +does not add a screen or controller and is not wired into the shell. + +## What changed + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/runs/actions/retry_action.dart` | 123 | `RetryRunAction`, gating, send/refusal/resync orchestration | +| `lib/features/runs/actions/retry_dialog.dart` | 207 | Native resume/restart confirmation, refusal display, key lifetime | +| `lib/features/runs/actions/retry_eligibility.dart` | 16 | `canRetryRun` mirroring the web `canRetry` | +| `lib/features/runs/actions/retry_intent.dart` | 29 | Mode, confirmed intent and idempotency-key generation | +| `lib/features/runs/actions/retry_wording.dart` | 33 | Web-verbatim words, titles, error wording and test keys | +| `test/.../retry_test_support.dart` | 112 | Fake gateway and Material/Cupertino hosts | +| `test/.../retry_action_test.dart` | 245 | Eligibility, both platforms, modes and key fields | +| `test/.../retry_resilience_test.dart` | 223 | Immediate refusals, recheck outcomes, key retention | +| `test/.../retry_safety_test.dart` | 133 | Double submit, late replies, narrow 2x layout | + +No repository, gateway, socket, controller, shell, main, pubspec, web, server or +device file was edited. + +## Behavior + +Eligibility is exactly the browser's rule: a loaded run that is not executing and +whose status is `failed` (`run != null && !run.executing && status == "failed"`). +A stale `failed` status while execution is still in flight, a running/waiting/ +succeeded/canceled run, and a malformed run render nothing. + +The button is a Material `FilledButton` or a Cupertino `CupertinoButton.filled`, +labelled `Retry`. Opening the prompt sends nothing, and `Keep` only closes it. + +The first confirmation is the browser's retry copy: title `Retry run {id}?`, +message `Only failed runs can be retried. The server starts a new run from the +same input.`, confirm `Retry`, dismiss `Keep`, plus the browser-only secondary +`Restart from start` that leads to a distinct confirmation. That second prompt +uses title `Restart run {id}?`, message `This replays the whole pipeline from the +start instead of resuming the failed stage.` and confirm `Restart from start`; +the resume actions are gone, so the more destructive choice cannot be mistaken +for resume. + +Resume calls `RunsRepository.retryRun` with only `run_id` and `request_key`, so +`retry_mode` is omitted and the server's `resume` default applies. Restart sends +`retry_mode: "restart"` with the same two required fields. + +A `request_key` is created on the first confirm of an open prompt, not on opening +or `Keep`. It survives a refusal, so pressing confirm again for the same +uncertain request reuses the key and the server can dedupe it. Closing the prompt +and opening it again is a fresh deliberate intent and gets a new key, so a resume +attempt followed by a restart attempt never shares a key. Switching to the +restart confirmation before any send simply confirms restart with that prompt's +first key. Keys are bounded and run-scoped (`app-retry-{runId}-…`, well under the +server's 128-character cap). + +A server refusal returns to the prompt immediately: the exact server words are +visible and `Keep`/back are available while the detached `get_run` recheck is +still pending. One bounded re-read is issued per refusal, single-flight through a +retained future, with no retry loop or polling. If server truth says the run is no +longer retryable, confirm is disabled and an attempted tap sends nothing; the +refusal stays visible until dismissal. If the recheck itself fails, truth is +unknown, so confirm is re-enabled and a deliberate retry uses the retained key. +Late retry replies and late rechecks after disposal or navigation are ignored. + +Construction, controls and error colour are standard Material/Cupertino defaults; +there is no custom palette, fixed control size or dependency. The narrow layout +relies on the native dialog's own scrolling/wrapping. + +## Acceptance checks + +Fake-gateway widget tests, both platforms, no socket or real server: + +- eligibility table for stopped failed vs executing failed, running, waiting, + succeeded and canceled runs, plus the same visibility table under both apps; +- `Retry` opens the native `AlertDialog`/`CupertinoAlertDialog`, `Keep` closes it + and the recorded gateway calls are still empty; +- resume sends exactly `{run_id, request_key}` and no `retry_mode`; restart sends + exactly `{run_id, request_key, retry_mode: "restart"}`; +- key format is deterministic under an injected clock/entropy, bounded, fresh per + call, retained across an uncertain retry (resume and restart), and different + after a deliberate reopen or mode change; +- refusal message appears while `get_run` is deliberately unresolved, with Keep + enabled, confirm disabled and no callback yet; Keep then closes and the late + recheck still delivers server truth safely; +- ineligible recheck (`succeeded`) blocks a repeat action; failed recheck leaves + the same key and a working deliberate retry; +- two confirm taps while in flight produce one `retry_run`; both the retry reply + and the recheck are safe after disposal; +- 320×480 at 2× text: both resume and restart confirmations render on both apps + with no exception, and Keep sends nothing. + +## Checks actually run + +``` +dart format lib/features/runs/actions test/features/runs/actions # clean +flutter analyze # No issues found! +flutter test test/features/runs/actions # 40 passed +flutter test # 69 passed +flutter build web # Built build/web (14.5s) +``` + +## Honest limits + +- **Not wired into a run-detail screen.** This branch has no runs screen or + controller; the manager owns that integration. There is no browser interaction + or rendered capture for this widget, and `flutter build web` proves compilation + only, not rendered behavior. +- Browser parity is by source/word/request-shape comparison with + `web/src/actions.js` and `web/src/repository.js`; the web client itself was not + changed and no live web retry was performed. +- **Mobile unverified.** No Android/iOS build, emulator, ADB or device was used. +- No real server or run was retried, canceled or otherwise mutated; all evidence + uses local fakes. +- The candidate is committed, not pushed or deployed. diff --git a/app/test/features/runs/actions/retry_action_test.dart b/app/test/features/runs/actions/retry_action_test.dart new file mode 100644 index 00000000..ca11fa8b --- /dev/null +++ b/app/test/features/runs/actions/retry_action_test.dart @@ -0,0 +1,245 @@ +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/features/runs/actions/retry_eligibility.dart'; +import 'package:pipelines_app/features/runs/actions/retry_intent.dart'; +import 'package:pipelines_app/features/runs/actions/retry_wording.dart'; + +import 'retry_test_support.dart'; + +void main() { + test('retry eligibility matches the web canRetry exactly', () { + final cases = <(String, JsonMap, bool)>[ + ('failed and stopped', failedRun(), true), + ('failed but still executing', failedRun(executing: true), false), + ('running', failedRun(status: 'running'), false), + ('waiting', failedRun(status: 'waiting'), false), + ('succeeded', failedRun(status: 'succeeded'), false), + ('canceled', failedRun(status: 'canceled'), false), + ]; + for (final (label, run, expected) in cases) { + expect(canRetryRun(run), expected, reason: label); + } + expect(canRetryRun(null), isFalse); + expect(retryRunId(failedRun()), 7); + expect(retryRunId({'id': '7'}), isNull); + }); + + test('a generated retry key is bounded, run-scoped and fresh', () { + final first = newRetryRequestKey(7); + final second = newRetryRequestKey(7); + + expect(first, startsWith('app-retry-7-')); + expect(first.length, lessThanOrEqualTo(128)); + expect(second.length, lessThanOrEqualTo(128)); + expect(first, isNot(second)); + expect( + newRetryRequestKey(7, now: DateTime.utc(2026, 1, 1), random: 36), + 'app-retry-7-${DateTime.utc(2026, 1, 1).microsecondsSinceEpoch}-10', + ); + }); + + testWidgets( + 'material retry asks first, Keep sends nothing, then omits retry_mode', + (tester) async { + final accepted = retriedRun(); + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + expect(find.byKey(retryActionKey), findsOneWidget); + expect(find.byType(FilledButton), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsOneWidget); + expect(find.text(retryDialogTitle(7)), findsOneWidget); + expect(find.text(retryDialogMessage), findsOneWidget); + expect( + find.descendant( + of: find.byType(AlertDialog), + matching: find.text(retryConfirmLabel), + ), + findsOneWidget, + ); + expect(find.text(restartConfirmLabel), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(retryActionKey), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(1)); + final fields = gateway.retries.single.fields; + expect(fields.keys, containsAll(['run_id', 'request_key'])); + expect(fields.containsKey('retry_mode'), isFalse); + expect(fields['run_id'], 7); + expect(fields['request_key'], startsWith('app-retry-7-')); + expect(fields['request_key'].length, lessThanOrEqualTo(128)); + expect(changed.single, equals(accepted)); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(retryActionKey), findsNothing); + }, + ); + + testWidgets( + 'material restart has its own confirmation and sends retry_mode', + (tester) async { + final accepted = retriedRun(); + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + + expect(find.text(restartDialogTitle(7)), findsOneWidget); + expect(find.text(restartDialogMessage), findsOneWidget); + expect(find.text(retryDialogTitle(7)), findsNothing); + expect(find.text(retryDialogMessage), findsNothing); + expect(find.text(restartConfirmLabel), findsOneWidget); + expect(find.byKey(retryRestartKey), findsNothing); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(1)); + final fields = gateway.retries.single.fields; + expect(fields['run_id'], 7); + expect(fields['retry_mode'], 'restart'); + expect(fields['request_key'], startsWith('app-retry-7-')); + expect(changed.single, equals(accepted)); + expect(find.byType(AlertDialog), findsNothing); + }, + ); + + testWidgets( + 'cupertino retry uses a native prompt and sends only on confirm', + (tester) async { + final accepted = retriedRun(); + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await pumpRetry( + tester, + gateway: gateway, + changed: changed, + cupertino: true, + ); + + expect(find.byKey(retryActionKey), findsOneWidget); + expect(find.byType(CupertinoButton), findsOneWidget); + expect(find.byType(FilledButton), findsNothing); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.byType(AlertDialog), findsNothing); + expect(find.text(retryDialogTitle(7)), findsOneWidget); + expect(find.text(retryDialogMessage), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(gateway.calls, isEmpty); + expect(find.byType(CupertinoAlertDialog), findsNothing); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(1)); + final fields = gateway.retries.single.fields; + expect(fields['run_id'], 7); + expect(fields.containsKey('retry_mode'), isFalse); + expect(fields['request_key'], startsWith('app-retry-7-')); + expect(changed.single, equals(accepted)); + expect(find.byType(CupertinoAlertDialog), findsNothing); + }, + ); + + testWidgets('cupertino restart switches to the restart confirmation', ( + tester, + ) async { + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': retriedRun()}, + ); + await pumpRetry( + tester, + gateway: gateway, + changed: [], + cupertino: true, + ); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.text(restartDialogTitle(7)), findsOneWidget); + expect(find.text(restartDialogMessage), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + expect(gateway.retries.single.fields['retry_mode'], 'restart'); + }); + + testWidgets('the action is absent for runs the web does not retry', ( + tester, + ) async { + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': retriedRun()}, + ); + final changed = []; + final cases = <(String, JsonMap, bool)>[ + ('failed', failedRun(), true), + ('executing', failedRun(executing: true), false), + ('running', failedRun(status: 'running'), false), + ('waiting', failedRun(status: 'waiting'), false), + ('succeeded', failedRun(status: 'succeeded'), false), + ('canceled', failedRun(status: 'canceled'), false), + ]; + for (final cupertino in [false, true]) { + for (final (label, run, visible) in cases) { + await tester.pumpWidget( + retryApp( + RetryHost( + key: ValueKey('$label-$cupertino'), + gateway: gateway, + initial: run, + changed: changed, + ), + cupertino: cupertino, + ), + ); + expect( + find.byKey(retryActionKey), + visible ? findsOneWidget : findsNothing, + reason: '$label cupertino=$cupertino', + ); + } + } + expect(gateway.calls, isEmpty); + expect(changed, isEmpty); + }); +} diff --git a/app/test/features/runs/actions/retry_resilience_test.dart b/app/test/features/runs/actions/retry_resilience_test.dart new file mode 100644 index 00000000..26053426 --- /dev/null +++ b/app/test/features/runs/actions/retry_resilience_test.dart @@ -0,0 +1,223 @@ +import 'dart:async'; + +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/retry_eligibility.dart'; +import 'package:pipelines_app/features/runs/actions/retry_wording.dart'; + +import 'retry_test_support.dart'; + +Future _openAndConfirm(WidgetTester tester) async { + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); +} + +void main() { + testWidgets('a refusal is shown at once and Keep does not wait for resync', ( + tester, + ) async { + const refusal = 'run 7 is still executing; wait for it to stop completely'; + final resync = Completer(); + final gateway = FakeRetryGateway((type, fields) { + if (type == 'retry_run') throw const ProtocolError(refusal); + return resync.future; + }); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await _openAndConfirm(tester); + await tester.pump(); + + expect(gateway.calls.map((call) => call.type), ['retry_run', 'get_run']); + expect(find.text(refusal), findsOneWidget); + expect(find.byKey(retryErrorKey), findsOneWidget); + expect( + tester.widget(find.byKey(retryKeepKey)).onPressed, + isNotNull, + ); + expect( + tester.widget(find.byKey(retryConfirmKey)).onPressed, + isNull, + ); + expect(changed, isEmpty); + + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + + resync.complete({'run_detail': failedRun(status: 'succeeded')}); + await tester.pump(); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed.single['status'], 'succeeded'); + expect(find.byKey(retryActionKey), findsNothing); + }); + + testWidgets('server truth that is ineligible blocks a repeat action', ( + tester, + ) async { + const refusal = 'only failed runs can be retried'; + final finished = failedRun(status: 'succeeded'); + final gateway = FakeRetryGateway((type, fields) async { + if (type == 'retry_run') throw const ProtocolError(refusal); + return {'run_detail': finished}; + }); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['retry_run', 'get_run']); + expect(find.text(refusal), findsOneWidget); + expect( + tester.widget(find.byKey(retryConfirmKey)).onPressed, + isNull, + ); + expect( + tester.widget(find.byKey(retryKeepKey)).onPressed, + isNotNull, + ); + + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pump(); + expect(gateway.calls.map((call) => call.type), ['retry_run', 'get_run']); + + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(retryActionKey), findsNothing); + expect(changed.single, equals(finished)); + expect(canRetryRun(changed.single), isFalse); + }); + + testWidgets('a failed recheck keeps the same key for the uncertain request', ( + tester, + ) async { + const refusal = 'connection dropped while retrying'; + var attempts = 0; + final gateway = FakeRetryGateway((type, fields) async { + if (type == 'get_run') throw const NotConnectedError(); + attempts += 1; + if (attempts == 1) throw const ProtocolError(refusal); + return {'run_detail': retriedRun()}; + }); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + + expect(find.text(refusal), findsOneWidget); + expect( + tester.widget(find.byKey(retryConfirmKey)).onPressed, + isNotNull, + ); + expect(gateway.retries, hasLength(1)); + + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(2)); + expect( + gateway.retries.last.fields['request_key'], + gateway.retries.first.fields['request_key'], + ); + expect( + gateway.retries.every((call) => !call.fields.containsKey('retry_mode')), + isTrue, + ); + expect(changed.single, equals(retriedRun())); + expect(find.byType(AlertDialog), findsNothing); + }); + + testWidgets('a restart retry keeps the mode and key across uncertainty', ( + tester, + ) async { + var attempts = 0; + final gateway = FakeRetryGateway((type, fields) async { + if (type == 'get_run') throw const NotConnectedError(); + attempts += 1; + if (attempts == 1) throw const ProtocolError('network lost'); + return {'run_detail': retriedRun()}; + }); + await pumpRetry(tester, gateway: gateway, changed: []); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(2)); + expect(gateway.retries.first.fields['retry_mode'], 'restart'); + expect(gateway.retries.last.fields['retry_mode'], 'restart'); + expect( + gateway.retries.last.fields['request_key'], + gateway.retries.first.fields['request_key'], + ); + }); + + testWidgets('a deliberate reopen sends a fresh request key', (tester) async { + final gateway = FakeRetryGateway((type, fields) async { + if (type == 'get_run') throw const NotConnectedError(); + throw const ProtocolError('server did not answer'); + }); + await pumpRetry(tester, gateway: gateway, changed: []); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(2)); + expect( + gateway.retries.first.fields['request_key'], + isNot(gateway.retries.last.fields['request_key']), + ); + }); + + testWidgets('a restart after a dismissed resume uses a fresh key', ( + tester, + ) async { + var attempts = 0; + final gateway = FakeRetryGateway((type, fields) async { + if (type == 'get_run') throw const NotConnectedError(); + attempts += 1; + if (attempts == 1) throw const ProtocolError('resume refused'); + return {'run_detail': retriedRun()}; + }); + await pumpRetry(tester, gateway: gateway, changed: []); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + // A refusal leaves the prompt open; keep the mode frozen and dismiss. + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(2)); + expect(gateway.retries.first.fields.containsKey('retry_mode'), isFalse); + expect(gateway.retries.last.fields['retry_mode'], 'restart'); + expect( + gateway.retries.first.fields['request_key'], + isNot(gateway.retries.last.fields['request_key']), + ); + }); +} diff --git a/app/test/features/runs/actions/retry_safety_test.dart b/app/test/features/runs/actions/retry_safety_test.dart new file mode 100644 index 00000000..df9e7e88 --- /dev/null +++ b/app/test/features/runs/actions/retry_safety_test.dart @@ -0,0 +1,133 @@ +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/retry_wording.dart'; + +import 'retry_test_support.dart'; + +void main() { + testWidgets('confirm cannot submit twice while the retry is in flight', ( + tester, + ) async { + final reply = Completer(); + final gateway = FakeRetryGateway((type, fields) => reply.future); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + final confirm = find.byKey(retryConfirmKey); + await tester.tap(confirm); + await tester.tap(confirm); + await tester.pump(); + + expect(gateway.retries, hasLength(1)); + expect( + tester.widget(find.byKey(retryConfirmKey)).onPressed, + isNull, + ); + expect( + tester.widget(find.byKey(retryKeepKey)).onPressed, + isNull, + ); + expect(find.byType(AlertDialog), findsOneWidget); + + reply.complete({'run_detail': retriedRun()}); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(changed, hasLength(1)); + }); + + testWidgets('a late retry reply after disposal is ignored safely', ( + tester, + ) async { + final reply = Completer(); + final gateway = FakeRetryGateway((type, fields) => reply.future); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pump(); + expect(gateway.retries, hasLength(1)); + + await tester.pumpWidget(const SizedBox()); + reply.complete({'run_detail': retriedRun()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + + testWidgets('a late resync after disposal is ignored safely', (tester) async { + final resync = Completer(); + final gateway = FakeRetryGateway((type, fields) { + if (type == 'retry_run') throw const ProtocolError('refused'); + return resync.future; + }); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pump(); + expect(gateway.calls.map((call) => call.type), ['retry_run', 'get_run']); + + await tester.pumpWidget(const SizedBox()); + resync.complete({'run_detail': retriedRun()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + + testWidgets('both confirmations fit 2x text at a narrow width', ( + tester, + ) async { + tester.view.physicalSize = const Size(320, 480); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + for (final cupertino in [false, true]) { + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': retriedRun()}, + ); + await pumpRetry( + tester, + gateway: gateway, + changed: [], + cupertino: cupertino, + textScale: 2, + ); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino'); + expect(find.text(retryDialogTitle(7)), findsOneWidget); + expect(find.text(retryDialogMessage), findsOneWidget); + expect( + cupertino + ? find.byType(CupertinoAlertDialog) + : find.byType(AlertDialog), + findsOneWidget, + ); + + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull, reason: 'restart=$cupertino'); + expect(find.text(restartDialogTitle(7)), findsOneWidget); + expect(find.text(restartDialogMessage), findsOneWidget); + + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(gateway.calls, isEmpty); + } + }); +} diff --git a/app/test/features/runs/actions/retry_test_support.dart b/app/test/features/runs/actions/retry_test_support.dart new file mode 100644 index 00000000..67556d05 --- /dev/null +++ b/app/test/features/runs/actions/retry_test_support.dart @@ -0,0 +1,112 @@ +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/features/runs/actions/retry_action.dart'; + +typedef RetryHandler = Future Function(String type, JsonMap fields); + +/// A fake gateway that records every request and never owns a socket. +class FakeRetryGateway implements ApiGateway { + FakeRetryGateway(this.handler); + + final RetryHandler handler; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) { + final copy = Map.from(fields); + calls.add((type: type, fields: copy)); + return handler(type, copy); + } + + @override + Stream get frames => const Stream.empty(); + + Iterable<({String type, JsonMap fields})> get retries => + calls.where((call) => call.type == 'retry_run'); +} + +JsonMap failedRun({ + num id = 7, + bool executing = false, + String status = 'failed', + String title = 'Nightly build', +}) => {'id': id, 'title': title, 'status': status, 'executing': executing}; + +JsonMap retriedRun({num id = 8}) => + failedRun(id: id, status: 'running', executing: true, title: 'Retry of 7'); + +/// Owns the run like a run-detail screen would, so the callback's returned +/// server detail is what the action renders next. +class RetryHost extends StatefulWidget { + const RetryHost({ + super.key, + required this.gateway, + required this.initial, + required this.changed, + }); + + final FakeRetryGateway gateway; + final JsonMap initial; + final List changed; + + @override + State createState() => _RetryHostState(); +} + +class _RetryHostState extends State { + late JsonMap _run = widget.initial; + + @override + Widget build(BuildContext context) { + return RetryRunAction( + run: _run, + gateway: widget.gateway, + onRunChanged: (run) { + widget.changed.add(run); + setState(() => _run = run); + }, + ); + } +} + +Widget retryApp(Widget child, {required bool cupertino, double textScale = 1}) { + Widget media(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + if (cupertino) { + return CupertinoApp( + builder: media, + home: CupertinoPageScaffold(child: Center(child: child)), + ); + } + return MaterialApp( + builder: media, + home: Scaffold(body: Center(child: child)), + ); +} + +Future pumpRetry( + WidgetTester tester, { + required FakeRetryGateway gateway, + required List changed, + bool cupertino = false, + double textScale = 1, + JsonMap? run, +}) async { + await tester.pumpWidget( + retryApp( + RetryHost( + gateway: gateway, + initial: run ?? failedRun(), + changed: changed, + ), + cupertino: cupertino, + textScale: textScale, + ), + ); +} From f2643a0ff416191e53489b2ca91fcddc2d47613a Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 15:14:44 +0100 Subject: [PATCH 40/84] feat(app): add native rename-run action Native Material/Cupertino prompt seeded from the run's stored title. Only Save sends set_run_title {run_id, title} with the text untrimmed; typing and Cancel send nothing, refusals stay verbatim with the draft kept, and only the accepted run_detail is delivered once. --- .../features/runs/actions/title_action.dart | 109 ++++++++ .../features/runs/actions/title_dialog.dart | 183 +++++++++++++ .../features/runs/actions/title_wording.dart | 24 ++ app/notes/R2d.md | 93 +++++++ .../runs/actions/title_action_test.dart | 244 ++++++++++++++++++ .../runs/actions/title_resilience_test.dart | 243 +++++++++++++++++ .../runs/actions/title_test_support.dart | 110 ++++++++ 7 files changed, 1006 insertions(+) create mode 100644 app/lib/features/runs/actions/title_action.dart create mode 100644 app/lib/features/runs/actions/title_dialog.dart create mode 100644 app/lib/features/runs/actions/title_wording.dart create mode 100644 app/notes/R2d.md create mode 100644 app/test/features/runs/actions/title_action_test.dart create mode 100644 app/test/features/runs/actions/title_resilience_test.dart create mode 100644 app/test/features/runs/actions/title_test_support.dart diff --git a/app/lib/features/runs/actions/title_action.dart b/app/lib/features/runs/actions/title_action.dart new file mode 100644 index 00000000..7a5b9b97 --- /dev/null +++ b/app/lib/features/runs/actions/title_action.dart @@ -0,0 +1,109 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../data/runs_repository.dart'; +import 'action_refusal.dart'; +import 'title_dialog.dart'; +import 'title_wording.dart'; + +/// The run detail's rename entry point, mirroring the browser's rename row. +/// +/// The prompt starts with [run]'s stored title exactly as the server sent it +/// (never a prompt or output fallback). Typing and Cancel send nothing; only +/// Save sends `set_run_title` with the exact run id and title text. A refusal is +/// returned verbatim to the kept-open prompt, and only the server's returned +/// `run_detail` is delivered through [onRunChanged], once. +class RunTitleAction extends StatefulWidget { + const RunTitleAction({ + super.key, + required this.run, + required this.gateway, + required this.onRunChanged, + }); + + final JsonMap run; + final ApiGateway gateway; + final ValueChanged onRunChanged; + + @override + State createState() => _RunTitleActionState(); +} + +class _RunTitleActionState extends State { + bool _dialogOpen = false; + bool _saving = false; + + bool _usesCupertino(BuildContext context) { + final material = Localizations.of( + context, + MaterialLocalizations, + ); + return material == null; + } + + Future _open() async { + final id = runTitleId(widget.run); + if (id == null || _dialogOpen) return; + _dialogOpen = true; + try { + await showRunTitlePrompt( + context: context, + runId: id, + initialTitle: storedRunTitle(widget.run), + cupertino: _usesCupertino(context), + onSubmit: (title) => _submit(id, title), + ); + } finally { + _dialogOpen = false; + if (mounted) setState(() {}); + } + } + + Future _submit(num id, String title) async { + if (_saving) return const ActionRefusal(actionAlreadySending); + _saving = true; + try { + final run = await RunsRepository(widget.gateway).setRunTitle(id, title); + if (!mounted) return null; + if (_owns(id)) widget.onRunChanged(run); + return null; + } catch (error) { + return ActionRefusal(describeTitleError(error)); + } finally { + _saving = false; + } + } + + bool _owns(num id) => mounted && runTitleId(widget.run) == id; + + @override + Widget build(BuildContext context) { + if (runTitleId(widget.run) == null) return const SizedBox.shrink(); + if (_usesCupertino(context)) { + return CupertinoButton( + key: runTitleActionKey, + onPressed: _open, + child: const Text(runTitleActionLabel), + ); + } + return OutlinedButton( + key: runTitleActionKey, + onPressed: _open, + child: const Text(runTitleActionLabel), + ); + } +} + +/// The run id used by the rename request, or null for a malformed run. +num? runTitleId(JsonMap run) { + final id = run['id']; + return id is num ? id : null; +} + +/// The run's stored title exactly as the browser reads it +/// (`String(d.title ?? "")`); never inferred from the prompt or output. +String storedRunTitle(JsonMap run) { + final title = run['title']; + return title == null ? '' : '$title'; +} diff --git a/app/lib/features/runs/actions/title_dialog.dart b/app/lib/features/runs/actions/title_dialog.dart new file mode 100644 index 00000000..9ae03a11 --- /dev/null +++ b/app/lib/features/runs/actions/title_dialog.dart @@ -0,0 +1,183 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'action_refusal.dart'; +import 'title_wording.dart'; + +/// Sends the typed title. Returns null once the server has accepted it, or an +/// [ActionRefusal] carrying the server's words verbatim; the prompt then stays +/// open with the typed title intact. +typedef TitleSubmit = Future Function(String title); + +/// Opens the native rename prompt for [runId], seeded with the run's stored +/// [initialTitle]. +/// +/// Typing and the dismiss action send nothing; only Save sends the title. The +/// title is passed through exactly as typed, including surrounding whitespace, +/// matching `setRunTitle` in `web/src/repository.js`; the server decides whether +/// a blank title is acceptable. +Future showRunTitlePrompt({ + required BuildContext context, + required num runId, + required String initialTitle, + required bool cupertino, + required TitleSubmit onSubmit, +}) { + final prompt = _TitlePrompt( + runId: runId, + initialTitle: initialTitle, + cupertino: cupertino, + onSubmit: onSubmit, + ); + if (cupertino) { + return showCupertinoDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); + } + return showDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); +} + +class _TitlePrompt extends StatefulWidget { + const _TitlePrompt({ + required this.runId, + required this.initialTitle, + required this.cupertino, + required this.onSubmit, + }); + + final num runId; + final String initialTitle; + final bool cupertino; + final TitleSubmit onSubmit; + + @override + State<_TitlePrompt> createState() => _TitlePromptState(); +} + +class _TitlePromptState extends State<_TitlePrompt> { + late final TextEditingController _title = TextEditingController( + text: widget.initialTitle, + ); + bool _sending = false; + String? _error; + + @override + void dispose() { + _title.dispose(); + super.dispose(); + } + + void _cancel() { + if (!_sending) Navigator.of(context).pop(); + } + + Future _save() async { + if (_sending) return; + setState(() { + _sending = true; + _error = null; + }); + final refusal = await widget.onSubmit(_title.text); + if (!mounted) return; + if (refusal == null) { + Navigator.of(context).pop(); + return; + } + setState(() { + _sending = false; + _error = refusal.message; + }); + } + + @override + Widget build(BuildContext context) { + final dialog = widget.cupertino ? _cupertino(context) : _material(context); + return PopScope(canPop: !_sending, child: dialog); + } + + Widget _material(BuildContext context) { + final theme = Theme.of(context); + return AlertDialog( + scrollable: true, + title: const Text(runTitleDialogTitle), + content: _body( + field: TextField( + key: runTitleFieldKey, + controller: _title, + enabled: !_sending, + autofocus: true, + decoration: const InputDecoration(labelText: runTitleFieldLabel), + textInputAction: TextInputAction.done, + onSubmitted: (_) => _save(), + ), + errorStyle: TextStyle(color: theme.colorScheme.error), + ), + actions: [ + TextButton( + key: runTitleCancelKey, + onPressed: _sending ? null : _cancel, + child: const Text(runTitleCancelLabel), + ), + FilledButton( + key: runTitleSaveKey, + onPressed: _sending ? null : _save, + child: const Text(runTitleSaveLabel), + ), + ], + ); + } + + Widget _cupertino(BuildContext context) { + return CupertinoAlertDialog( + title: const Text(runTitleDialogTitle), + content: _body( + field: CupertinoTextField( + key: runTitleFieldKey, + controller: _title, + enabled: !_sending, + autofocus: true, + placeholder: runTitleFieldLabel, + textInputAction: TextInputAction.done, + onSubmitted: (_) => _save(), + ), + errorStyle: TextStyle( + color: CupertinoColors.systemRed.resolveFrom(context), + ), + ), + actions: [ + CupertinoDialogAction( + key: runTitleCancelKey, + onPressed: _sending ? null : _cancel, + child: const Text(runTitleCancelLabel), + ), + CupertinoDialogAction( + key: runTitleSaveKey, + isDefaultAction: true, + onPressed: _sending ? null : _save, + child: const Text(runTitleSaveLabel), + ), + ], + ); + } + + Widget _body({required Widget field, required TextStyle errorStyle}) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + field, + if (_error case final error?) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(error, key: runTitleErrorKey, style: errorStyle), + ), + ], + ); + } +} diff --git a/app/lib/features/runs/actions/title_wording.dart b/app/lib/features/runs/actions/title_wording.dart new file mode 100644 index 00000000..8fa85891 --- /dev/null +++ b/app/lib/features/runs/actions/title_wording.dart @@ -0,0 +1,24 @@ +import 'package:flutter/widgets.dart'; + +/// The browser client's rename wording, kept verbatim. +const runTitleActionLabel = 'Rename'; +const runTitleDialogTitle = 'Rename'; +const runTitleFieldLabel = 'Run title'; +const runTitleSaveLabel = 'Save'; +const runTitleCancelLabel = 'Cancel'; + +/// Stable test/semantics keys shared by the action and its prompt. +const runTitleActionKey = ValueKey('rename-run-action'); +const runTitleFieldKey = ValueKey('rename-run-field'); +const runTitleSaveKey = ValueKey('rename-run-save'); +const runTitleCancelKey = ValueKey('rename-run-cancel'); +const runTitleErrorKey = ValueKey('rename-run-error'); + +/// The server's refusal, verbatim. Only a blank error gets a generic sentence +/// so the prompt never claims a rename that did not happen. +String describeTitleError(Object error) { + final message = '$error'; + return message.trim().isEmpty + ? 'The server did not rename the run.' + : message; +} diff --git a/app/notes/R2d.md b/app/notes/R2d.md new file mode 100644 index 00000000..c262351f --- /dev/null +++ b/app/notes/R2d.md @@ -0,0 +1,93 @@ +# R2d — native run title rename + +## What changed + +New `lib/features/runs/actions/title*` slice plus its tests and this note. No +existing source file was edited. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/runs/actions/title_wording.dart` | 24 | Web-verbatim words, test keys, refusal wording | +| `lib/features/runs/actions/title_dialog.dart` | 183 | Native Material/Cupertino text-field prompt and inline refusal | +| `lib/features/runs/actions/title_action.dart` | 109 | `RunTitleAction`, stored-title seeding, send/deliver orchestration | +| `test/features/runs/actions/title_test_support.dart` | 110 | Fake gateway, run fixtures, stateful host, app wrappers | +| `test/features/runs/actions/title_action_test.dart` | 244 | Both-platform open/cancel/exact-save and stored-title seeding | +| `test/features/runs/actions/title_resilience_test.dart` | 243 | Refusal retention, double save, disposal, stale owner, 2x/narrow | + +`RunTitleAction(run: …, gateway: …, onRunChanged: …)` renders one native +`OutlinedButton` (`Rename`) on Material and one plain `CupertinoButton` on +Cupertino, and nothing for a run without a numeric id. Platform style follows the +enclosing app (`MaterialLocalizations` presence). No style overrides, fixed +component sizes or new dependencies. + +## Behaviour and web parity + +The prompt is seeded with the run's actual stored title exactly as the browser +reads it, `String(d.title ?? "")` in `web/src/views/runDetail.js`. It is never +derived from `input.prompt`, stage output or a placeholder. A missing title seeds +an empty field. + +Typing, opening and the dismiss action send nothing. Only `Save` calls the +existing `RunsRepository.setRunTitle(id, title)`, which sends the exact envelope: + +``` +set_run_title {"run_id": , "title": } +``` + +The field text is passed through untrimmed, matching `repo.setRunTitle(id, +String(state.renameValue ?? ""))` in `web/src/repository.js`. Leading/trailing +spaces and Unicode are preserved, and a blank title is sent as `""` so the server, +not the client, decides whether it is acceptable. There is no local +`canSubmit` gate on blank text. + +A refusal (including a blank-title refusal) is shown verbatim below the field and +the prompt stays open with the typed draft intact. Nothing is updated locally. +Only an accepted reply closes the prompt and passes the server's returned +`run_detail` once through `onRunChanged`; the action never fabricates a run or a +title. A second Save tap while sending is ignored, both dialog actions disable +until the reply, and every asynchronous resume checks `mounted`. A reply for a run +the widget no longer owns is dropped. + +## Checks actually run + +``` +dart format lib/features/runs/actions/title*.dart \ + test/features/runs/actions/title*.dart # clean +flutter analyze # No issues found! +flutter test test/features/runs/actions/title_action_test.dart \ + test/features/runs/actions/title_resilience_test.dart # 11 passed +flutter test test/features/runs # 45 passed +flutter test # 63 passed +flutter build web # Built build/web (16.2s) +``` + +Focused acceptance coverage: + +- both platforms: native button and dialog, stored title in the field, typing and + Cancel produce zero gateway calls, Save sends exact `set_run_title` fields; +- exact field values: Unicode plus leading/trailing whitespace preserved; blank + title sent as `""` and the server refusal shown with the blank draft retained; +- failed save: server words verbatim, draft retained, dialog open, no callback and + no local title change; transport failure likewise; +- double Save: one request, action buttons disabled while in flight; +- disposal: a late reply after the tree is replaced throws nothing and delivers + nothing; a reply after the widget's run id changes is not delivered; +- 320x480 at 2x text: both prompts open, show a long title and a refusal, and close + with no rendering exception; +- malformed run: no rename button, and the stored-title helper ignores prompts. + +## Honest limits + +- **Not wired into a run-detail screen.** This branch has no run-detail screen or + controller; the manager owns integration. No real browser interaction or + capture was performed, so rendered feature parity is not claimed. `flutter build + web` proves compilation of the existing entrypoint, not that this widget is + reachable or visible. +- **Mobile unverified.** No Android/iOS build, emulator, ADB or device was used. + Source uses portable Flutter/Cupertino/Material widgets only. +- No real server, operator run or chat was touched. Tests use a local fake gateway + with no socket. +- No repository/domain/controller/shell/main/pubspec, `web/`, Go server, + installer or deployment file was changed. +- Nothing was committed, pushed or deployed; the files above are the candidate in + the working tree, per the stage instruction not to commit. diff --git a/app/test/features/runs/actions/title_action_test.dart b/app/test/features/runs/actions/title_action_test.dart new file mode 100644 index 00000000..110fda20 --- /dev/null +++ b/app/test/features/runs/actions/title_action_test.dart @@ -0,0 +1,244 @@ +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_action.dart'; +import 'package:pipelines_app/features/runs/actions/title_wording.dart'; + +import 'title_test_support.dart'; + +String _materialFieldText(WidgetTester tester) => + tester.widget(find.byKey(runTitleFieldKey)).controller!.text; + +String _cupertinoFieldText(WidgetTester tester) => tester + .widget(find.byKey(runTitleFieldKey)) + .controller! + .text; + +void main() { + testWidgets( + 'material rename starts from the stored title, typing sends nothing, ' + 'Cancel sends nothing and Save sends the exact text', + (tester) async { + final accepted = renamedRun(title: 'Release build'); + final gateway = FakeTitleGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await tester.pumpWidget( + titleApp( + TitleHost(gateway: gateway, initial: titledRun(), changed: changed), + cupertino: false, + ), + ); + + expect(find.byKey(runTitleActionKey), findsOneWidget); + expect(find.byType(OutlinedButton), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsOneWidget); + expect(find.text(runTitleDialogTitle), findsWidgets); + expect(find.text(runTitleFieldLabel), findsOneWidget); + expect(_materialFieldText(tester), 'Nightly build'); + + await tester.enterText( + find.byKey(runTitleFieldKey), + ' 发布 🚀 — nightly ', + ); + await tester.pump(); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(runTitleCancelKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(gateway.calls, isEmpty); + expect(changed, isEmpty); + expect( + tester.widget(find.byKey(titleHostTitleKey)).data, + 'Nightly build', + ); + + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + expect(_materialFieldText(tester), 'Nightly build'); + await tester.enterText( + find.byKey(runTitleFieldKey), + ' 发布 🚀 — nightly ', + ); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['set_run_title']); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'title': ' 发布 🚀 — nightly ', + }); + expect(changed.single, equals(accepted)); + expect(find.byType(AlertDialog), findsNothing); + expect( + tester.widget(find.byKey(titleHostTitleKey)).data, + 'Release build', + ); + }, + ); + + testWidgets('cupertino rename is native and sends only on Save', ( + tester, + ) async { + final accepted = renamedRun(title: 'Release build'); + final gateway = FakeTitleGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await tester.pumpWidget( + titleApp( + TitleHost(gateway: gateway, initial: titledRun(), changed: changed), + cupertino: true, + ), + ); + + expect(find.byKey(runTitleActionKey), findsOneWidget); + expect(find.byType(CupertinoButton), findsOneWidget); + expect(find.byType(OutlinedButton), findsNothing); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.byType(AlertDialog), findsNothing); + expect(_cupertinoFieldText(tester), 'Nightly build'); + + await tester.enterText(find.byKey(runTitleFieldKey), 'Typed only'); + await tester.pump(); + expect(gateway.calls, isEmpty); + await tester.tap(find.byKey(runTitleCancelKey)); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoAlertDialog), findsNothing); + expect(gateway.calls, isEmpty); + + 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.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['set_run_title']); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'title': 'Release build', + }); + expect(changed.single, equals(accepted)); + expect(find.byType(CupertinoAlertDialog), findsNothing); + }); + + testWidgets('a blank title is sent exactly and the server refusal is shown', ( + tester, + ) async { + const refusal = 'title must not be blank'; + final gateway = FakeTitleGateway( + (type, fields) async => throw const ProtocolError(refusal), + ); + final changed = []; + await tester.pumpWidget( + titleApp( + TitleHost(gateway: gateway, initial: titledRun(), changed: changed), + cupertino: false, + ), + ); + + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + await tester.enterText(find.byKey(runTitleFieldKey), ''); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.single.fields, {'run_id': 7, 'title': ''}); + expect(find.text(refusal), findsOneWidget); + expect(find.byKey(runTitleErrorKey), findsOneWidget); + expect(_materialFieldText(tester), ''); + expect(find.byType(AlertDialog), findsOneWidget); + expect(changed, isEmpty); + expect( + tester.widget(find.byKey(titleHostTitleKey)).data, + 'Nightly build', + ); + expect( + tester.widget(find.byKey(runTitleSaveKey)).onPressed, + isNotNull, + ); + }); + + testWidgets('the prompt is seeded from the stored title, never the prompt', ( + tester, + ) async { + final gateway = FakeTitleGateway( + (type, fields) async => {'run_detail': titledRun()}, + ); + final changed = []; + + await tester.pumpWidget( + titleApp( + TitleHost( + gateway: gateway, + initial: titledRun( + title: 'Stored title', + prompt: 'prompt fallback must not appear', + ), + changed: changed, + ), + cupertino: false, + ), + ); + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + expect(_materialFieldText(tester), 'Stored title'); + expect(find.text('prompt fallback must not appear'), findsNothing); + await tester.tap(find.byKey(runTitleCancelKey)); + await tester.pumpAndSettle(); + + await tester.pumpWidget( + titleApp( + TitleHost( + gateway: gateway, + initial: titledRun(title: null, prompt: 'prompt is not a title'), + changed: changed, + ), + cupertino: false, + ), + ); + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + expect(_materialFieldText(tester), ''); + expect(find.text('prompt is not a title'), findsNothing); + await tester.tap(find.byKey(runTitleCancelKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls, isEmpty); + expect(changed, isEmpty); + }); + + testWidgets('a malformed run has no rename entry point', (tester) async { + final gateway = FakeTitleGateway( + (type, fields) async => {'run_detail': titledRun()}, + ); + await tester.pumpWidget( + titleApp( + TitleHost( + gateway: gateway, + initial: {'title': 'No id'}, + changed: [], + ), + cupertino: false, + ), + ); + + expect(find.byKey(runTitleActionKey), findsNothing); + expect(gateway.calls, isEmpty); + expect(runTitleId({'title': 'No id'}), isNull); + expect(storedRunTitle({'title': 'Kept'}), 'Kept'); + expect(storedRunTitle({}), ''); + }); +} diff --git a/app/test/features/runs/actions/title_resilience_test.dart b/app/test/features/runs/actions/title_resilience_test.dart new file mode 100644 index 00000000..32a566c3 --- /dev/null +++ b/app/test/features/runs/actions/title_resilience_test.dart @@ -0,0 +1,243 @@ +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 'title_test_support.dart'; + +Future _pump( + WidgetTester tester, + FakeTitleGateway gateway, + List changed, { + bool cupertino = false, + double textScale = 1, + JsonMap? run, +}) async { + await tester.pumpWidget( + titleApp( + TitleHost( + gateway: gateway, + initial: run ?? titledRun(), + changed: changed, + ), + cupertino: cupertino, + textScale: textScale, + ), + ); +} + +Future _open(WidgetTester tester) async { + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); +} + +String _fieldText(WidgetTester tester, {required bool cupertino}) { + if (cupertino) { + return tester + .widget(find.byKey(runTitleFieldKey)) + .controller! + .text; + } + return tester + .widget(find.byKey(runTitleFieldKey)) + .controller! + .text; +} + +void main() { + testWidgets('a failed save keeps the prompt open with the draft intact', ( + tester, + ) async { + const refusal = 'rename refused: the run is locked'; + final gateway = FakeTitleGateway( + (type, fields) async => throw const ProtocolError(refusal), + ); + final changed = []; + await _pump(tester, gateway, changed); + + await _open(tester); + await tester.enterText(find.byKey(runTitleFieldKey), ' Renamed draft '); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['set_run_title']); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'title': ' Renamed draft ', + }); + expect(find.text(refusal), findsOneWidget); + expect(find.byKey(runTitleErrorKey), findsOneWidget); + expect(_fieldText(tester, cupertino: false), ' Renamed draft '); + expect(find.byType(AlertDialog), findsOneWidget); + expect(changed, isEmpty); + expect( + tester.widget(find.byKey(titleHostTitleKey)).data, + 'Nightly build', + ); + }); + + testWidgets('a transport failure keeps the server words and the draft', ( + tester, + ) async { + final gateway = FakeTitleGateway( + (type, fields) async => throw const NotConnectedError(), + ); + final changed = []; + await _pump(tester, gateway, changed, cupertino: true); + + await _open(tester); + await tester.enterText(find.byKey(runTitleFieldKey), 'Unsent title'); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + + expect(find.byKey(runTitleErrorKey), findsOneWidget); + expect(_fieldText(tester, cupertino: true), 'Unsent title'); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(changed, isEmpty); + }); + + testWidgets('Save cannot send twice while the rename is in flight', ( + tester, + ) async { + final reply = Completer(); + final gateway = FakeTitleGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + + await _open(tester); + await tester.enterText(find.byKey(runTitleFieldKey), 'One title'); + final save = find.byKey(runTitleSaveKey); + await tester.tap(save); + await tester.tap(save); + await tester.pump(); + + expect( + gateway.calls.where((call) => call.type == 'set_run_title'), + hasLength(1), + ); + expect(tester.widget(save).onPressed, isNull); + expect( + tester.widget(find.byKey(runTitleCancelKey)).onPressed, + isNull, + ); + expect(find.byType(AlertDialog), findsOneWidget); + + reply.complete({'run_detail': renamedRun(title: 'One title')}); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(changed, hasLength(1)); + expect(changed.single['title'], 'One title'); + }); + + testWidgets('a late reply after disposal is ignored safely', (tester) async { + final reply = Completer(); + final gateway = FakeTitleGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + + await _open(tester); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pump(); + expect(gateway.calls, hasLength(1)); + + await tester.pumpWidget(const SizedBox()); + reply.complete({'run_detail': renamedRun()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + + testWidgets('a reply for a run the widget no longer owns is not delivered', ( + tester, + ) async { + final reply = Completer(); + final gateway = FakeTitleGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + + await _open(tester); + await tester.enterText(find.byKey(runTitleFieldKey), 'Run seven title'); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pump(); + + await tester.pumpWidget( + titleApp( + TitleHost( + gateway: gateway, + initial: titledRun(id: 8, title: 'Another run'), + changed: changed, + ), + cupertino: false, + ), + ); + await tester.pump(); + reply.complete({'run_detail': renamedRun(title: 'Run seven title')}); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'title': 'Run seven title', + }); + expect(changed, isEmpty); + expect( + tester.widget(find.byKey(titleHostTitleKey)).data, + 'Another run', + ); + }); + + testWidgets('both prompts fit 2x text at a narrow width', (tester) async { + tester.view.physicalSize = const Size(320, 480); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + const refusal = 'the title is too long for this run; shorten it'; + for (final cupertino in [false, true]) { + final gateway = FakeTitleGateway( + (type, fields) async => throw const ProtocolError(refusal), + ); + await _pump( + tester, + gateway, + [], + cupertino: cupertino, + textScale: 2, + ); + await _open(tester); + + expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino'); + expect( + cupertino + ? find.byType(CupertinoAlertDialog) + : find.byType(AlertDialog), + findsOneWidget, + ); + expect(find.text(runTitleFieldLabel), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.enterText( + find.byKey(runTitleFieldKey), + 'A deliberately long title that must scroll rather than overflow', + ); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino'); + expect(find.text(refusal), findsOneWidget); + expect( + _fieldText(tester, cupertino: cupertino), + 'A deliberately long title that must scroll rather than overflow', + ); + + await tester.tap(find.byKey(runTitleCancelKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byType(CupertinoAlertDialog), findsNothing); + } + }); +} diff --git a/app/test/features/runs/actions/title_test_support.dart b/app/test/features/runs/actions/title_test_support.dart new file mode 100644 index 00000000..b566a2d8 --- /dev/null +++ b/app/test/features/runs/actions/title_test_support.dart @@ -0,0 +1,110 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/actions/title_action.dart'; + +typedef TitleHandler = Future Function(String type, JsonMap fields); + +/// A fake gateway that records every request and never owns a socket. +class FakeTitleGateway implements ApiGateway { + FakeTitleGateway(this.handler); + + final TitleHandler handler; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) { + final copy = Map.from(fields); + calls.add((type: type, fields: copy)); + return handler(type, copy); + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap titledRun({ + num id = 7, + String? title = 'Nightly build', + String status = 'succeeded', + String prompt = 'the submitted prompt', +}) => { + 'id': id, + 'title': title, + 'status': status, + 'input': {'prompt': prompt}, +}; + +JsonMap renamedRun({num id = 7, String title = 'Release build'}) => + titledRun(id: id, title: title, status: 'succeeded'); + +/// Owns the run like a run-detail screen would, so the callback's returned +/// server detail is what the action renders next. Re-pumping with a different +/// initial run updates the action in place, as a refreshed detail does. +class TitleHost extends StatefulWidget { + const TitleHost({ + super.key, + required this.gateway, + required this.initial, + required this.changed, + }); + + final FakeTitleGateway gateway; + final JsonMap initial; + final List changed; + + @override + State createState() => _TitleHostState(); +} + +class _TitleHostState extends State { + late JsonMap _run = widget.initial; + + @override + void didUpdateWidget(covariant TitleHost oldWidget) { + super.didUpdateWidget(oldWidget); + if (!identical(oldWidget.initial, widget.initial)) { + _run = widget.initial; + } + } + + @override + Widget build(BuildContext context) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text('${_run['title'] ?? ''}', key: titleHostTitleKey), + RunTitleAction( + run: _run, + gateway: widget.gateway, + onRunChanged: (run) { + widget.changed.add(run); + setState(() => _run = run); + }, + ), + ], + ); + } +} + +const titleHostTitleKey = ValueKey('rename-host-title'); + +Widget titleApp(Widget child, {required bool cupertino, double textScale = 1}) { + Widget media(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + final body = Center(child: child); + if (cupertino) { + return CupertinoApp( + builder: media, + home: CupertinoPageScaffold(child: body), + ); + } + return MaterialApp( + builder: media, + home: Scaffold(body: body), + ); +} From b9639650e5a7660dd93b210c47951c42703fd592 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 15:15:47 +0100 Subject: [PATCH 41/84] feat(app): add saved-schedule repository and domain record Port the web client's list/save/delete schedule request shapes and reply checks, with a typed record that preserves the whole server payload including unknown fields. Revision stays the CAS token; server refusals propagate unchanged. --- app/.gitignore | 5 +- .../schedules/data/schedules_repository.dart | 116 +++++++++++++++ .../schedules/domain/saved_schedule.dart | 87 ++++++++++++ .../schedules/domain/schedule_json.dart | 22 +++ .../schedules/domain/schedule_rule.dart | 41 ++++++ app/notes/S1a.md | 94 +++++++++++++ .../data/saved_schedule_record_test.dart | 101 ++++++++++++++ .../schedules/data/schedule_test_support.dart | 83 +++++++++++ .../schedules/data/schedules_delete_test.dart | 131 +++++++++++++++++ .../data/schedules_protocol_bounds_test.dart | 81 +++++++++++ .../data/schedules_repository_test.dart | 132 ++++++++++++++++++ 11 files changed, 892 insertions(+), 1 deletion(-) create mode 100644 app/lib/features/schedules/data/schedules_repository.dart create mode 100644 app/lib/features/schedules/domain/saved_schedule.dart create mode 100644 app/lib/features/schedules/domain/schedule_json.dart create mode 100644 app/lib/features/schedules/domain/schedule_rule.dart create mode 100644 app/notes/S1a.md create mode 100644 app/test/features/schedules/data/saved_schedule_record_test.dart create mode 100644 app/test/features/schedules/data/schedule_test_support.dart create mode 100644 app/test/features/schedules/data/schedules_delete_test.dart create mode 100644 app/test/features/schedules/data/schedules_protocol_bounds_test.dart create mode 100644 app/test/features/schedules/data/schedules_repository_test.dart diff --git a/app/.gitignore b/app/.gitignore index 9f91cbac..371e9bd8 100644 --- a/app/.gitignore +++ b/app/.gitignore @@ -45,6 +45,9 @@ app.*.map.json /android/app/release # The repository ignores runtime data/ directories. Feature repository source -# is code, not runtime data, and must be included in fresh checkouts. +# and its tests are code, not runtime data, and must be included in fresh +# checkouts. !/lib/**/data/ !/lib/**/data/** +!/test/**/data/ +!/test/**/data/** diff --git a/app/lib/features/schedules/data/schedules_repository.dart b/app/lib/features/schedules/data/schedules_repository.dart new file mode 100644 index 00000000..432bf841 --- /dev/null +++ b/app/lib/features/schedules/data/schedules_repository.dart @@ -0,0 +1,116 @@ +import '../../../core/api_gateway.dart'; +import '../domain/saved_schedule.dart'; +import '../domain/schedule_json.dart'; + +/// Client-side protocol failure. Server refusals and transport errors are not +/// wrapped: [ApiGateway] already surfaces their exact text. +class SchedulesRepositoryException implements Exception { + const SchedulesRepositoryException(this.message); + final String message; + @override + String toString() => message; +} + +/// The saved-schedule commands of the current web client. +/// +/// These are run configurations, not pipeline definitions: this repository +/// never submits, validates or publishes a workflow, and it never starts or +/// polls a run. Timer execution belongs to the server. +class SchedulesRepository { + SchedulesRepository(this._gateway); + + final ApiGateway _gateway; + + /// Lists saved schedules, optionally for one pipeline. + /// + /// An explicit empty reply is a valid empty list. A reply without the + /// `schedules` type is not: that is an older/unsupported server and must be + /// reported rather than shown as "no schedules". + Future> listSchedules({int? pipelineId}) async { + final fields = {}; + if (pipelineId != null) { + if (!_isPositiveId(pipelineId)) { + throw const SchedulesRepositoryException( + 'A positive pipeline ID is required.', + ); + } + fields['pipeline_id'] = pipelineId; + } + final reply = await _gateway.call('list_schedules', fields); + final schedules = reply['schedules']; + if (reply['type'] != 'schedules' || + (schedules != null && schedules is! List)) { + throw const SchedulesRepositoryException( + 'The server returned no schedules response.', + ); + } + if (schedules == null) return const []; + return [ + for (final item in schedules as List) + if (item is Map) + SavedSchedule(Map.from(item)) + else + throw const SchedulesRepositoryException( + 'The server returned an invalid schedule record.', + ), + ]; + } + + /// Creates or updates one saved schedule. + /// + /// Creation sends the web client's sentinel record (`id` 0, no revision) and + /// may carry a stable request key so a lost reply is retried instead of + /// creating a duplicate. Updating sends the record read from the server, + /// whose `revision` is the compare-and-swap token; the key is omitted, as in + /// the web client. A stale revision is refused by the server and propagated + /// unchanged, never overwritten locally. + Future saveSchedule( + JsonMap schedule, { + String? requestKey, + }) async { + if (requestKey != null && requestKey.length > 128) { + throw const SchedulesRepositoryException( + 'Schedule request keys must be strings of at most 128 characters.', + ); + } + final fields = {'schedule': cloneJsonMap(schedule)}; + if (requestKey != null && requestKey.isNotEmpty) { + fields['request_key'] = requestKey; + } + final reply = await _gateway.call('save_schedule', fields); + final saved = reply['schedule']; + if (saved is! Map) { + throw const SchedulesRepositoryException( + 'The server returned no saved schedule.', + ); + } + return SavedSchedule(Map.from(saved)); + } + + /// Deletes exactly the revision the caller read. + /// + /// Both identity and revision are required before any request is sent; a + /// confirmation for a different schedule is treated as a failed delete. + Future deleteSchedule(int id, int revision) async { + if (!_isPositiveId(id) || !_isPositiveId(revision)) { + throw const SchedulesRepositoryException( + 'An exact schedule ID and revision are required.', + ); + } + final reply = await _gateway.call('delete_schedule', { + 'schedule_id': id, + 'expected_revision': revision, + }); + if (reply['type'] != 'schedule_deleted' || reply['schedule_id'] != id) { + throw const SchedulesRepositoryException( + 'The server did not confirm deletion of this schedule.', + ); + } + } +} + +/// JSON/JavaScript integers are safe up to 2^53-1; the web client checks +/// `Number.isSafeInteger` before sending an identity. +const _maxSafeInteger = 9007199254740991; + +bool _isPositiveId(int value) => value > 0 && value <= _maxSafeInteger; diff --git a/app/lib/features/schedules/domain/saved_schedule.dart b/app/lib/features/schedules/domain/saved_schedule.dart new file mode 100644 index 00000000..32570b72 --- /dev/null +++ b/app/lib/features/schedules/domain/saved_schedule.dart @@ -0,0 +1,87 @@ +import '../../../core/api_gateway.dart'; +import 'schedule_json.dart'; +import 'schedule_rule.dart'; + +/// One saved run configuration from `list_schedules` or `save_schedule`. +/// +/// A saved schedule is a complete run request pinned to one pipeline version. +/// It is deliberately not a pipeline definition: nothing here is published, +/// validated as a graph or treated as the pipeline's current version. +/// +/// [raw] keeps the exact server record, including fields this client does not +/// know yet. Typed getters are views; they never rewrite [raw]. +class SavedSchedule { + SavedSchedule(JsonMap raw) : raw = cloneJsonMap(raw); + + final JsonMap raw; + + /// Server identity; null when an older reply omits it. Never defaulted to 0, + /// because 0 is the create sentinel rather than a saved identity. + int? get id => _integer(raw['id']); + + /// Compare-and-swap token. Updates reuse it and deletes send it as + /// `expected_revision`; this client never invents or increments it. + int? get revision => _integer(raw['revision']); + + int? get pipelineId => _integer(raw['pipeline_id']); + int? get version => _integer(raw['version']); + String get name => _text(raw['name']); + bool get enabled => raw['enabled'] == true; + + JsonMap get input => _map(raw['input']); + String get prompt => _text(input['prompt']); + String get workspace => _text(raw['workspace']); + ScheduleRule get rule => ScheduleRule(_map(raw['rule'])); + + List get writePaths => _texts(raw['write_paths']); + bool get allowTools => raw['allow_tools'] == true; + String get model => _text(raw['model']); + Map get stageModels => { + for (final entry in _map(raw['stage_models']).entries) + if (entry.value is String) entry.key: entry.value as String, + }; + String get notifyMode => _text(raw['notify_mode']); + String get title => _text(raw['title']); + String get outputFormat => _text(raw['output_format']); + + String get nextDue => _text(raw['next_due']); + String get createdAt => _text(raw['created_at']); + String get updatedAt => _text(raw['updated_at']); + + /// The record to pass to `save_schedule`, deep-copied so callers cannot + /// mutate this snapshot by aliasing. + JsonMap toJson() => cloneJsonMap(raw); + + /// Pause/enable copy. Identity, revision and every unknown field are kept so + /// the update still targets the revision this record was read at. + SavedSchedule withEnabled(bool value) { + final copy = toJson(); + copy['enabled'] = value; + return SavedSchedule(copy); + } +} + +int? _integer(dynamic value) { + if (value is int) return value; + if (value is num && value.isFinite && value == value.truncateToDouble()) { + return value.toInt(); + } + return null; +} + +String _text(dynamic value) => value is String ? value : ''; + +JsonMap _map(dynamic value) { + if (value is! Map) return {}; + return { + for (final entry in value.entries) + '${entry.key}': cloneJsonValue(entry.value), + }; +} + +List _texts(dynamic value) => value is List + ? [ + for (final item in value) + if (item is String) item, + ] + : const []; diff --git a/app/lib/features/schedules/domain/schedule_json.dart b/app/lib/features/schedules/domain/schedule_json.dart new file mode 100644 index 00000000..a0e541bf --- /dev/null +++ b/app/lib/features/schedules/domain/schedule_json.dart @@ -0,0 +1,22 @@ +import '../../../core/api_gateway.dart'; + +/// Deep copy of a decoded JSON value. +/// +/// Saved schedules travel back to the server unchanged, so unknown fields (and +/// unknown nested values) must survive every round trip without sharing state +/// with the reply map that produced them. +dynamic cloneJsonValue(dynamic value) { + if (value is Map) { + return { + for (final entry in value.entries) + '${entry.key}': cloneJsonValue(entry.value), + }; + } + if (value is List) { + return [for (final item in value) cloneJsonValue(item)]; + } + return value; +} + +JsonMap cloneJsonMap(JsonMap value) => + Map.from(cloneJsonValue(value) as Map); diff --git a/app/lib/features/schedules/domain/schedule_rule.dart b/app/lib/features/schedules/domain/schedule_rule.dart new file mode 100644 index 00000000..7eb4bed5 --- /dev/null +++ b/app/lib/features/schedules/domain/schedule_rule.dart @@ -0,0 +1,41 @@ +import '../../../core/api_gateway.dart'; +import 'schedule_json.dart'; + +/// Weekday keys the server accepts for an interval rule. +const scheduleDays = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']; + +/// The timer part of a saved schedule (`rule` on the wire). +/// +/// This is a view over the decoded server record, not a timer implementation: +/// it never calculates due times, converts timezones or starts runs. Unknown +/// rule fields stay in [raw] and are returned by [toJson]. +class ScheduleRule { + ScheduleRule([JsonMap? raw]) : raw = cloneJsonMap(raw ?? const {}); + + final JsonMap raw; + + /// Go-style duration such as `24h` or `1h30m`; empty for a clock rule. + String get every => _text(raw['every']); + + /// Distinct 24-hour times such as `09:00`; empty for an interval rule. + List get times => _texts(raw['times']); + + /// Empty means every day (written as absent on the wire). + List get days => _texts(raw['days']); + + /// Empty or `Local` means the server's timezone. + String get timezone => _text(raw['timezone']); + + bool get isClock => times.isNotEmpty; + + JsonMap toJson() => cloneJsonMap(raw); +} + +String _text(dynamic value) => value is String ? value : ''; + +List _texts(dynamic value) => value is List + ? [ + for (final item in value) + if (item is String) item, + ] + : const []; diff --git a/app/notes/S1a.md b/app/notes/S1a.md new file mode 100644 index 00000000..58426e32 --- /dev/null +++ b/app/notes/S1a.md @@ -0,0 +1,94 @@ +# S1a — saved-schedule repository and record + +## What changed + +New, app-only files (no existing feature, shell, transport, `main` or pubspec +source edited): + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/schedules/data/schedules_repository.dart` | 116 | `list_schedules`, `save_schedule`, `delete_schedule` envelopes and reply checks | +| `lib/features/schedules/domain/saved_schedule.dart` | 87 | typed view over one saved run configuration; exact raw record retained | +| `lib/features/schedules/domain/schedule_rule.dart` | 41 | interval/clock/timezone/weekday fields of `rule` | +| `lib/features/schedules/domain/schedule_json.dart` | 22 | deep JSON copy used by every round trip | +| `test/features/schedules/data/schedules_repository_test.dart` | 132 | list/create/update envelopes, unchanged input, CAS revision | +| `test/features/schedules/data/schedules_delete_test.dart` | 131 | delete envelope, confirmations, refusals, missing/empty replies | +| `test/features/schedules/data/schedules_protocol_bounds_test.dart` | 81 | web-mirrored ID/revision/request-key bounds | +| `test/features/schedules/data/saved_schedule_record_test.dart` | 101 | provenance, unknown fields, deep-copy and absent-field behavior | +| `test/features/schedules/data/schedule_test_support.dart` | 83 | recording fake gateway and server-shaped fixtures | + +`app/.gitignore` also gained the missing `!/test/**/data/` exception. The root +`.gitignore` ignores every `data/` directory, so without it these assigned tests +would silently disappear from a fresh checkout. The existing `!/lib/**/data/` +exception is for the same reason. + +## Behavior copied from the current web client + +Requests are exactly the ones in `web/src/repository.js`: + +- `list_schedules` with no field, or `pipeline_id` for one pipeline. A positive + safe integer is required before sending; `{type:"schedules"}` or + `schedules:null` is an empty list, while a reply without `type:"schedules"` is + an error, not "no schedules". +- `save_schedule` with `schedule` unchanged. A non-empty `request_key` (at most + 128 characters) is added only for a create retry; updates omit it, as the web + editor does. Creation keeps the web sentinel `id: 0` and no revision. Updates + send the record read from the server, whose `revision` is the server's + compare-and-swap token. The reply is only accepted when it contains + `schedule`. +- `delete_schedule` with exactly `schedule_id` and `expected_revision`; only + `{type:"schedule_deleted", schedule_id:}` counts as success. + +Server refusals are not wrapped or translated. `ApiGateway` already turns an +`error` envelope into `ProtocolError` with the server's text, and the repository +lets that object through unchanged (conflict and unknown-command coverage in +`server refusals and conflicts propagate verbatim`). The repository has no +capability flags, no "not supported" substitution and no local fallback. + +Saved schedules are run configurations, never pipeline definitions. `SavedSchedule` +keeps the complete server map, including unknown future nested fields, and +exposes pipeline, version, prompt/input, workspace, rule (every/times/days/ +timezone), enabled, model/stage models, notify mode, write paths/tools, title, +output format, due time and timestamps. `toJson()` is a deep copy; `withEnabled` +preserves identity, revision and unknowns. Missing identity/revision stays +`null` rather than becoming a fabricated `0`. There is no timer execution, +polling, rule parsing into due dates or timezone conversion in this slice. + +## Checks actually run + +``` +flutter pub get +dart format lib/features/schedules test/features/schedules # 9 files, 5 changed, then clean +flutter test test/features/schedules/data # 18 passed +flutter analyze # No issues found! (1.4s) +flutter test # 70 passed +``` + +Focused coverage maps to the requested acceptance: + +- exact `list_schedules`/`save_schedule`/`delete_schedule` bodies recorded by a + fake gateway, including `expected_revision` only on delete and no invented + create revision/key; +- untouched caller record on save; deep equality of returned records with the + server reply including unknown top-level/rule/input fields; +- update reuses revision 3, accepts server revision 4 and leaves the stale draft + at 3; a mismatch is the server's refusal, propagated verbatim; +- empty list vs missing/unsupported schedules reply, missing/invalid saved + schedule, and delete confirmation for the wrong id/type; +- preflight bounds match the web client: pipeline id, schedule id, revision and + 129-character request keys send nothing; 128 characters is accepted; +- no fabricated identity when a reply contains an empty schedule object. + +## Honest limits + +- **No UI or wiring.** There is no schedules screen, editor, pause/delete control + or shell registration in this slice; the manager owns later UI integration. + No browser interaction or screenshot applies to this nonvisual item. +- **No live server used.** All checks use local recording fakes; no production + schedule, run or workflow was created, changed or deleted. No polling or + scheduler was touched. +- **Mobile unverified.** Only web-targeted Flutter tests and analysis ran. No + Android/iOS build, emulator, ADB or device was used; the code is pure Dart. +- **Not committed.** The stage instruction for this visit forbids commit, push + and deploy, so the candidate remains in the `flutter/s1-data` worktree for the + manager to inspect and commit. No deployment or preview was performed. diff --git a/app/test/features/schedules/data/saved_schedule_record_test.dart b/app/test/features/schedules/data/saved_schedule_record_test.dart new file mode 100644 index 00000000..aef17fe6 --- /dev/null +++ b/app/test/features/schedules/data/saved_schedule_record_test.dart @@ -0,0 +1,101 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/schedules/domain/saved_schedule.dart'; + +import 'schedule_test_support.dart'; + +void main() { + test('saved schedule exposes run-configuration provenance', () { + final schedule = SavedSchedule(savedRecord()); + + expect(schedule.id, 8); + expect(schedule.revision, 3); + expect(schedule.pipelineId, 4); + expect(schedule.version, 2); + expect(schedule.name, 'Research batteries'); + expect(schedule.enabled, isTrue); + expect(schedule.prompt, 'Research batteries'); + expect(schedule.input['custom'], {'nested': 'kept'}); + expect(schedule.workspace, '/srv/research'); + expect(schedule.writePaths, ['reports/research.md']); + expect(schedule.allowTools, isTrue); + expect(schedule.model, 'openai/gpt-5'); + expect(schedule.stageModels, {'one': 'openai/gpt-5'}); + expect(schedule.notifyMode, 'off'); + expect(schedule.title, 'Battery research'); + expect(schedule.outputFormat, 'markdown'); + expect(schedule.rule.every, '24h'); + expect(schedule.rule.days, ['mon', 'wed']); + expect(schedule.rule.timezone, 'Europe/London'); + expect(schedule.rule.isClock, isFalse); + expect(schedule.nextDue, '2026-10-22T09:00:00Z'); + expect(schedule.createdAt, '2026-10-20T09:00:00Z'); + expect(schedule.updatedAt, '2026-10-21T09:00:00Z'); + }); + + test('unknown fields survive the typed view and pause copy', () { + final schedule = SavedSchedule(savedRecord()); + final paused = schedule.withEnabled(false); + + expect(paused.enabled, isFalse); + expect(paused.id, 8); + expect(paused.revision, 3); + expect(paused.toJson()['future_server_field'], { + 'nested': [ + 1, + 2, + {'deep': true}, + ], + }); + expect(paused.toJson()['input'], { + 'prompt': 'Research batteries', + 'custom': {'nested': 'kept'}, + }); + expect(paused.toJson()['rule'], savedRecord()['rule']); + + // The original snapshot is untouched and still enabled. + expect(schedule.enabled, isTrue); + expect(schedule.revision, 3); + }); + + test('toJson is a deep copy, not an alias of the server reply', () { + final source = savedRecord(); + final schedule = SavedSchedule(source); + + final first = schedule.toJson(); + ((first['future_server_field'] as Map)['nested'] as List).add('changed'); + final second = schedule.toJson(); + expect((second['future_server_field'] as Map)['nested'], [ + 1, + 2, + {'deep': true}, + ]); + + final promptInput = schedule.input; + promptInput['custom'] = 'changed'; + expect(schedule.input['custom'], {'nested': 'kept'}); + }); + + test('missing fields stay absent instead of being fabricated', () { + final schedule = SavedSchedule(const {}); + + expect(schedule.id, isNull); + expect(schedule.revision, isNull); + expect(schedule.pipelineId, isNull); + expect(schedule.version, isNull); + expect(schedule.enabled, isFalse); + expect(schedule.prompt, ''); + expect(schedule.workspace, ''); + expect(schedule.rule.every, ''); + expect(schedule.rule.times, isEmpty); + expect(schedule.writePaths, isEmpty); + expect(schedule.stageModels, isEmpty); + expect(schedule.toJson(), isEmpty); + }); + + test('a fractional revision is not truncated into a false token', () { + final schedule = SavedSchedule(const {'id': 8, 'revision': 3.5}); + + expect(schedule.id, 8); + expect(schedule.revision, isNull); + }); +} diff --git a/app/test/features/schedules/data/schedule_test_support.dart b/app/test/features/schedules/data/schedule_test_support.dart new file mode 100644 index 00000000..f80b852f --- /dev/null +++ b/app/test/features/schedules/data/schedule_test_support.dart @@ -0,0 +1,83 @@ +import 'dart:convert'; + +import 'package:pipelines_app/core/api_gateway.dart'; + +class RecordedCall { + const RecordedCall(this.type, this.fields); + final String type; + final JsonMap fields; +} + +/// Records the exact request built by the repository and replays queued +/// replies. Both are deep-copied, so a test can prove the repository neither +/// mutated its input nor depended on alias mutation of a reply. +class RecordingGateway implements ApiGateway { + final calls = []; + final replies = []; + Object? failure; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add(RecordedCall(type, deepCopy(fields))); + if (failure case final error?) throw error; + if (replies.isEmpty) throw StateError('No recorded reply for $type'); + return deepCopy(replies.removeAt(0)); + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap deepCopy(JsonMap value) => jsonDecode(jsonEncode(value)) as JsonMap; + +/// A complete server record including fields this client does not interpret +/// yet, an unknown nested rule field and unknown input. +JsonMap savedRecord() => { + 'id': 8, + 'revision': 3, + 'name': 'Research batteries', + 'pipeline_id': 4, + 'version': 2, + 'enabled': true, + 'input': { + 'prompt': 'Research batteries', + 'custom': {'nested': 'kept'}, + }, + 'workspace': '/srv/research', + 'write_paths': ['reports/research.md'], + 'allow_tools': true, + 'model': 'openai/gpt-5', + 'stage_models': {'one': 'openai/gpt-5'}, + 'notify_mode': 'off', + 'title': 'Battery research', + 'output_format': 'markdown', + 'rule': { + 'every': '24h', + 'days': ['mon', 'wed'], + 'timezone': 'Europe/London', + 'future_rule_field': 'kept', + }, + 'next_due': '2026-10-22T09:00:00Z', + 'created_at': '2026-10-20T09:00:00Z', + 'updated_at': '2026-10-21T09:00:00Z', + 'future_server_field': { + 'nested': [ + 1, + 2, + {'deep': true}, + ], + }, +}; + +/// The create form of the record: id 0 is the server's create sentinel and no +/// revision has been issued yet. +JsonMap createRecord() => { + 'id': 0, + 'name': 'Research batteries', + 'pipeline_id': 4, + 'version': 2, + 'enabled': true, + 'input': {'prompt': 'Research batteries'}, + 'workspace': '/srv/research', + 'rule': {'every': '24h', 'timezone': 'Europe/London'}, +}; diff --git a/app/test/features/schedules/data/schedules_delete_test.dart b/app/test/features/schedules/data/schedules_delete_test.dart new file mode 100644 index 00000000..fc4f8d32 --- /dev/null +++ b/app/test/features/schedules/data/schedules_delete_test.dart @@ -0,0 +1,131 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/schedules/data/schedules_repository.dart'; + +import 'schedule_test_support.dart'; + +void main() { + test('delete sends the exact ID and expected revision', () async { + final gateway = RecordingGateway() + ..replies.add({'type': 'schedule_deleted', 'schedule_id': 8}); + final repository = SchedulesRepository(gateway); + + await repository.deleteSchedule(8, 3); + + expect(gateway.calls.single.type, 'delete_schedule'); + expect(gateway.calls.single.fields, { + 'schedule_id': 8, + 'expected_revision': 3, + }); + }); + + test('delete refuses a confirmation for anything else', () async { + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + for (final reply in [ + {}, + {'type': 'pong'}, + {'type': 'schedule_deleted'}, + {'type': 'schedule_deleted', 'schedule_id': 9}, + ]) { + gateway.replies.add(reply); + await expectLater( + repository.deleteSchedule(8, 3), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server did not confirm deletion of this schedule.', + ), + ), + ); + } + }); + + test('server refusals and conflicts propagate verbatim', () async { + final conflict = const ProtocolError( + 'schedule revision conflict; reload before editing', + ); + final recording = RecordingGateway()..failure = conflict; + final conflicting = SchedulesRepository(recording); + await expectLater( + conflicting.saveSchedule(createRecord()), + throwsA(same(conflict)), + ); + await expectLater( + conflicting.deleteSchedule(8, 3), + throwsA(same(conflict)), + ); + + final unsupported = const ProtocolError( + 'unknown message type: list_schedules', + ); + recording.failure = unsupported; + await expectLater( + conflicting.listSchedules(pipelineId: 4), + throwsA(same(unsupported)), + ); + }); + + test('missing and empty list replies are different facts', () async { + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + + gateway.replies.add({'type': 'schedules'}); + expect(await repository.listSchedules(), isEmpty); + + gateway.replies.add({'type': 'schedules', 'schedules': null}); + expect(await repository.listSchedules(), isEmpty); + + for (final reply in [ + {}, + {'type': 'pong'}, + {'type': 'schedules', 'schedules': {}}, + { + 'type': 'schedules', + 'schedules': ['not a record'], + }, + ]) { + gateway.replies.add(reply); + await expectLater( + repository.listSchedules(), + throwsA(isA()), + ); + } + }); + + test('save requires a saved schedule in the reply', () async { + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + for (final reply in [ + {}, + {'type': 'schedule'}, + {'type': 'schedule', 'schedule': null}, + {'type': 'schedule', 'schedule': 'record'}, + ]) { + gateway.replies.add(reply); + await expectLater( + repository.saveSchedule(createRecord()), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server returned no saved schedule.', + ), + ), + ); + } + }); + + test('an empty schedule object is not turned into a fake identity', () async { + final gateway = RecordingGateway() + ..replies.add({'type': 'schedule', 'schedule': {}}); + final repository = SchedulesRepository(gateway); + + final saved = await repository.saveSchedule(createRecord()); + + expect(saved.id, isNull); + expect(saved.revision, isNull); + expect(saved.toJson(), isEmpty); + }); +} diff --git a/app/test/features/schedules/data/schedules_protocol_bounds_test.dart b/app/test/features/schedules/data/schedules_protocol_bounds_test.dart new file mode 100644 index 00000000..db39b164 --- /dev/null +++ b/app/test/features/schedules/data/schedules_protocol_bounds_test.dart @@ -0,0 +1,81 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/schedules/data/schedules_repository.dart'; + +import 'schedule_test_support.dart'; + +void main() { + test( + 'list rejects non-positive and unsafe pipeline IDs before sending', + () async { + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + + for (final id in [0, -1, 9007199254740992]) { + await expectLater( + repository.listSchedules(pipelineId: id), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'A positive pipeline ID is required.', + ), + ), + ); + } + expect(gateway.calls, isEmpty); + }, + ); + + test( + 'delete rejects an inexact identity or revision before sending', + () async { + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + + for (final pair in [ + (0, 1), + (-1, 1), + (8, 0), + (8, -1), + (8, 9007199254740992), + ]) { + await expectLater( + repository.deleteSchedule(pair.$1, pair.$2), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'An exact schedule ID and revision are required.', + ), + ), + ); + } + expect(gateway.calls, isEmpty); + }, + ); + + test( + 'request keys are bounded at 128 characters like the web client', + () async { + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + + await expectLater( + repository.saveSchedule(createRecord(), requestKey: 'x' * 129), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'Schedule request keys must be strings of at most 128 characters.', + ), + ), + ); + expect(gateway.calls, isEmpty); + + final key = 'x' * 128; + gateway.replies.add({'type': 'schedule', 'schedule': savedRecord()}); + await repository.saveSchedule(createRecord(), requestKey: key); + expect(gateway.calls.single.fields['request_key'], key); + }, + ); +} diff --git a/app/test/features/schedules/data/schedules_repository_test.dart b/app/test/features/schedules/data/schedules_repository_test.dart new file mode 100644 index 00000000..8ac1ef4c --- /dev/null +++ b/app/test/features/schedules/data/schedules_repository_test.dart @@ -0,0 +1,132 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/schedules/data/schedules_repository.dart'; +import 'package:pipelines_app/features/schedules/domain/saved_schedule.dart'; + +import 'schedule_test_support.dart'; + +void main() { + test( + 'lists with the exact web envelope and retains every record field', + () async { + final record = savedRecord(); + final gateway = RecordingGateway() + ..replies.add({ + 'type': 'schedules', + 'schedules': [record], + }); + final repository = SchedulesRepository(gateway); + + final listed = await repository.listSchedules(pipelineId: 4); + + expect(gateway.calls.single.type, 'list_schedules'); + expect(gateway.calls.single.fields, {'pipeline_id': 4}); + expect(listed.single.toJson(), record); + expect(listed.single.pipelineId, 4); + expect(listed.single.version, 2); + expect(listed.single.prompt, 'Research batteries'); + expect(listed.single.workspace, '/srv/research'); + expect(listed.single.enabled, isTrue); + expect(listed.single.rule.every, '24h'); + expect(listed.single.rule.days, ['mon', 'wed']); + expect(listed.single.rule.timezone, 'Europe/London'); + expect(listed.single.model, 'openai/gpt-5'); + expect(listed.single.notifyMode, 'off'); + expect(listed.single.toJson()['future_server_field'], { + 'nested': [ + 1, + 2, + {'deep': true}, + ], + }); + + gateway.replies.add({'type': 'schedules'}); + await repository.listSchedules(); + expect(gateway.calls.last.type, 'list_schedules'); + expect(gateway.calls.last.fields, isEmpty); + }, + ); + + test( + 'create sends the web sentinel record without inventing a revision', + () async { + final create = createRecord(); + final original = deepCopy(create); + final gateway = RecordingGateway() + ..replies.add({'type': 'schedule', 'schedule': savedRecord()}); + final repository = SchedulesRepository(gateway); + + final saved = await repository.saveSchedule(create); + + expect(gateway.calls.single.type, 'save_schedule'); + expect(gateway.calls.single.fields, {'schedule': create}); + expect(gateway.calls.single.fields.containsKey('request_key'), isFalse); + expect( + gateway.calls.single.fields.containsKey('expected_revision'), + isFalse, + ); + expect(create, original, reason: 'the caller record must be unchanged'); + expect(saved.id, 8); + expect(saved.revision, 3); + expect(saved.toJson(), savedRecord()); + }, + ); + + test( + 'a stable create key is forwarded exactly and blanks are omitted', + () async { + final create = createRecord(); + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + + gateway.replies.add({'type': 'schedule', 'schedule': savedRecord()}); + await repository.saveSchedule( + create, + requestKey: 'schedule:stable-editor-key', + ); + expect(gateway.calls.last.fields, { + 'schedule': create, + 'request_key': 'schedule:stable-editor-key', + }); + + gateway.replies.add({'type': 'schedule', 'schedule': savedRecord()}); + await repository.saveSchedule(create, requestKey: ''); + expect(gateway.calls.last.fields, {'schedule': create}); + }, + ); + + test('update reuses the read revision as the CAS token', () async { + final current = SavedSchedule(savedRecord()); + final paused = current.withEnabled(false); + expect(paused.id, 8); + expect(paused.revision, 3); + expect(paused.toJson()['future_server_field'], isNotNull); + + final gateway = RecordingGateway() + ..replies.add({ + 'type': 'schedule', + 'schedule': {...savedRecord(), 'enabled': false, 'revision': 4}, + }); + final repository = SchedulesRepository(gateway); + + final updated = await repository.saveSchedule(paused.toJson()); + + final body = gateway.calls.single.fields['schedule'] as Map; + expect(gateway.calls.single.type, 'save_schedule'); + expect(gateway.calls.single.fields.containsKey('request_key'), isFalse); + expect( + gateway.calls.single.fields.containsKey('expected_revision'), + isFalse, + ); + expect(body['id'], 8); + expect(body['revision'], 3); + expect(body['enabled'], isFalse); + expect(body['future_server_field'], isNotNull); + expect(updated.revision, 4); + expect(updated.enabled, isFalse); + + // The stale draft keeps its token: a conflict must not be papered over by + // silently adopting the reply revision. + expect(current.revision, 3); + expect(current.enabled, isTrue); + }); +} From 515c500bb1671cae3ca533f1f0febc4cbd79daa7 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 15:17:13 +0100 Subject: [PATCH 42/84] docs(app): verify rename component landing and start template-data slice --- app/WORK.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/WORK.md b/app/WORK.md index e6fe6224..ebafbaac 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -23,8 +23,9 @@ All work under app/. Existing applications remain running and unchanged. | I1 | App-owned socket/session + live Runs shell registration | run50 / flutter/r1-native | Code computed success; WAITING truncated2MiB export | held, review not reached | not deployed | | E1 | Narrow authorized server export-bound fix | run53 / fix/session-export-limit | API v8, Flash; bounded export/repair regressions | pending | no service restart authorized by pipeline | | R2c | Native retry/restart confirmation | run54 / flutter/r2-retry | Task v6, Flash; small independent action | pending | pending | -| R2d | Native rename-run dialog | run55 / flutter/r2-title | Task v6, Flash; small independent action | pending | pending | +| R2d | Native rename-run dialog | run55 / commitf2643a0 | manager reran11 focused tests + analyze, pass; clean scoped diff | main3dde288, ancestry verified | reusable only; screen/list update wiring pending | | S1a | Saved schedules repository/revision safety | run56 / flutter/s1-data | Task v6, Flash; nonvisual independent slice | pending | — | +| T1a | Templates/validate/create-only requests | run57 / flutter/t1-data | Task v6, Flash; nonvisual independent slice | pending | — | ## Next ready work - P1 pipelines list/detail/source/version; P2 graph and stage/visit selection. From 9eb01b8f6a8dcbe27a60b618d264ecdf149c5ba8 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 15:20:36 +0100 Subject: [PATCH 43/84] docs(app): record schedule and retry landings plus 98-test integration check --- app/WORK.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/app/WORK.md b/app/WORK.md index ebafbaac..9d4dff9a 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -22,10 +22,12 @@ All work under app/. Existing applications remain running and unchanged. | X1 | Native search and result targets | run49 / flutter/x1-search | Code computed success; WAITING truncated2MiB export | held, review not reached | pending | | I1 | App-owned socket/session + live Runs shell registration | run50 / flutter/r1-native | Code computed success; WAITING truncated2MiB export | held, review not reached | not deployed | | E1 | Narrow authorized server export-bound fix | run53 / fix/session-export-limit | API v8, Flash; bounded export/repair regressions | pending | no service restart authorized by pipeline | -| R2c | Native retry/restart confirmation | run54 / flutter/r2-retry | Task v6, Flash; small independent action | pending | pending | +| R2c | Native retry/restart confirmation | run54 / commit178f22a | manager reran17 focused tests + analyze, pass; exact modes/stable intent keys checked | main804e531, ancestry verified | reusable only; wiring/browser pending | | R2d | Native rename-run dialog | run55 / commitf2643a0 | manager reran11 focused tests + analyze, pass; clean scoped diff | main3dde288, ancestry verified | reusable only; screen/list update wiring pending | -| S1a | Saved schedules repository/revision safety | run56 / flutter/s1-data | Task v6, Flash; nonvisual independent slice | pending | — | +| S1a | Saved schedules repository/revision safety | run56 / commitb963965 | manager reran18 focused tests + analyze, pass; revision/unknown field preservation checked | maina290858, ancestry verified | — | | T1a | Templates/validate/create-only requests | run57 / flutter/t1-data | Task v6, Flash; nonvisual independent slice | pending | — | +| S1b | Native read-only schedule list | run58 / flutter/s1-list | Task v6, Flash; separate from editor | pending | pending | +| P2a | Graph identities/recorded-visit model | run59 / flutter/p2-model | Task v6, Flash; separate from layout/rendering | pending | — | ## Next ready work - P1 pipelines list/detail/source/version; P2 graph and stage/visit selection. @@ -58,6 +60,10 @@ override, server edit or shell-write bypass was used by the manager. Allowed pipeline models: Luna or DeepSeek V4.1 Flash; current runs use Luna. ## Latest integration check +At804e531 manager ran the integrated main Flutter suite: 98tests passed and +flutter analyze was clean. These cover landed source/components only, not the +six unreviewed export-blocked feature branches or visible screen delivery. + ### Current delivery blocker — session export cap User asked about failed runs; explicit status inspection found runs34/37/39/42/ 49/50 are waiting, not failed: each Code visit1 computed success and is quiescent, From 22801a9b06d9c465460e6b0230f34c91916f64e0 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 15:26:29 +0100 Subject: [PATCH 44/84] fix(stage): align session export render cap with artifact bound Six computed Flutter runs stopped at the export handoff gate because the rendered session.html cap was 2 MiB while their complete sessions (well inside the 8 MiB source read bound) rendered between 2.25 and 4.28 MiB once html escaping and the readable projection duplicated native text. Raise SessionExportFileLimit to 8 MiB, the server's existing per-artifact file bound, so a complete export is still listed and served. Normal export verification, versioned repair and the handoff gate keep using the single shared constant. The source read bound is unchanged, and an over-cap render is still visibly truncated and recorded partial. Add focused regressions for a complete export above the old cap, an over-new-cap file rejected as partial, repair above the old cap leaving original evidence untouched, the gate accepting the larger repair, and the constant staying inside the artifact file bound. Update the artifact, handoff-gate and operations docs and record the diagnosis in docs/notes/session-export-render-cap.md. --- docs/notes/session-export-handoff-gate.md | 2 +- docs/notes/session-export-render-cap.md | 44 +++++++++++++ docs/stage-artifacts.md | 11 ++-- .../author/skill/references/operations.md | 7 ++- internal/server/session_export_gate_test.go | 50 +++++++++++++++ internal/server/session_export_repair_test.go | 51 +++++++++++++++ internal/server/session_export_status_test.go | 63 ++++++++++++++++++- internal/stage/session_export.go | 13 +++- internal/stage/session_export_test.go | 32 ++++++++++ 9 files changed, 261 insertions(+), 12 deletions(-) create mode 100644 docs/notes/session-export-render-cap.md diff --git a/docs/notes/session-export-handoff-gate.md b/docs/notes/session-export-handoff-gate.md index 6f09e72c..086d550a 100644 --- a/docs/notes/session-export-handoff-gate.md +++ b/docs/notes/session-export-handoff-gate.md @@ -73,7 +73,7 @@ retry and refresh of an already-open Session tab. Large (>256 KiB) API fixtures, wrong identity, partial/empty exports, restart, cancellation, workspace reservation, and exactly-once successor admission have focused regressions. A full ordinary artifact inventory no longer blocks versioned audit repair. -Repairs have a separate bounded allowance (twenty attempts, each at most 2 MiB), +Repairs have a separate bounded allowance (twenty attempts, each at most 8 MiB), so neither the ordinary inventory's file count nor its byte budget consumes the mandatory audit-recovery capacity. The ordinary scan limits remain unchanged. diff --git a/docs/notes/session-export-render-cap.md b/docs/notes/session-export-render-cap.md new file mode 100644 index 00000000..3ffd0b34 --- /dev/null +++ b/docs/notes/session-export-render-cap.md @@ -0,0 +1,44 @@ +# Session export: rendered-file cap aligned with the artifact bound + +## Problem + +Six computed Flutter runs (34, 37, 39, 42, 49, 50) reached Code visit 1 with a +successful, quiescent agent session but stopped at the export handoff gate. Each +recorded `session_export.status: partial`, `html_bytes: 2097152`, +`truncated: true`; the manual versioned repair of run 34 hit the same exact size. +The sessions had completed their computation, so a stage rerun was not the right +recovery. + +A read-only inspection of the recorded session rows showed the original native +data for those six sessions was between 1,083,391 and 2,111,470 bytes (the +complete HTTP export envelope for one of them was 2,126,449 bytes). All were +well inside the existing 8 MiB source read cap. The binding limit was the 2 MiB +rendered-file cap: html escaping and the readable projection keep native text +more than once, so an ordinary session can render larger than its source. +Re-exporting the six exact sessions read-only into scratch directories with the +new cap produced complete, untruncated files of 2,252,874 to 4,276,358 bytes. + +## Change + +`internal/stage/session_export.go` raises `SessionExportFileLimit` from 2 MiB to +8 MiB. That value is the same as the server's ordinary per-artifact file bound +(`maxArtifactFileBytes` in `internal/server/artifacts.go`), so a complete export +remains listed and served instead of being cut below the bound that the artifact +inventory already enforces. + +The source read remains capped by `SessionExportSourceLimit` (the single +`opencode.MaxSessionExport` value, 8 MiB). Normal export verification, versioned +export repair and the handoff gate all use `SessionExportFileLimit`, so they now +share one larger bound. The export still refuses to overwrite an existing file, +still marks any cut with a visible leading and trailing banner, and still reports +`truncated: true` and `status: partial`; nothing treats a partial export as +complete. + +## Checks + +Focused stage and server regressions cover a complete export above the old 2 MiB +cap but inside the new cap, a file above the new cap rejected as partial with the +verification diagnostic, repair accepting the larger complete file while the +original evidence stays unchanged, and the constant staying within the ordinary +artifact file bound. Focused stage/server suites and `go build ./...` plus +`go vet ./...` are run before landing; see the delivery report for exact results. diff --git a/docs/stage-artifacts.md b/docs/stage-artifacts.md index b29260d0..b2da6462 100644 --- a/docs/stage-artifacts.md +++ b/docs/stage-artifacts.md @@ -97,10 +97,13 @@ no special casing. `opencode session export `. Both reuse the same invocation helper and session-ID/messages validation as the transcript readback. The file is the harness's real session, never a reconstruction. -- Bounds: the source read is capped at 8 MiB and the rendered file at 2 MiB. When - either is cut, the file carries a visible truncation banner near the start and - the end and the step records `truncated: true`; a truncated export is never - described as whole. +- Bounds: the source read is capped at 8 MiB and the rendered file at 8 MiB, + matching the ordinary per-artifact file bound. The rendered file can exceed + its source because html escaping and the readable projection keep native text + more than once, so the previous 2 MiB render cap cut complete sessions that + were well inside the source bound. When either bound is exceeded, the file + carries a visible truncation banner near the start and the end and the step + records `truncated: true`; a truncated export is never described as whole. - Evidence: the step records `session_export` (`session_id`, `backend`, `source`, `html`, `html_bytes`, `messages`, `truncated`, `diagnostic`), so `pipelines inspect RUN_ID --json` shows what was written without reading the diff --git a/internal/author/skill/references/operations.md b/internal/author/skill/references/operations.md index 06a6013a..c67de23b 100644 --- a/internal/author/skill/references/operations.md +++ b/internal/author/skill/references/operations.md @@ -249,9 +249,10 @@ landed. presented. A run recorded before the HTML-only change still lists `session.md` among its stored artifacts (dated evidence kept on disk, not deleted); every listing — app, TUI, web spike — hides it rather than showing it beside the html. -- The source read is capped at 8 MiB and the rendered file at 2 MiB; a cut source or - a cut rendered file carries a visible truncation banner at both ends and - `session_export.truncated: true`, and a truncated export is never called whole. +- The source read is capped at 8 MiB and the rendered file at 8 MiB, matching the + ordinary per-artifact file bound; a cut source or a cut rendered file carries a + visible truncation banner at both ends and `session_export.truncated: true`, and + a truncated export is never called whole. - The step records `session_export` (`session_id`, `backend`, `source`, the html file name, `html_bytes`, `messages`, `truncated`, `diagnostic`) in `inspect RUN_ID --json`. A record written before the change still carried diff --git a/internal/server/session_export_gate_test.go b/internal/server/session_export_gate_test.go index a32a0943..3c9519c4 100644 --- a/internal/server/session_export_gate_test.go +++ b/internal/server/session_export_gate_test.go @@ -136,6 +136,56 @@ func TestSessionExportGateRetryOnlyAndExactlyOnce(t *testing.T) { } } +// TestSessionExportGateAcceptsRepairAboveOldRenderCap keeps the handoff gate's +// versioned-repair verification on the same larger bound as normal export. +func TestSessionExportGateAcceptsRepairAboveOldRenderCap(t *testing.T) { + h, s, id, first, second := gateRunner(t, func(context.Context, stage.SessionExportRequest) (stage.SessionExportResult, error) { + return stage.SessionExportResult{}, errors.New("export offline") + }, false) + h.runner.wg.Wait() + ctx := context.Background() + if err := s.ConfirmRecoveredSession(ctx, pipeline.SessionOwner{RunID: id, ID: "ses_exact"}); err != nil { + t.Fatal(err) + } + size := int64(2<<20) + 4096 + h.runner.exportSession = func(_ context.Context, req stage.SessionExportRequest) (stage.SessionExportResult, error) { + if err := os.MkdirAll(req.ArtifactsDir, 0700); err != nil { + return stage.SessionExportResult{}, err + } + f, err := os.Create(filepath.Join(req.ArtifactsDir, req.FileName)) + if err != nil { + return stage.SessionExportResult{}, err + } + if err := f.Truncate(size); err != nil { + f.Close() + return stage.SessionExportResult{}, err + } + if err := f.Close(); err != nil { + return stage.SessionExportResult{}, err + } + return stage.SessionExportResult{Source: "native_export", HTML: req.FileName, HTMLBytes: size, Messages: 2}, nil + } + if _, err := h.runner.repairSessionExport(ctx, id, 1); err != nil { + t.Fatal(err) + } + // The worker promotes a persisted complete repair before claiming a lease. + job, err := s.ClaimSessionExportJob(ctx, time.Now().Add(time.Second), time.Minute) + if err != nil { + t.Fatal(err) + } + if job != nil { + t.Fatalf("complete repair still claimed as a recovery job: %+v", job) + } + if err := h.runner.resumeExportGates(ctx); err != nil { + t.Fatal(err) + } + h.runner.wg.Wait() + d, _ := s.GetRun(ctx, id) + if first.Load() != 1 || second.Load() != 1 || d.Status != "succeeded" || len(d.Steps) != 2 { + t.Fatalf("large repair did not advance the gate: %+v (%d/%d)", d, first.Load(), second.Load()) + } +} + func TestSessionExportGateCleanupUnconfirmedDoesNotExportOrAdvance(t *testing.T) { var exports atomic.Int32 h, s, id, _, second := gateRunner(t, func(ctx context.Context, req stage.SessionExportRequest) (stage.SessionExportResult, error) { diff --git a/internal/server/session_export_repair_test.go b/internal/server/session_export_repair_test.go index 4c0d8252..c2aabf3a 100644 --- a/internal/server/session_export_repair_test.go +++ b/internal/server/session_export_repair_test.go @@ -111,6 +111,57 @@ func TestRuntimeSessionExportRepairPreservesOriginalAndUsesRecordedOwner(t *test } } +// TestRuntimeSessionExportRepairAcceptsAboveTheOldRenderCap proves a versioned +// repair uses the same larger bound as a normal export while leaving the +// original recorded evidence untouched. +func TestRuntimeSessionExportRepairAcceptsAboveTheOldRenderCap(t *testing.T) { + h, s, id := sessionExportRunner(t, "v2", func(stage.SessionExportRequest) (stage.SessionExportResult, error) { + return stage.SessionExportResult{}, errors.New("initial export unavailable") + }) + if err := s.ConfirmRecoveredSession(context.Background(), pipeline.SessionOwner{RunID: id, ID: "ses_run"}); err != nil { + t.Fatal(err) + } + original, err := s.GetRun(context.Background(), id) + if err != nil { + t.Fatal(err) + } + before, _ := json.Marshal(original.Steps[0].SessionExport) + size := int64(2<<20) + 4096 + h.runner.exportSession = func(_ context.Context, req stage.SessionExportRequest) (stage.SessionExportResult, error) { + if err := os.MkdirAll(req.ArtifactsDir, 0700); err != nil { + return stage.SessionExportResult{}, err + } + f, err := os.Create(filepath.Join(req.ArtifactsDir, req.FileName)) + if err != nil { + return stage.SessionExportResult{}, err + } + if err := f.Truncate(size); err != nil { + f.Close() + return stage.SessionExportResult{}, err + } + if err := f.Close(); err != nil { + return stage.SessionExportResult{}, err + } + return stage.SessionExportResult{Source: "native_export", HTML: req.FileName, HTMLBytes: size, Messages: 2}, nil + } + repaired, err := h.runner.repairSessionExport(context.Background(), id, 1) + if err != nil { + t.Fatal(err) + } + latest := repaired.Steps[0].SessionExportRepairs[0] + if latest.Status != "complete" || latest.HTMLBytes != size || latest.HTML == "" { + t.Fatalf("repair above the old cap was not complete: %+v", latest) + } + after, _ := json.Marshal(repaired.Steps[0].SessionExport) + if string(before) != string(after) { + t.Fatal("repair above the old cap overwrote original evidence") + } + info, err := os.Stat(filepath.Join(h.runner.artifactsRoot, "1", "stages", "01-"+repaired.Steps[0].Stage, latest.HTML)) + if err != nil || info.Size() != size { + t.Fatalf("repair file missing or resized: %v %+v", err, info) + } +} + func TestRuntimeRepairRejectsUnrecordedAndActiveVisits(t *testing.T) { h, _, id := sessionExportRunner(t, "v2", func(stage.SessionExportRequest) (stage.SessionExportResult, error) { return stage.SessionExportResult{}, errors.New("unavailable") diff --git a/internal/server/session_export_status_test.go b/internal/server/session_export_status_test.go index a1bae02a..10daae33 100644 --- a/internal/server/session_export_status_test.go +++ b/internal/server/session_export_status_test.go @@ -1,10 +1,13 @@ package server import ( - "git.a-wan.net/alan/pipelines/internal/protocol" "os" "path/filepath" + "strings" "testing" + + "git.a-wan.net/alan/pipelines/internal/protocol" + "git.a-wan.net/alan/pipelines/internal/stage" ) func TestSessionExportCompleteness(t *testing.T) { @@ -56,3 +59,61 @@ func TestRuntimeSessionExportFileVerificationDoesNotClaimMissingEvidence(t *test }) } } + +func sizedSessionFile(t *testing.T, size int64) string { + t.Helper() + dir := t.TempDir() + path := filepath.Join(dir, "session.html") + f, err := os.Create(path) + if err != nil { + t.Fatal(err) + } + if err := f.Truncate(size); err != nil { + f.Close() + t.Fatal(err) + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + return dir +} + +// TestRuntimeSessionExportVerificationAcceptsAboveTheOldRenderCap pins the +// ordinary-session case the previous 2 MiB rendered bound cut. The file is +// larger than that old cap and inside the artifact-aligned bound, so normal +// export verification must keep it and classify the evidence complete. +func TestRuntimeSessionExportVerificationAcceptsAboveTheOldRenderCap(t *testing.T) { + size := int64(2<<20) + 4096 + dir := sizedSessionFile(t, size) + evidence := &protocol.SessionExport{Source: "native_export", Messages: 2, HTML: "session.html", HTMLBytes: size} + verifySessionExportFile(evidence, dir) + classifySessionExport(evidence) + if evidence.Status != "complete" || evidence.HTML != "session.html" || evidence.HTMLBytes != size || evidence.Diagnostic != "" { + t.Fatalf("complete export above the old cap was rejected: %+v", evidence) + } +} + +// TestRuntimeSessionExportVerificationRejectsAboveTheNewCap confirms the larger +// bound is still a hard bound: an oversized file is not presented as evidence. +func TestRuntimeSessionExportVerificationRejectsAboveTheNewCap(t *testing.T) { + size := int64(stage.SessionExportFileLimit) + 1 + dir := sizedSessionFile(t, size) + evidence := &protocol.SessionExport{Source: "native_export", Messages: 2, HTML: "session.html", HTMLBytes: size} + verifySessionExportFile(evidence, dir) + classifySessionExport(evidence) + if evidence.Status != "partial" || evidence.HTML != "" || evidence.HTMLBytes != 0 || !strings.Contains(evidence.Diagnostic, "bounded verification") { + t.Fatalf("oversized export was not rejected as partial: %+v", evidence) + } +} + +// TestSessionExportFileLimitStaysInsideArtifactBounds keeps the render cap +// principled: larger than the cap that cut ordinary sessions, and no larger +// than the ordinary per-artifact file bound that serves the file. +func TestSessionExportFileLimitStaysInsideArtifactBounds(t *testing.T) { + if stage.SessionExportFileLimit <= 2<<20 { + t.Fatalf("render cap %d did not grow beyond the old 2 MiB cutoff", stage.SessionExportFileLimit) + } + if stage.SessionExportFileLimit > maxArtifactFileBytes { + t.Fatalf("render cap %d exceeds the artifact file bound %d", stage.SessionExportFileLimit, maxArtifactFileBytes) + } +} diff --git a/internal/stage/session_export.go b/internal/stage/session_export.go index 583602dd..2c752c5c 100644 --- a/internal/stage/session_export.go +++ b/internal/stage/session_export.go @@ -20,7 +20,7 @@ import ( // artifacts directory as one html file so the existing artifact listing and // serving paths find it with no special casing. The source read is capped at // SessionExportSourceLimit and the rendered file at SessionExportFileLimit, so -// the export adds at most ~2 MiB per step, inside the artifact scan limits. +// the export stays inside the server's per-artifact file bound. const ( // SessionHTMLFile is the one session export a stage writes. SessionHTMLFile = "session.html" @@ -32,8 +32,15 @@ const ( // SessionExportSourceLimit is the native session read cap; it is the one // opencode.MaxSessionExport value, not a second copy. SessionExportSourceLimit = opencode.MaxSessionExport - SessionExportFileLimit = 2 << 20 - SessionExportTimeout = 10 * time.Second + // SessionExportFileLimit is the rendered file cap. Ordinary native sessions + // commonly render a little larger than their raw source because html escaping + // and the readable projection duplicate native text; the previous 2 MiB cap + // cut complete sessions that were well inside the source bound. This cap + // matches the server's per-artifact file bound (maxArtifactFileBytes in + // internal/server/artifacts.go), so a complete export remains listed and + // served while a genuinely oversized one is still visibly truncated. + SessionExportFileLimit = 8 << 20 + SessionExportTimeout = 10 * time.Second ) // SessionExportRequest names the stage session to export and the evidence the diff --git a/internal/stage/session_export_test.go b/internal/stage/session_export_test.go index 5db417fd..8cf2efe2 100644 --- a/internal/stage/session_export_test.go +++ b/internal/stage/session_export_test.go @@ -222,6 +222,38 @@ func TestExportSessionLargeHTTPExportWritesBoundedRealHTML(t *testing.T) { } } +// TestExportSessionCompletesAboveTheOldRenderedCap covers the ordinary case the +// previous 2 MiB render cap cut: a complete native session inside the 8 MiB +// source bound whose escaped html is larger than 2 MiB. +func TestExportSessionCompletesAboveTheOldRenderedCap(t *testing.T) { + const oldRenderCap = 2 << 20 + dir := t.TempDir() + line := "complete ordinary session line " + text := strings.Repeat(line, oldRenderCap/len(line)+1000) + body := `{"info":{"id":"ses_ok"},"messages":[{"info":{"id":"m1","role":"user"},"text":"` + text + `"}]}` + sessionCLI(t, "ses_ok", body) + result, err := ExportSession(context.Background(), sessionRequest(dir)) + if err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(filepath.Join(dir, result.HTML)) + if err != nil { + t.Fatal(err) + } + if result.Truncated || result.Messages != 1 || result.HTMLBytes != int64(len(data)) { + t.Fatalf("complete export above the old cap was not recorded: %+v", result) + } + if len(data) <= oldRenderCap || len(data) > SessionExportFileLimit { + t.Fatalf("rendered size %d is not above the old cap and inside the new one", len(data)) + } + if strings.Contains(string(data), "TRUNCATED") { + t.Fatal("a complete export carried a truncation banner") + } + if !strings.Contains(string(data), "complete ordinary session line") { + t.Fatal("complete export lost its session text") + } +} + func TestExportSessionSourceTruncationIsLabelledNotWhole(t *testing.T) { session := opencode.ExportedSession{ ID: "ses_ok", From cd9ec62d28ffa24754330f3d5de1db0689797466 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 15:31:10 +0100 Subject: [PATCH 45/84] feat(app): add template catalogue and create-only submit repository Add the nonvisual templates data/domain slice: TemplateRepository over the shared ApiGateway for list_templates, validate and create-only submit, and TemplateEntry preserving every server field in a deeply read-only raw map. Re-include test/**/data/ in app/.gitignore so the mirroring tests are not silently dropped from a fresh checkout. Tests cover exact request shapes, source preservation, blank-name refusal, malformed replies, server refusals and immutability. --- app/.gitignore | 6 +- .../templates/data/template_repository.dart | 84 +++++++++ .../templates/domain/template_entry.dart | 63 +++++++ app/notes/T1a.md | 140 +++++++++++++++ .../templates/data/template_create_test.dart | 147 ++++++++++++++++ .../templates/data/template_list_test.dart | 165 ++++++++++++++++++ .../templates/data/template_test_support.dart | 47 +++++ 7 files changed, 651 insertions(+), 1 deletion(-) create mode 100644 app/lib/features/templates/data/template_repository.dart create mode 100644 app/lib/features/templates/domain/template_entry.dart create mode 100644 app/notes/T1a.md create mode 100644 app/test/features/templates/data/template_create_test.dart create mode 100644 app/test/features/templates/data/template_list_test.dart create mode 100644 app/test/features/templates/data/template_test_support.dart diff --git a/app/.gitignore b/app/.gitignore index 9f91cbac..ffe0bc2c 100644 --- a/app/.gitignore +++ b/app/.gitignore @@ -45,6 +45,10 @@ app.*.map.json /android/app/release # The repository ignores runtime data/ directories. Feature repository source -# is code, not runtime data, and must be included in fresh checkouts. +# and its mirroring tests are code, not runtime data, and must be included in +# fresh checkouts. The test negation is required too: without it every +# `test/**/data/` directory is silently dropped from the candidate. !/lib/**/data/ !/lib/**/data/** +!/test/**/data/ +!/test/**/data/** diff --git a/app/lib/features/templates/data/template_repository.dart b/app/lib/features/templates/data/template_repository.dart new file mode 100644 index 00000000..da56f5ea --- /dev/null +++ b/app/lib/features/templates/data/template_repository.dart @@ -0,0 +1,84 @@ +import '../../../core/api_gateway.dart'; +import '../domain/template_entry.dart'; + +/// A templates protocol refusal kept separate from transport errors; server +/// error envelopes are propagated unchanged by [ApiGateway]. +class TemplateRepositoryException implements Exception { + const TemplateRepositoryException(this.message); + final String message; + @override + String toString() => message; +} + +/// Template catalogue, definition validation and create-only submission over +/// the application's shared gateway. +/// +/// These are reads plus one explicit submit. No method publishes, runs, +/// overwrites or schedules a pipeline, so merely loading or validating a +/// template can never start work. +class TemplateRepository { + TemplateRepository(this._gateway); + final ApiGateway _gateway; + + /// The server's template catalogue, exactly as `list_templates` returns it. + /// A reply without a `templates` field is the older server answering with no + /// catalogue, which is an empty list rather than an error. + Future> listTemplates() async { + final reply = await _gateway.call('list_templates'); + final templates = reply['templates']; + if (templates == null) return const []; + if (templates is! List) { + throw const TemplateRepositoryException( + 'The server returned no template catalogue.', + ); + } + return List.unmodifiable( + templates.map((entry) { + if (entry is! Map) { + throw const TemplateRepositoryException( + 'The server returned a template that is not an object.', + ); + } + return TemplateEntry.fromJson(Map.from(entry)); + }), + ); + } + + /// Parses one definition source on the server (`validate`) and returns the + /// graph it produced. The source is sent byte-for-byte: no trimming, casing or + /// whitespace changes. A malformed definition rejects with the server's own + /// error; a reply without a graph is refused rather than reported as valid. + Future validate(String source) async { + final reply = await _gateway.call('validate', {'source': source}); + final graph = reply['graph']; + if (graph is! Map) { + throw const TemplateRepositoryException('The server returned no graph.'); + } + return Map.from(graph); + } + + /// Creates a new draft pipeline from [source] (`submit`), create-only. + /// + /// A blank name is refused locally before anything is sent, matching the + /// browser and Android clients; the name that is sent is trimmed. The source + /// is not changed. `create_only` is always true, so an existing pipeline can + /// never be overwritten, and no run is started. + Future submit(String name, String source) async { + final trimmed = name.trim(); + if (trimmed.isEmpty) { + throw const TemplateRepositoryException('Enter a pipeline name.'); + } + final reply = await _gateway.call('submit', { + 'name': trimmed, + 'source': source, + 'create_only': true, + }); + final detail = reply['detail']; + if (detail is! Map) { + throw const TemplateRepositoryException( + 'The server returned no pipeline detail.', + ); + } + return Map.from(detail); + } +} diff --git a/app/lib/features/templates/domain/template_entry.dart b/app/lib/features/templates/domain/template_entry.dart new file mode 100644 index 00000000..6c86bcbf --- /dev/null +++ b/app/lib/features/templates/domain/template_entry.dart @@ -0,0 +1,63 @@ +import '../../../core/api_gateway.dart'; + +/// One template from the server catalogue. +/// +/// The server owns this record: [key], [name], [description], [source] and +/// [scheduled] are read from it verbatim and every other field is kept in +/// [raw], so a later view or round-trip never loses fields this client does not +/// understand yet. Loading a template is a read; it never publishes or runs it. +class TemplateEntry { + const TemplateEntry({ + required this.key, + required this.name, + required this.description, + required this.source, + required this.scheduled, + required this.raw, + }); + + factory TemplateEntry.fromJson(JsonMap json) { + final raw = _frozenMap(json); + return TemplateEntry( + key: _text(raw['key']), + name: _text(raw['name']), + description: _text(raw['description']), + source: _text(raw['source']), + scheduled: raw['scheduled'] == true, + raw: raw, + ); + } + + /// The stable catalogue key the gallery selects on. + final String key; + final String name; + final String description; + + /// The template's complete, untrimmed definition source. + final String source; + + /// Whether the source declares a schedule (the summary's "Includes a schedule"). + final bool scheduled; + + /// Every field the server sent, including fields this client does not model. + /// Deeply unmodifiable: nested maps and lists are copied into read-only + /// collections too, so a view cannot mutate the server reply through it. + final JsonMap raw; + + static String _text(dynamic value) => value == null ? '' : '$value'; + + static JsonMap _frozenMap(Map json) => + Map.unmodifiable( + json.map((key, value) => MapEntry(key, _frozen(value))), + ); + + static dynamic _frozen(dynamic value) { + if (value is Map) { + return _frozenMap(Map.from(value)); + } + if (value is List) { + return List.unmodifiable(value.map(_frozen)); + } + return value; + } +} diff --git a/app/notes/T1a.md b/app/notes/T1a.md new file mode 100644 index 00000000..e8a39fc4 --- /dev/null +++ b/app/notes/T1a.md @@ -0,0 +1,140 @@ +# T1a — template catalogue, validate and create-only submit + +## What changed + +New nonvisual `templates` data/domain slice. One shared file was edited: +`app/.gitignore` re-includes `test/**/data/`, because the repository's runtime +`data/` rule was silently excluding this slice's tests from the candidate. No +other lane's work, `lib/main.dart`, shell, pubspec, `web/`, server or Android +file was touched. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/templates/domain/template_entry.dart` | 63 | Immutable server template; models key/name/description/source/scheduled and keeps every unknown field in deeply read-only `raw` | +| `lib/features/templates/data/template_repository.dart` | 84 | `TemplateRepository(ApiGateway)`: list, validate, create-only submit | +| `test/features/templates/data/template_test_support.dart` | 47 | Recording/refusing fake gateways, server-refusal error, Unicode source fixture | +| `test/features/templates/data/template_list_test.dart` | 165 | Catalogue request shape, field preservation, deep immutability, missing/malformed catalogue | +| `test/features/templates/data/template_create_test.dart` | 147 | Validate/submit envelopes, blank-name gate, missing payloads, verbatim refusals | +| `app/.gitignore` | +4 | Re-includes `test/**/data/` so test files enter the candidate | + +Nothing under `lib/main.dart`, `lib/shell/`, another feature, `pubspec.*`, +`web/`, the Go server or `android/` was changed. No dependency was added. + +## Review findings addressed + +- **Tests could never land (blocking).** `test/features/templates/data/` was + excluded by the repository root rule `data/`; `app/.gitignore` only re-included + `lib/**/data/`. The same negation now covers `test/**/data/`, so these three + test files are untracked-but-visible to git and `git add -n` succeeds. Fixing + the rule (rather than `git add -f`) also protects later `test/**/data/` lanes + such as S1a. No test was moved, so `test/` still mirrors `lib/`. +- **`raw` was only shallowly immutable (advisory).** `TemplateEntry.fromJson` + now deep-copies nested maps/lists into read-only collections, and the listed + test proves nested mutation throws and that the copy does not alias the reply. +- **Malformed-catalogue branches were untested (advisory).** Added tests for a + non-list `templates` value and a non-object catalogue entry, both rejecting + with explicit messages. +- `_text` still stringifies a non-string protocol value with `'$value'`; the + protocol only sends strings, and this matches how the browser would render + such a value, so the behaviour was left unchanged and is documented here + rather than claimed as strict parity. + +## Wire behaviour (mirrors `web/src/repository.js`) + +- `listTemplates()` sends exactly `{"type":"list_templates"}` with no fields and + returns the `templates` catalogue. A reply with no `templates` field is the + older server's empty catalogue (`?? []` in the browser), not a fake template. + Each entry keeps `key`, `name`, `description`, `source`, `scheduled` and all + unknown fields in `TemplateEntry.raw`; the reply list/maps are never mutated. + `raw` is a deep unmodifiable copy: nested unknown maps and lists are copied + into read-only collections, so neither the view nor a later caller can mutate + the server reply through it. +- `listTemplates()` rejects a malformed envelope instead of fabricating + entries: a non-list `templates` throws + `"The server returned no template catalogue."` and a non-object entry throws + `"The server returned a template that is not an object."`. The real server + cannot produce either, but a protocol mistake must not look like an empty or + half-populated catalogue. +- `validate(source)` sends exactly `{"type":"validate","source":}` and + returns the reply's `graph`. A reply without a graph throws + `TemplateRepositoryException("The server returned no graph.")` — the browser's + exact words — rather than reporting a valid definition. +- `submit(name, source)` sends exactly + `{"type":"submit","name":,"source":,"create_only":true}`. + A blank/whitespace-only name is refused locally with + `TemplateRepositoryException("Enter a pipeline name.")` and no gateway call is + made; the accepted name is trimmed. A reply without `detail` throws + `TemplateRepositoryException("The server returned no pipeline detail.")`. +- The source string is never trimmed, normalised or re-encoded: Unicode, tabs, + newlines and significant leading/trailing whitespace arrive unchanged. +- A server refusal is never caught or reworded by the repository. It reaches the + caller as the same gateway error object, so the server's own text is shown. +- The repository exposes only these three operations. It has no publish, run, + schedule or overwrite path, so loading or validating a template cannot start + work or mutate a retained pipeline. + +## Checks actually run + +``` +flutter pub get # Got dependencies +dart format lib/features/templates test/features/templates # clean +flutter analyze # No issues found! (0.9s) +flutter test test/features/templates # 13 passed +flutter test # 76 passed +flutter build web # ✓ Built build/web (15.5s) +git diff --check # clean +git check-ignore / git add -n # tests are no longer ignored +``` + +Tests are part of the candidate, not merely present on disk: + +``` +$ git add -n app/test/features/templates/data/template_list_test.dart \ + app/test/features/templates/data/template_create_test.dart \ + app/test/features/templates/data/template_test_support.dart +add 'app/test/features/templates/data/template_create_test.dart' +add 'app/test/features/templates/data/template_list_test.dart' +add 'app/test/features/templates/data/template_test_support.dart' +exit=0 + +$ git status --porcelain=v1 -uall + M app/.gitignore +?? app/lib/features/templates/data/template_repository.dart +?? app/lib/features/templates/domain/template_entry.dart +?? app/notes/T1a.md +?? app/test/features/templates/data/template_create_test.dart +?? app/test/features/templates/data/template_list_test.dart +?? app/test/features/templates/data/template_test_support.dart +``` + +Focused acceptance coverage: + +- exact `list_templates` request (no fields, one call) and preservation of + modelled plus unknown fields, including nested unknown data; +- listing does not mutate the reply's template list or entry maps; `raw` and + every nested map/list are read-only, and the copy does not alias the reply; +- missing catalogue -> empty list; malformed catalogue -> explicit refusal; +- blank/whitespace name -> refusal with zero gateway calls; +- Unicode/emoji, tab/newline and leading/trailing source whitespace preserved in + both `validate` and `submit`; submit sends only name, source and + `create_only: true`, with the name trimmed; +- missing `graph` and missing `detail` rejected with the browser's exact + messages, with no fabricated graph/detail; +- validate and submit server refusals surface as the identical error object, + not a wrapper. + +## Honest limits + +- **Not wired into a screen.** This branch has no templates screen and the task + owns data/domain only; the manager owns integration. No browser capture was + made because there is no rendered change in this slice. +- **Mobile unverified.** No Android/iOS build, emulator, ADB or device was used. + The code is plain Dart with no platform-specific code. +- No live server, template catalogue, validate call or submit/creation was + performed. All tests use local fake gateways with no socket, so no real + pipeline was created or run. +- No export-gate workaround, server change or service operation was made; the + pending export-cap fix remains another lane's scope. +- **Not committed.** The stage instruction says not to commit, push or deploy, + so the candidate above is uncommitted in the working tree even though the run + prompt asks to commit a reviewed candidate. Nothing was pushed or deployed. diff --git a/app/test/features/templates/data/template_create_test.dart b/app/test/features/templates/data/template_create_test.dart new file mode 100644 index 00000000..68b82c4b --- /dev/null +++ b/app/test/features/templates/data/template_create_test.dart @@ -0,0 +1,147 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/templates/data/template_repository.dart'; + +import 'template_test_support.dart'; + +void main() { + test( + 'validate sends the exact source and returns the server graph', + () async { + final graph = { + 'stages': [ + {'key': 'build', 'type': 'model'}, + ], + 'unknown_graph_field': true, + }; + final gateway = RecordingGateway([ + {'type': 'validated', 'graph': graph}, + ]); + + final result = await TemplateRepository(gateway).validate(source); + + expect(gateway.calls.single.type, 'validate'); + expect(gateway.calls.single.fields, {'source': source}); + expect(gateway.calls.single.fields['source'], source); + expect(result, graph); + }, + ); + + test( + 'validate rejects a reply without a graph instead of faking success', + () async { + for (final reply in [ + {'type': 'validated'}, + {'type': 'validated', 'graph': null}, + ]) { + final gateway = RecordingGateway([reply]); + + await expectLater( + TemplateRepository(gateway).validate(source), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server returned no graph.', + ), + ), + ); + } + }, + ); + + test('validate propagates a server refusal verbatim', () async { + const refusal = ServerRefusal('invalid stage "añadir": unknown key'); + final gateway = RefusingGateway(refusal); + + await expectLater( + TemplateRepository(gateway).validate(source), + throwsA(same(refusal)), + ); + expect(gateway.calls, ['validate']); + }); + + test('submit refuses a blank name without sending anything', () async { + for (final name in ['', ' ', '\t\n']) { + final gateway = RecordingGateway([ + { + 'detail': {'id': 1}, + }, + ]); + + await expectLater( + TemplateRepository(gateway).submit(name, source), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'Enter a pipeline name.', + ), + ), + ); + expect(gateway.calls, isEmpty); + } + }); + + test( + 'submit trims the name, preserves the source and is always create-only', + () async { + final detail = { + 'id': 9, + 'name': 'Release 2', + 'version': 1, + }; + final gateway = RecordingGateway([ + {'type': 'submitted', 'detail': detail}, + ]); + + final result = await TemplateRepository( + gateway, + ).submit(' Release 2 ', source); + + expect(gateway.calls.single.type, 'submit'); + expect(gateway.calls.single.fields, { + 'name': 'Release 2', + 'source': source, + 'create_only': true, + }); + expect(gateway.calls.single.fields.keys, [ + 'name', + 'source', + 'create_only', + ]); + expect(result, detail); + }, + ); + + test( + 'submit rejects a reply without a detail instead of faking success', + () async { + final gateway = RecordingGateway([ + {'type': 'submitted'}, + ]); + + await expectLater( + TemplateRepository(gateway).submit('Release', source), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server returned no pipeline detail.', + ), + ), + ); + }, + ); + + test('submit propagates a server refusal verbatim', () async { + const refusal = ServerRefusal('a pipeline named "Release" already exists'); + final gateway = RefusingGateway(refusal); + + await expectLater( + TemplateRepository(gateway).submit(' Release ', source), + throwsA(same(refusal)), + ); + expect(gateway.calls, ['submit']); + }); +} diff --git a/app/test/features/templates/data/template_list_test.dart b/app/test/features/templates/data/template_list_test.dart new file mode 100644 index 00000000..63cd2e93 --- /dev/null +++ b/app/test/features/templates/data/template_list_test.dart @@ -0,0 +1,165 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/templates/data/template_repository.dart'; + +import 'template_test_support.dart'; + +void main() { + test( + 'list_templates sends only the type and preserves every field', + () async { + final catalogue = [ + { + 'key': 'release', + 'name': 'Release', + 'description': 'Ship a version', + 'source': source, + 'scheduled': true, + 'future_field': { + 'nested': [1, 2, 3], + }, + }, + { + 'key': 'blank', + 'name': '', + 'description': '', + 'source': 'name: empty', + 'scheduled': false, + }, + ]; + final gateway = RecordingGateway([ + {'templates': catalogue}, + ]); + + final entries = await TemplateRepository(gateway).listTemplates(); + + expect(gateway.calls, hasLength(1)); + expect(gateway.calls.single.type, 'list_templates'); + expect(gateway.calls.single.fields, isEmpty); + expect(entries, hasLength(2)); + expect(entries.first.key, 'release'); + expect(entries.first.name, 'Release'); + expect(entries.first.description, 'Ship a version'); + expect(entries.first.source, source); + expect(entries.first.scheduled, isTrue); + expect(entries.first.raw['future_field'], { + 'nested': [1, 2, 3], + }); + expect(entries.last.key, 'blank'); + expect(entries.last.scheduled, isFalse); + expect(entries.last.raw, isNot(contains('missing'))); + }, + ); + + test('list_templates leaves the server reply untouched', () async { + final first = { + 'key': 'one', + 'name': 'One', + 'source': source, + 'scheduled': true, + 'unknown': ['keep', 'me'], + }; + final reply = { + 'templates': [first], + 'usage': {'templates': 1}, + }; + final gateway = RecordingGateway([reply]); + + final entries = await TemplateRepository(gateway).listTemplates(); + + expect(reply['templates'], hasLength(1)); + expect(first, { + 'key': 'one', + 'name': 'One', + 'source': source, + 'scheduled': true, + 'unknown': ['keep', 'me'], + }); + expect(entries.single.raw['unknown'], ['keep', 'me']); + expect( + () => entries.single.raw['name'] = 'changed', + throwsUnsupportedError, + ); + expect(first['name'], 'One'); + }); + + test('list_templates freezes nested unknown data in raw', () async { + final nested = { + 'nested': [1, 2, 3], + }; + final gateway = RecordingGateway([ + { + 'templates': [ + { + 'key': 'one', + 'name': 'One', + 'source': source, + 'scheduled': true, + 'future_field': nested, + }, + ], + }, + ]); + + final entries = await TemplateRepository(gateway).listTemplates(); + final raw = entries.single.raw; + final future = raw['future_field'] as Map; + + expect(() => future['added'] = true, throwsUnsupportedError); + expect(() => (future['nested'] as List).add(4), throwsUnsupportedError); + expect(future['nested'], [1, 2, 3]); + // The unmodifiable copies do not alias the server reply either. + nested['added'] = true; + expect(raw['future_field'], isNot(contains('added'))); + }); + + test('list_templates rejects a catalogue that is not a list', () async { + final gateway = RecordingGateway([ + { + 'templates': {'key': 'not-a-list'}, + }, + ]); + + await expectLater( + TemplateRepository(gateway).listTemplates(), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server returned no template catalogue.', + ), + ), + ); + }); + + test( + 'list_templates rejects a catalogue entry that is not an object', + () async { + final gateway = RecordingGateway([ + { + 'templates': ['not-an-entry'], + }, + ]); + + await expectLater( + TemplateRepository(gateway).listTemplates(), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server returned a template that is not an object.', + ), + ), + ); + }, + ); + + test('list_templates treats a reply with no catalogue as empty', () async { + final gateway = RecordingGateway([{}]); + + final entries = await TemplateRepository(gateway).listTemplates(); + + expect(entries, isEmpty); + expect(gateway.calls.single.type, 'list_templates'); + }); +} diff --git a/app/test/features/templates/data/template_test_support.dart b/app/test/features/templates/data/template_test_support.dart new file mode 100644 index 00000000..f4f36500 --- /dev/null +++ b/app/test/features/templates/data/template_test_support.dart @@ -0,0 +1,47 @@ +import 'package:pipelines_app/core/api_gateway.dart'; + +/// A recording gateway: it captures every request and answers from [replies]. +class RecordingGateway implements ApiGateway { + RecordingGateway([List replies = const []]) + : _replies = [...replies]; + + final List _replies; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add((type: type, fields: Map.from(fields))); + return _replies.removeAt(0); + } + + @override + Stream get frames => const Stream.empty(); +} + +/// A gateway that refuses every request with the same server error object. +class RefusingGateway implements ApiGateway { + RefusingGateway(this.refusal); + + final Object refusal; + final List calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add(type); + throw refusal; + } + + @override + Stream get frames => const Stream.empty(); +} + +class ServerRefusal implements Exception { + const ServerRefusal(this.message); + final String message; + @override + String toString() => message; +} + +/// A source with Unicode, tabs, newlines and significant leading/trailing +/// whitespace: every request must carry it unchanged. +const source = ' name: "café"\n\tstages:\n - key: "añadir" 😀 \n'; From 2c105074aac8aea01d21593258aded6c4525ac5d Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 15:31:43 +0100 Subject: [PATCH 46/84] feat(app): add graph domain model for runs and definitions Pure-Dart graph foundation mirroring the current web client: terminal targets and labels, definition edges and nodes with web outcome ordering, recorded run evidence (visited stages, taken routes, current stage and live start), and sequence-ordered stage visit selection with clamping. No layout, widgets, screens or coordinates; fixtures cover linear, diamond, self-loop, repeated visits, mixed outcomes, terminals and missing/malformed evidence. --- .../graph/domain/graph_definition.dart | 152 ++++++++++++ .../features/graph/domain/graph_protocol.dart | 43 ++++ .../graph/domain/run_graph_state.dart | 124 ++++++++++ .../features/graph/domain/stage_visits.dart | 107 ++++++++ app/notes/P2a.md | 112 +++++++++ .../graph/domain/graph_definition_test.dart | 229 ++++++++++++++++++ .../features/graph/domain/graph_fixtures.dart | 96 ++++++++ .../graph/domain/graph_protocol_test.dart | 56 +++++ .../domain/run_graph_state_live_test.dart | 91 +++++++ .../graph/domain/run_graph_state_test.dart | 170 +++++++++++++ .../graph/domain/stage_visits_test.dart | 150 ++++++++++++ 11 files changed, 1330 insertions(+) create mode 100644 app/lib/features/graph/domain/graph_definition.dart create mode 100644 app/lib/features/graph/domain/graph_protocol.dart create mode 100644 app/lib/features/graph/domain/run_graph_state.dart create mode 100644 app/lib/features/graph/domain/stage_visits.dart create mode 100644 app/notes/P2a.md create mode 100644 app/test/features/graph/domain/graph_definition_test.dart create mode 100644 app/test/features/graph/domain/graph_fixtures.dart create mode 100644 app/test/features/graph/domain/graph_protocol_test.dart create mode 100644 app/test/features/graph/domain/run_graph_state_live_test.dart create mode 100644 app/test/features/graph/domain/run_graph_state_test.dart create mode 100644 app/test/features/graph/domain/stage_visits_test.dart diff --git a/app/lib/features/graph/domain/graph_definition.dart b/app/lib/features/graph/domain/graph_definition.dart new file mode 100644 index 00000000..60735fa9 --- /dev/null +++ b/app/lib/features/graph/domain/graph_definition.dart @@ -0,0 +1,152 @@ +import 'graph_protocol.dart'; + +/// The graph definition: nodes and edges declared by a pipeline, never the +/// evidence that a run executed them. Run evidence lives in +/// `run_graph_state.dart`; keeping the two shapes separate means a definition +/// can be drawn without claiming a visit happened. +/// +/// Mirrors `stageOutcomes`, `edgeLabel`, `graphEdges` and `nodeDisplayLabel` +/// from `web/src/graph.js` (and `web/src/runDetail.js`). Pure data only. + +/// Ordering priority: success first, error last, every other outcome +/// alphabetical in between (the web client's `outcomePriority`). +int _outcomePriority(String outcome) { + if (outcome == 'success') return 0; + if (outcome == 'error') return 2; + return 1; +} + +/// A stage's edge outcomes in the app's one stable order. +List stageOutcomes(dynamic stage) { + final edges = stage is Map ? stage['edges'] : null; + if (edges is! Map) return const []; + final outcomes = edges.keys.map((key) => '$key').toList(); + outcomes.sort((a, b) { + final priority = _outcomePriority(a) - _outcomePriority(b); + return priority != 0 ? priority : a.compareTo(b); + }); + return outcomes; +} + +/// The outcome label on an edge: `error*` for an implicit fallback error route. +String edgeLabel(dynamic stage, String outcome) { + final implicitFallback = stage is Map && stage['fallback_error'] == true; + return outcome == 'error' && implicitFallback ? 'error*' : outcome; +} + +/// One declared edge, in stable definition order. +class GraphEdge { + const GraphEdge({ + required this.id, + required this.source, + required this.outcome, + required this.target, + required this.label, + required this.fallback, + required this.knownTarget, + }); + + /// The 1-based id assigned in stable definition order (`Graph.edges()`). + final int id; + final String source; + final String outcome; + + /// The resolved target: `#` has already become `#success`/`#failure`. + final String target; + final String label; + + /// True only for the parser's implicit `error -> #failure` route. + final bool fallback; + + /// True when [target] is a terminal or a stage declared in this graph. + /// + /// An empty or unknown target is kept exactly as recorded, with this flag + /// false, so callers can show it honestly instead of inventing a node. + final bool knownTarget; + + bool get isTerminal => isTerminalTarget(target); +} + +/// One graph definition node: a declared stage, or a terminal the definition +/// routes to. +class GraphNode { + const GraphNode({required this.key, required this.terminal, this.stageIndex}); + + final String key; + final bool terminal; + + /// The node's stage declaration index, or null for a terminal. + final int? stageIndex; + + String get label => nodeDisplayLabel(key); + String get shortLabel => nodeLabel(key); +} + +List> _stages(dynamic graph) { + if (graph is! Map) return const >[]; + final stages = graph['stages']; + if (stages is! List) return const >[]; + return stages.whereType().map(Map.from).toList(); +} + +String _stageKey(Map stage) => '${stage['key'] ?? ''}'; + +/// Every definition edge in stable id order. +/// +/// Stages keep declaration order and each stage's outcomes use +/// [stageOutcomes]; ids are contiguous in that order. An absent (null) edge +/// value declares no edge and is skipped, while an empty or unknown target is +/// preserved with [GraphEdge.knownTarget] false. +List graphEdges(dynamic graph) { + final stages = _stages(graph); + final stageKeys = { + for (final stage in stages) + if (_stageKey(stage).isNotEmpty) _stageKey(stage), + }; + final result = []; + for (final stage in stages) { + final edges = stage['edges']; + if (edges is! Map) continue; + final source = _stageKey(stage); + for (final outcome in stageOutcomes(stage)) { + final raw = edges[outcome]; + if (raw == null) continue; + final target = resolveTarget(outcome, '$raw') ?? ''; + result.add( + GraphEdge( + id: result.length + 1, + source: source, + outcome: outcome, + target: target, + label: edgeLabel(stage, outcome), + fallback: outcome == 'error' && stage['fallback_error'] == true, + knownTarget: isTerminalTarget(target) || stageKeys.contains(target), + ), + ); + } + } + return result; +} + +/// The definition's nodes in declaration order. +/// +/// A stage key identifies one node even when it is declared twice; self edges +/// and loops therefore never duplicate identity. Terminal nodes are appended +/// failure first, then success, once any declared edge resolves to a terminal +/// (the same `hasTerminal` rule the web layout uses). They are still +/// definition nodes, not evidence that a run reached them. +List graphNodes(dynamic graph) { + final stages = _stages(graph); + final seen = {}; + final nodes = []; + for (var index = 0; index < stages.length; index += 1) { + final key = _stageKey(stages[index]); + if (key.isEmpty || !seen.add(key)) continue; + nodes.add(GraphNode(key: key, terminal: false, stageIndex: index)); + } + if (graphEdges(graph).any((edge) => edge.isTerminal)) { + nodes.add(const GraphNode(key: failureEnd, terminal: true)); + nodes.add(const GraphNode(key: successEnd, terminal: true)); + } + return nodes; +} diff --git a/app/lib/features/graph/domain/graph_protocol.dart b/app/lib/features/graph/domain/graph_protocol.dart new file mode 100644 index 00000000..a033884c --- /dev/null +++ b/app/lib/features/graph/domain/graph_protocol.dart @@ -0,0 +1,43 @@ +/// Protocol terminal targets and the labels the graph uses for them. +/// +/// Mirrors `web/src/protocol.js` (`SUCCESS_END`, `FAILURE_END`, +/// `isTerminal`, `resolveTarget`) and the label helpers in `web/src/graph.js`. +/// Pure Dart: no Flutter imports and no layout or rendering decisions. +library; + +/// The explicit success terminal (`Protocol.SUCCESS_END`). +const String successEnd = '#success'; + +/// The explicit failure terminal (`Protocol.FAILURE_END`). +const String failureEnd = '#failure'; + +/// True only for the two explicit terminal targets. +/// +/// A bare `#` is not itself terminal; [resolveTarget] turns it into one using +/// the outcome, exactly as the server and the web client do. +bool isTerminalTarget(String? target) => + target == successEnd || target == failureEnd; + +/// Mirrors `Protocol.resolveTarget`: a bare `#` is the outcome's terminal. +/// +/// Every other value is preserved verbatim, including an empty or unknown +/// stage key. A missing target stays null rather than becoming a terminal, so +/// a blank edge cannot fabricate a visit or a terminal node. +String? resolveTarget(String? outcome, String? target) { + if (target != '#') return target; + return outcome == 'error' ? failureEnd : successEnd; +} + +/// A graph node title: a stage keeps its key, a terminal reads Success/Failure. +String nodeDisplayLabel(String? key) { + if (key == successEnd) return 'Success'; + if (key == failureEnd) return 'Failure'; + return key ?? ''; +} + +/// The TUI-mirroring label: terminal targets are all caps. +String nodeLabel(String? key) { + if (key == successEnd) return 'SUCCESS'; + if (key == failureEnd) return 'FAILURE'; + return key ?? ''; +} diff --git a/app/lib/features/graph/domain/run_graph_state.dart b/app/lib/features/graph/domain/run_graph_state.dart new file mode 100644 index 00000000..ef3fb8be --- /dev/null +++ b/app/lib/features/graph/domain/run_graph_state.dart @@ -0,0 +1,124 @@ +import 'graph_protocol.dart'; + +/// Which stages and routes a run actually recorded. +/// +/// This is executed-route evidence, deliberately distinct from the graph +/// definition's nodes and edges. It mirrors `runGraphState` from +/// `web/src/runDetail.js` (Android `RunGraphState.from`): every recorded step's +/// stage is visited once in first-appearance order, a step with a non-blank +/// outcome and target contributes one deduplicated `source\0outcome\0target` +/// route, and only a resolved terminal is added by its target. A non-terminal +/// target is not visited until a step lands on it. +/// +/// The run map is the same detail produced by the runs feature; this helper +/// reads recorded steps and never folds live events a second time. +class RunGraphState { + RunGraphState({ + required List visitedStages, + required List takenRoutes, + required this.currentStage, + required this.executing, + required this.currentStageStartedAt, + }) : visitedStages = List.unmodifiable(visitedStages), + takenRoutes = List.unmodifiable(takenRoutes); + + /// Visited stage keys in first-appearance order, without duplicates. + final List visitedStages; + + /// Taken routes as `source\0outcome\0resolvedTarget`, in recorded order. + final List takenRoutes; + + /// The run's current stage, else the last recorded visit's stage, else null. + final String? currentStage; + final bool executing; + + /// The running visit's start for [currentStage], only while executing. + final String? currentStageStartedAt; + + bool isStageVisited(String key) => visitedStages.contains(key); + + /// True when a recorded visit took this definition route. The target is + /// resolved with the same `#` rule the definition edges use. + bool isRouteTaken(String source, String outcome, String target) { + final resolved = resolveTarget(outcome, target); + if (resolved == null || resolved.isEmpty) return false; + return takenRoutes.contains('$source\u0000$outcome\u0000$resolved'); + } + + /// The active stage for a live run, else null. A finished run has none. + String? get activeStage { + if (!executing || currentStage == null || currentStage!.isEmpty) { + return null; + } + return currentStage; + } +} + +List> _steps(dynamic run) { + if (run is! Map) return const >[]; + final steps = run['steps']; + if (steps is! List) return const >[]; + return steps.whereType().map(Map.from).toList(); +} + +String _text(dynamic value) => '${value ?? ''}'; + +/// Derives [RunGraphState] from one run detail map. +/// +/// Missing or malformed steps yield no visits and no routes; nothing is +/// fabricated from a missing capture. Repeated visits stay one identity per +/// stage, and self edges or loops never recurse. +RunGraphState runGraphState(dynamic run) { + final steps = _steps(run); + final visitedStages = []; + final seenStages = {}; + final takenRoutes = []; + final seenRoutes = {}; + + void visit(String? key) { + if (key == null || key.isEmpty || !seenStages.add(key)) return; + visitedStages.add(key); + } + + for (final step in steps) { + final stage = _text(step['stage']); + if (stage.isNotEmpty) visit(stage); + + final outcome = _text(step['outcome']); + final target = _text(step['target']); + if (outcome.trim().isEmpty || target.trim().isEmpty) continue; + + final resolved = resolveTarget(outcome, target); + if (resolved == null || resolved.isEmpty) continue; + final route = '$stage\u0000$outcome\u0000$resolved'; + if (seenRoutes.add(route)) takenRoutes.add(route); + if (isTerminalTarget(resolved)) visit(resolved); + } + + final lastStage = steps.isEmpty ? '' : _text(steps.last['stage']); + final rawCurrent = _text(run is Map ? run['current_stage'] : null); + final currentStage = rawCurrent.trim().isNotEmpty + ? rawCurrent + : (lastStage.trim().isNotEmpty ? lastStage : null); + final executing = run is Map && run['executing'] == true; + + String? currentStageStartedAt; + if (executing && currentStage != null) { + for (var index = steps.length - 1; index >= 0; index -= 1) { + final step = steps[index]; + if (_text(step['stage']) != currentStage) continue; + if (_text(step['status']) != 'running') continue; + final started = _text(step['started_at']); + if (started.trim().isNotEmpty) currentStageStartedAt = started; + break; + } + } + + return RunGraphState( + visitedStages: visitedStages, + takenRoutes: takenRoutes, + currentStage: currentStage, + executing: executing, + currentStageStartedAt: currentStageStartedAt, + ); +} diff --git a/app/lib/features/graph/domain/stage_visits.dart b/app/lib/features/graph/domain/stage_visits.dart new file mode 100644 index 00000000..4a546cfa --- /dev/null +++ b/app/lib/features/graph/domain/stage_visits.dart @@ -0,0 +1,107 @@ +import '../../../core/api_gateway.dart'; + +/// Recorded stage-visit selection, matching the web client's timeline and +/// stage pane. Visits are ordered by their recorded sequence, never by the +/// order a caller happens to pass them in; repeated visits to one stage stay +/// separate entries. Pure data: no widgets, layout or coordinates. + +int _sequenceOf(JsonMap step) { + final sequence = step['sequence']; + return sequence is num ? sequence.toInt() : 0; +} + +int _positiveVisit(dynamic control) { + if (control is! Map) return 0; + final visit = control['visit']; + if (visit is num) return visit > 0 ? visit.toInt() : 0; + return int.tryParse('${visit ?? ''}') ?? 0; +} + +/// The visit number a timeline row shows: the recorded `control.visit` when it +/// is positive, else the position within the stage's ordered visits. +int displayVisit(JsonMap step, int index) { + final recorded = _positiveVisit(step['control']); + return recorded > 0 ? recorded : index + 1; +} + +/// Clamps a visit index into `[0, count)`; an empty list yields 0. +int clampVisitIndex(int index, int count) { + if (count <= 0) return 0; + if (index < 0) return 0; + return index >= count ? count - 1 : index; +} + +List _ordered(List visits) { + final indexed = <({int position, JsonMap step})>[ + for (var index = 0; index < visits.length; index += 1) + (position: index, step: visits[index]), + ]; + indexed.sort((a, b) { + final bySequence = _sequenceOf(a.step).compareTo(_sequenceOf(b.step)); + return bySequence != 0 ? bySequence : a.position.compareTo(b.position); + }); + return [for (final entry in indexed) entry.step]; +} + +/// Every stage's recorded visits, ordered by sequence. +/// +/// The map keeps stage first-appearance order. Equal sequences keep their +/// recorded order (the web client's stable sort), and a stage with no recorded +/// visit is simply absent rather than present with a synthetic visit. +Map> visitsByStage(List steps) { + final grouped = >{}; + for (final step in steps) { + final stage = '${step['stage'] ?? ''}'; + grouped.putIfAbsent(stage, () => []).add(step); + } + return >{ + for (final entry in grouped.entries) entry.key: _ordered(entry.value), + }; +} + +/// One selected stage visit. [step] is null when the stage has no recorded +/// visit, so callers cannot mistake an absent capture for an execution. +class StageVisitSelection { + const StageVisitSelection({ + required this.stageKey, + required this.visits, + required this.index, + }); + + final String stageKey; + + /// The stage's visits ordered by sequence. + final List visits; + + /// The clamped index into [visits]; 0 when there are none. + final int index; + + bool get hasVisit => visits.isNotEmpty; + JsonMap? get step => hasVisit ? visits[index] : null; + int get visitNumber => step == null ? 0 : displayVisit(step!, index); + + /// True when an explicit requested index was clamped, so a caller can + /// correct its route exactly as the web stage route does. + bool correctedRequest(int? requested) => + requested != null && requested != index; +} + +/// Selects a stage's visit exactly as the web stage pane does. +/// +/// A null [visitIndex] means the stage's most recent recorded visit; an +/// out-of-range index is clamped to the last visit (negative values to the +/// first). A stage with no recorded visits returns [StageVisitSelection.step] +/// null instead of a fabricated visit. +StageVisitSelection selectStageVisit( + List steps, + String stageKey, { + int? visitIndex, +}) { + final visits = visitsByStage(steps)[stageKey] ?? const []; + final wanted = visitIndex ?? (visits.isEmpty ? 0 : visits.length - 1); + return StageVisitSelection( + stageKey: stageKey, + visits: visits, + index: clampVisitIndex(wanted, visits.length), + ); +} diff --git a/app/notes/P2a.md b/app/notes/P2a.md new file mode 100644 index 00000000..2e7d1e48 --- /dev/null +++ b/app/notes/P2a.md @@ -0,0 +1,112 @@ +# P2a — graph domain: nodes, edges, terminals, run evidence and stage visits + +## What changed + +New, app-only, pure-Dart files. No server, web client, legacy client, shell, +`main.dart`, pubspec, other feature or platform source was edited. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/graph/domain/graph_protocol.dart` | 43 | terminal constants, `resolveTarget`, terminal labels | +| `lib/features/graph/domain/graph_definition.dart` | 152 | outcome/edge order, definition edges, definition nodes | +| `lib/features/graph/domain/run_graph_state.dart` | 124 | recorded visited stages/routes, current-stage fallback, live start | +| `lib/features/graph/domain/stage_visits.dart` | 107 | sequence-ordered visits, display visit, clamped visit selection | +| `test/features/graph/domain/graph_fixtures.dart` | 96 | linear/diamond/self-loop/incomplete definitions and step fixtures | +| `test/features/graph/domain/graph_protocol_test.dart` | 56 | shorthand and terminal-label regressions | +| `test/features/graph/domain/graph_definition_test.dart` | 229 | edge order/ids, loops, duplicate keys, missing/unknown targets | +| `test/features/graph/domain/run_graph_state_test.dart` | 170 | linear/diamond/self-loop/repeated visits/outcomes/terminals/no evidence | +| `test/features/graph/domain/run_graph_state_live_test.dart` | 91 | current/last-stage fallback, live start, finished run | +| `test/features/graph/domain/stage_visits_test.dart` | 150 | repeated visits by sequence, latest default, clamping, absent visit | + +No layout, coordinates, widgets, styles or rendering were added. + +## Behavior copied from the current web client + +- **Terminals and `#`** (`web/src/protocol.js`): `#success`, `#failure`, + `isTerminal` only for the explicit keys, and `resolveTarget`: a bare `#` + becomes `#failure` for the `error` outcome and `#success` for every other + outcome. All other values are preserved verbatim, including `""` and unknown + stage keys. A missing target stays `null`, never a fabricated terminal. +- **Labels** (`web/src/graph.js`): `nodeDisplayLabel` gives `Success` / + `Failure` for graph nodes; `nodeLabel` gives the TUI-mirroring `SUCCESS` / + `FAILURE`. Stage keys are unchanged. +- **Definition edges** (`web/src/graph.js`): outcomes are success first, other + outcomes alphabetical, `error` last; stages keep declaration order; ids are + contiguous in that order; the label carries `error*` only when + `fallback_error` is true. A `null` edge value declares no edge and is + skipped. Empty/unknown targets are kept, with `knownTarget == false`. +- **Definition nodes** (`web/src/graph.js` `layoutGraph`): stage nodes keep + declaration order and one identity per key; terminal nodes are appended + failure then success once any declared edge resolves to a terminal. These + are definition nodes only, never run evidence. +- **Run evidence** (`web/src/runDetail.js` `runGraphState`): visited stages in + first-appearance order without duplicates; routes keyed + `source\0outcome\0resolvedTarget` without duplicates; only a resolved + terminal is visited by its target; a non-terminal target is not visited until + a step lands there. Current stage is `current_stage` when non-blank, else the + last recorded step's stage, else `null`. A start timestamp is read only while + executing, for a `running` visit of the current stage. +- **Visits** (`web/src/runDetail.js` `runTimeline`, `clampVisitIndex`, + `displayVisit`, and `web/src/app.js` stage routing): visits are grouped by + stage and ordered by recorded sequence with stable ties; the display visit + is a positive `control.visit`, else position + 1; no requested visit selects + the stage's most recent visit; an explicit index clamps to `[0, count)`; a + stage with no recorded visit yields `step == null`. + +The run map is the same detail the runs feature already holds; this slice only +reads `steps`, so it adds no second event fold. Live-event merging remains in +`lib/features/runs/domain/run_step_evidence.dart` and `run_events.dart`. + +## Honest edge handling + +- A missing/`null` definition edge produces no edge and no node. +- An empty or unknown target is returned as recorded, flagged `knownTarget: + false`; it never becomes a stage node or terminal and never produces a + visited stage. +- A blank recorded stage key is not turned into an empty visited identity. A + step with a blank outcome or target records no route and no terminal visit. +- Self edges and loops record one route and one node identity; nothing recurses. +- A stage with no recorded visits cannot be presented as visited: selection + exposes a null step rather than synthesizing one. + +## Checks actually run + +``` +flutter pub get +dart format lib/features/graph test/features/graph # 10 files, 0 changed after formatting +flutter test test/features/graph/domain # 41 passed +flutter analyze # No issues found! (0.8s) +flutter test # 139 passed +``` + +Focused coverage is the requested matrix: + +- **Linear**: plan -> build -> ship, contiguous ids, implicit `error*` + fallback, terminals. +- **Diamond**: fan-out/fan-in edges stay distinct and ordered; converging + routes do not merge. +- **Self loop**: `a/retry -> a` is one edge and one node identity; one run + self-loop is one route and one visited stage. +- **Repeated stage**: repeated visits remain separate ordered entries; visited + stage identity is not duplicated; repeated identical routes collapse. +- **Different outcomes**: success/approved/rejected routes to the same target + remain distinct. +- **Terminals**: bare `#` resolves by outcome, explicit terminals normalize, + labels are `SUCCESS`/`FAILURE`, mid-run targets do not fabricate visits. +- **Missing evidence**: null/absent/malformed steps and graphs yield empty + evidence, no terminals and no fabricated visits. + +## Honest limits + +- **No UI, layout or wiring.** This is deliberately the nonvisual foundation + slice; the native graph screen, layout, highlighting and interaction are + later work and are not claimed here. +- **No browser evidence.** A nonvisual pure-Dart change has no rendered + behavior to capture; no browser or screenshot check applies. +- **No live server or device used.** All tests use local fixtures. No run, + pipeline, schedule, workflow or service was created, changed or restarted. +- **Mobile unverified.** Only web-targeted Flutter tests and analysis ran; no + Android/iOS build, emulator, ADB or device. +- **Not committed, pushed or deployed.** The stage instruction for this visit + forbids commit/push/deploy, so the candidate remains as new untracked files + in the `flutter/p2-model` worktree for the manager to inspect and land. diff --git a/app/test/features/graph/domain/graph_definition_test.dart b/app/test/features/graph/domain/graph_definition_test.dart new file mode 100644 index 00000000..deb13d62 --- /dev/null +++ b/app/test/features/graph/domain/graph_definition_test.dart @@ -0,0 +1,229 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; + +import 'graph_fixtures.dart'; + +void main() { + group('outcome and edge order', () { + test('success first, other outcomes alphabetical, error last', () { + expect( + stageOutcomes( + stage( + 'a', + edges: { + 'error': '#', + 'rejected': 'a', + 'success': 'b', + 'approved': 'b', + 'retry': 'a', + }, + ), + ), + ['success', 'approved', 'rejected', 'retry', 'error'], + ); + expect(stageOutcomes({}), isEmpty); + expect(stageOutcomes(null), isEmpty); + }); + + test('edgeLabel marks only an implicit fallback error route', () { + expect( + edgeLabel({'fallback_error': true}, 'error'), + 'error*', + ); + expect( + edgeLabel({'fallback_error': false}, 'error'), + 'error', + ); + expect( + edgeLabel({'fallback_error': true}, 'success'), + 'success', + ); + expect(edgeLabel({}, 'rejected'), 'rejected'); + }); + }); + + group('linear definition', () { + test('edges keep stage and outcome order with contiguous ids', () { + final edges = graphEdges(linearGraph()); + expect(edges.map((edge) => edge.id), [1, 2, 3, 4, 5]); + expect(edges.map((edge) => edge.source), [ + 'plan', + 'plan', + 'build', + 'ship', + 'ship', + ]); + expect(edges.map((edge) => edge.outcome), [ + 'success', + 'error', + 'success', + 'success', + 'error', + ]); + expect(edges.map((edge) => edge.target), [ + 'build', + '#failure', + 'ship', + '#success', + '#failure', + ]); + expect(edges.map((edge) => edge.label), [ + 'success', + 'error*', + 'success', + 'success', + 'error', + ]); + expect(edges.where((edge) => edge.fallback).map((edge) => edge.id), [ + 2, + ]); + expect(edges.every((edge) => edge.knownTarget), isTrue); + }); + + test('nodes are declaration order plus failure then success terminals', () { + final nodes = graphNodes(linearGraph()); + expect(nodes.map((node) => node.key), [ + 'plan', + 'build', + 'ship', + failureEnd, + successEnd, + ]); + expect(nodes.map((node) => node.stageIndex), [0, 1, 2, null, null]); + expect(nodes.map((node) => node.terminal), [ + false, + false, + false, + true, + true, + ]); + expect(nodes[3].label, 'Failure'); + expect(nodes[3].shortLabel, 'FAILURE'); + expect(nodes[4].label, 'Success'); + expect(nodes[4].shortLabel, 'SUCCESS'); + }); + }); + + group('diamond definition', () { + test('keeps every converging edge distinct in stable order', () { + final edges = graphEdges(diamondGraph()); + expect( + edges.map((edge) => '${edge.source}/${edge.outcome}->${edge.target}'), + [ + 'a/success->b', + 'a/approved->c', + 'a/error->#failure', + 'b/success->d', + 'c/success->d', + 'd/success->#success', + ], + ); + expect(edges.every((edge) => edge.knownTarget), isTrue); + }); + }); + + group('self loops', () { + test('a self edge is one edge and never duplicates node identity', () { + final graph = selfLoopGraph(); + final edges = graphEdges(graph); + expect( + edges.map((edge) => '${edge.source}/${edge.outcome}->${edge.target}'), + [ + 'a/success->b', + 'a/retry->a', + 'b/success->#success', + 'b/error->#failure', + ], + ); + expect(edges[1].source, edges[1].target); + expect(edges[1].knownTarget, isTrue); + + final nodes = graphNodes(graph); + expect(nodes.map((node) => node.key), [ + 'a', + 'b', + failureEnd, + successEnd, + ]); + expect(nodes.where((node) => node.key == 'a'), hasLength(1)); + }); + + test( + 'a stage declared twice keeps one node and one set of edges per key', + () { + final graph = { + 'stages': [ + stage('a', edges: {'retry': 'a'}), + stage('a', edges: {'success': '#success'}), + ], + }; + expect(graphNodes(graph).map((node) => node.key), [ + 'a', + failureEnd, + successEnd, + ]); + // Both declarations are still definition data, with unique edge ids. + expect(graphEdges(graph).map((edge) => edge.id), [1, 2]); + }, + ); + }); + + group('missing and unknown targets', () { + test( + 'an absent edge declares nothing; empty and unknown targets stay honest', + () { + final edges = graphEdges(incompleteGraph()); + expect(edges.map((edge) => edge.id), [1, 2, 3, 4]); + expect(edges.map((edge) => edge.outcome), [ + 'blocked', + 'retry', + 'error', + 'success', + ]); + expect(edges[0].target, ''); + expect(edges[0].knownTarget, isFalse); + expect(edges[1].target, 'ghost'); + expect(edges[1].knownTarget, isFalse); + expect(edges[2].target, failureEnd); + expect(edges[2].fallback, isTrue); + expect(edges[3].target, successEnd); + }, + ); + + test('an unknown target does not become a node or a terminal', () { + final graph = { + 'stages': [ + stage('a', edges: {'retry': 'ghost'}), + ], + }; + expect(graphNodes(graph).map((node) => node.key), ['a']); + expect(graphEdges(graph).single.knownTarget, isFalse); + }); + + test('a graph with no stages has no nodes or edges', () { + expect(graphNodes({}), isEmpty); + expect(graphEdges({'stages': null}), isEmpty); + expect(graphNodes(null), isEmpty); + }); + }); + + test( + 'definition nodes ignore run evidence even when the graph map carries it', + () { + final graph = { + 'stages': [ + stage('a', edges: {'success': 'b'}), + stage('b'), + ], + 'steps': [ + step(sequence: 1, stage: 'a', outcome: 'success', target: 'b'), + ], + 'visited_stages': ['a', 'b'], + }; + final nodes = graphNodes(graph); + expect(nodes.map((node) => node.key), ['a', 'b']); + expect(nodes.every((node) => !node.terminal), isTrue); + }, + ); +} diff --git a/app/test/features/graph/domain/graph_fixtures.dart b/app/test/features/graph/domain/graph_fixtures.dart new file mode 100644 index 00000000..3a074221 --- /dev/null +++ b/app/test/features/graph/domain/graph_fixtures.dart @@ -0,0 +1,96 @@ +import 'package:pipelines_app/core/api_gateway.dart'; + +/// Small, server-shaped fixtures shared by the graph domain tests. + +JsonMap step({ + int sequence = 0, + String stage = '', + String status = 'completed', + String outcome = '', + String target = '', + String startedAt = '', + Map? control, +}) { + return { + 'sequence': sequence, + 'stage': stage, + 'status': status, + 'outcome': outcome, + 'target': target, + if (startedAt.isNotEmpty) 'started_at': startedAt, + 'control': ?control, + }; +} + +JsonMap stage( + String key, { + Map edges = const {}, + bool fallbackError = false, + String type = 'model', +}) { + return { + 'key': key, + 'type': type, + 'edges': edges, + if (fallbackError) 'fallback_error': true, + }; +} + +/// plan -> build -> ship, with an implicit failure fallback on plan and an +/// explicit terminal pair on ship. +JsonMap linearGraph() => { + 'stages': [ + stage( + 'plan', + edges: {'success': 'build', 'error': '#'}, + fallbackError: true, + ), + stage('build', edges: {'success': 'ship'}), + stage( + 'ship', + edges: {'success': '#success', 'error': '#failure'}, + ), + ], +}; + +/// a fans out to b/c and both converge on d. +JsonMap diamondGraph() => { + 'stages': [ + stage( + 'a', + edges: {'success': 'b', 'approved': 'c', 'error': '#'}, + fallbackError: true, + ), + stage('b', edges: {'success': 'd'}), + stage('c', edges: {'success': 'd'}), + stage('d', edges: {'success': '#success'}), + ], +}; + +/// a retries itself and can still succeed into b; terminal pair on b. +JsonMap selfLoopGraph() => { + 'stages': [ + stage('a', edges: {'success': 'b', 'retry': 'a'}), + stage( + 'b', + edges: {'success': '#success', 'error': '#failure'}, + ), + ], +}; + +/// A definition with an absent edge, an empty target and an unknown target. +JsonMap incompleteGraph() => { + 'stages': [ + stage( + 'a', + edges: { + 'success': null, + 'blocked': '', + 'retry': 'ghost', + 'error': '#', + }, + fallbackError: true, + ), + stage('b', edges: {'success': '#success'}), + ], +}; diff --git a/app/test/features/graph/domain/graph_protocol_test.dart b/app/test/features/graph/domain/graph_protocol_test.dart new file mode 100644 index 00000000..972fc77e --- /dev/null +++ b/app/test/features/graph/domain/graph_protocol_test.dart @@ -0,0 +1,56 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; + +void main() { + group('terminal target normalization', () { + test('a bare # resolves by outcome exactly like the web protocol', () { + expect(resolveTarget('error', '#'), failureEnd); + expect(resolveTarget('success', '#'), successEnd); + expect(resolveTarget('approved', '#'), successEnd); + expect(resolveTarget('', '#'), successEnd); + }); + + test('explicit, empty and unknown targets are preserved verbatim', () { + expect(resolveTarget('success', successEnd), successEnd); + expect(resolveTarget('error', failureEnd), failureEnd); + expect(resolveTarget('success', 'review'), 'review'); + expect(resolveTarget('blocked', ''), ''); + expect(resolveTarget('retry', 'ghost'), 'ghost'); + expect(resolveTarget('success', ' #success'), ' #success'); + }); + + test( + 'a missing target stays missing instead of fabricating a terminal', + () { + expect(resolveTarget('success', null), isNull); + expect(resolveTarget(null, null), isNull); + }, + ); + + test('only the explicit terminal keys are terminals', () { + expect(isTerminalTarget(successEnd), isTrue); + expect(isTerminalTarget(failureEnd), isTrue); + expect(isTerminalTarget('#'), isFalse); + expect(isTerminalTarget('review'), isFalse); + expect(isTerminalTarget(''), isFalse); + expect(isTerminalTarget(null), isFalse); + }); + }); + + group('terminal labels', () { + test('TUI labels are SUCCESS and FAILURE', () { + expect(nodeLabel(successEnd), 'SUCCESS'); + expect(nodeLabel(failureEnd), 'FAILURE'); + expect(nodeLabel('implementer'), 'implementer'); + expect(nodeLabel(''), ''); + expect(nodeLabel(null), ''); + }); + + test('display labels title-case the terminals and keep stage keys', () { + expect(nodeDisplayLabel(successEnd), 'Success'); + expect(nodeDisplayLabel(failureEnd), 'Failure'); + expect(nodeDisplayLabel('implementer'), 'implementer'); + expect(nodeDisplayLabel(null), ''); + }); + }); +} diff --git a/app/test/features/graph/domain/run_graph_state_live_test.dart b/app/test/features/graph/domain/run_graph_state_live_test.dart new file mode 100644 index 00000000..18244107 --- /dev/null +++ b/app/test/features/graph/domain/run_graph_state_live_test.dart @@ -0,0 +1,91 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/run_graph_state.dart'; + +import 'graph_fixtures.dart'; + +void main() { + group('current stage fallback', () { + test('the run current stage wins over the last recorded visit', () { + final state = runGraphState({ + 'current_stage': 'committer', + 'steps': [step(sequence: 1, stage: 'review')], + }); + expect(state.currentStage, 'committer'); + }); + + test('a blank current stage falls back to the last visit, else null', () { + final fallback = runGraphState({ + 'current_stage': ' ', + 'steps': [ + step(sequence: 1, stage: 'a'), + step(sequence: 2, stage: 'b'), + ], + }); + expect(fallback.currentStage, 'b'); + + final blankLast = runGraphState({ + 'steps': [step(sequence: 1)], + }); + expect(blankLast.currentStage, isNull); + }); + }); + + group('active stage and start', () { + test('a live run exposes its running visit start', () { + final state = runGraphState({ + 'executing': true, + 'current_stage': 'review', + 'steps': [ + step( + sequence: 1, + stage: 'review', + status: 'running', + startedAt: '2026-01-01T00:00:00Z', + ), + ], + }); + expect(state.executing, isTrue); + expect(state.activeStage, 'review'); + expect(state.currentStageStartedAt, '2026-01-01T00:00:00Z'); + }); + + test('a finished run has no active stage or start', () { + final state = runGraphState({ + 'executing': false, + 'current_stage': 'review', + 'steps': [ + step( + sequence: 1, + stage: 'review', + status: 'running', + startedAt: '2026-01-01T00:00:00Z', + ), + ], + }); + expect(state.activeStage, isNull); + expect(state.currentStageStartedAt, isNull); + }); + + test('only an exact running status with a non-blank start is used', () { + final state = runGraphState({ + 'executing': true, + 'current_stage': 'review', + 'steps': [ + step( + sequence: 1, + stage: 'review', + status: 'Running', + startedAt: '2026-01-01T00:00:00Z', + ), + step( + sequence: 2, + stage: 'review', + status: 'running', + startedAt: ' ', + ), + ], + }); + expect(state.currentStageStartedAt, isNull); + }); + }); +} diff --git a/app/test/features/graph/domain/run_graph_state_test.dart b/app/test/features/graph/domain/run_graph_state_test.dart new file mode 100644 index 00000000..3af43777 --- /dev/null +++ b/app/test/features/graph/domain/run_graph_state_test.dart @@ -0,0 +1,170 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/domain/run_graph_state.dart'; + +import 'graph_fixtures.dart'; + +void main() { + group('linear run evidence', () { + test('visits and routes follow the recorded visits', () { + final state = runGraphState({ + 'executing': false, + 'steps': [ + step(sequence: 1, stage: 'plan', outcome: 'success', target: 'build'), + step(sequence: 2, stage: 'build', outcome: 'success', target: 'ship'), + step( + sequence: 3, + stage: 'ship', + outcome: 'success', + target: '#success', + ), + ], + }); + expect(state.visitedStages, [ + 'plan', + 'build', + 'ship', + successEnd, + ]); + expect(state.takenRoutes, [ + 'plan\u0000success\u0000build', + 'build\u0000success\u0000ship', + 'ship\u0000success\u0000#success', + ]); + expect(state.currentStage, 'ship'); + expect(state.executing, isFalse); + expect(state.currentStageStartedAt, isNull); + expect(state.activeStage, isNull); + }); + }); + + group('diamond run evidence', () { + test('repeated visits keep one identity and loop routes stay distinct', () { + final state = runGraphState({ + 'executing': false, + 'steps': [ + step(sequence: 1, stage: 'a', outcome: 'success', target: 'b'), + step(sequence: 2, stage: 'b', outcome: 'success', target: 'd'), + step(sequence: 3, stage: 'd', outcome: 'rejected', target: 'b'), + step(sequence: 4, stage: 'b', outcome: 'success', target: 'd'), + step(sequence: 5, stage: 'd', outcome: 'success', target: '#success'), + ], + }); + expect(state.visitedStages, ['a', 'b', 'd', successEnd]); + expect(state.visitedStages.where((key) => key == 'b'), hasLength(1)); + expect(state.takenRoutes, [ + 'a\u0000success\u0000b', + 'b\u0000success\u0000d', + 'd\u0000rejected\u0000b', + 'd\u0000success\u0000#success', + ]); + }); + + test('different outcomes to the same target stay separate routes', () { + final state = runGraphState({ + 'executing': false, + 'steps': [ + step(sequence: 1, stage: 'a', outcome: 'success', target: 'b'), + step(sequence: 2, stage: 'a', outcome: 'approved', target: 'b'), + step(sequence: 3, stage: 'a', outcome: 'success', target: 'b'), + ], + }); + expect(state.visitedStages, ['a']); + expect(state.takenRoutes, [ + 'a\u0000success\u0000b', + 'a\u0000approved\u0000b', + ]); + }); + }); + + group('self edges', () { + test('a self edge is evidence, not a second visit or recursion', () { + final state = runGraphState({ + 'executing': false, + 'steps': [ + step(sequence: 1, stage: 'a', outcome: 'retry', target: 'a'), + step(sequence: 2, stage: 'a', outcome: 'success', target: 'b'), + ], + }); + expect(state.visitedStages, ['a']); + expect(state.takenRoutes, [ + 'a\u0000retry\u0000a', + 'a\u0000success\u0000b', + ]); + }); + }); + + group('terminals', () { + test('a bare # resolves to failure on error and success otherwise', () { + final failed = runGraphState({ + 'steps': [ + step(sequence: 1, stage: 'impl', outcome: 'error', target: '#'), + ], + }); + expect(failed.visitedStages, ['impl', failureEnd]); + expect(failed.visitedStages, isNot(contains(successEnd))); + expect(failed.isRouteTaken('impl', 'error', '#'), isTrue); + + final succeeded = runGraphState({ + 'steps': [ + step(sequence: 1, stage: 'impl', outcome: 'done', target: '#'), + ], + }); + expect(succeeded.visitedStages, ['impl', successEnd]); + expect(succeeded.visitedStages, isNot(contains(failureEnd))); + }); + + test('a non-terminal target is not visited until a step lands on it', () { + final state = runGraphState({ + 'steps': [ + step( + sequence: 1, + stage: 'impl', + outcome: 'success', + target: 'review', + ), + ], + }); + expect(state.visitedStages, ['impl']); + expect(state.isStageVisited('review'), isFalse); + expect(state.isRouteTaken('impl', 'success', 'review'), isTrue); + }); + + test('blank outcome or target records no route and no terminal visit', () { + final state = runGraphState({ + 'steps': [ + step(sequence: 1, stage: 'impl', outcome: 'success', target: ''), + step(sequence: 2, stage: 'impl', outcome: '', target: '#success'), + ], + }); + expect(state.visitedStages, ['impl']); + expect(state.takenRoutes, isEmpty); + }); + }); + + group('missing evidence', () { + test('absent run or steps fabricates no visits', () { + for (final run in [ + null, + {}, + {'steps': null}, + {'steps': []}, + ]) { + final state = runGraphState(run); + expect(state.visitedStages, isEmpty); + expect(state.takenRoutes, isEmpty); + expect(state.currentStage, isNull); + expect(state.executing, isFalse); + expect(state.currentStageStartedAt, isNull); + } + }); + + test('malformed step entries are ignored, not invented', () { + final state = runGraphState({ + 'steps': ['nope', 42, null], + }); + expect(state.visitedStages, isEmpty); + expect(state.takenRoutes, isEmpty); + }); + }); +} diff --git a/app/test/features/graph/domain/stage_visits_test.dart b/app/test/features/graph/domain/stage_visits_test.dart new file mode 100644 index 00000000..dcf77840 --- /dev/null +++ b/app/test/features/graph/domain/stage_visits_test.dart @@ -0,0 +1,150 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/stage_visits.dart'; + +import 'graph_fixtures.dart'; + +void main() { + group('ordered stage visits', () { + test('repeated visits are ordered by sequence, not input order', () { + final steps = [ + step( + sequence: 5, + stage: 'review', + outcome: 'rejected', + target: 'implementer', + control: {'visit': 2}, + ), + step(sequence: 3, stage: 'implementer'), + step( + sequence: 2, + stage: 'review', + outcome: 'success', + target: 'done', + control: {'visit': 1}, + ), + ].cast>(); + + final byStage = visitsByStage(steps); + expect(byStage.keys, ['review', 'implementer']); + expect(byStage['review']!.map((visit) => visit['sequence']), [2, 5]); + expect(byStage['review']!.map((visit) => visit['outcome']), [ + 'success', + 'rejected', + ]); + expect(displayVisit(byStage['review']![0], 0), 1); + expect(displayVisit(byStage['review']![1], 1), 2); + }); + + test('equal sequences keep their recorded order', () { + final steps = [ + step(sequence: 1, stage: 'a', outcome: 'first'), + step(sequence: 1, stage: 'a', outcome: 'second'), + ].cast>(); + expect( + visitsByStage(steps)['a']!.map((visit) => visit['outcome']), + ['first', 'second'], + ); + }); + + test('a missing control visit falls back to the position', () { + final steps = [ + step(sequence: 1, stage: 'a'), + step(sequence: 2, stage: 'a'), + ].cast>(); + final visits = visitsByStage(steps)['a']!; + expect(displayVisit(visits[0], 0), 1); + expect(displayVisit(visits[1], 1), 2); + }); + + test( + 'a non-positive or malformed control visit falls back to position', + () { + expect( + displayVisit(step(control: {'visit': 0}), 2), + 3, + ); + expect( + displayVisit(step(control: {'visit': -1}), 2), + 3, + ); + expect( + displayVisit(step(control: {'visit': '3'}), 0), + 3, + ); + expect(displayVisit(step(), 4), 5); + }, + ); + }); + + group('clamping', () { + test('keeps a valid index and handles an empty list', () { + expect(clampVisitIndex(0, 3), 0); + expect(clampVisitIndex(2, 3), 2); + expect(clampVisitIndex(99, 3), 2); + expect(clampVisitIndex(-4, 3), 0); + expect(clampVisitIndex(5, 0), 0); + }); + }); + + group('selection', () { + List> repeatedVisits() => [ + step(sequence: 5, stage: 'review', outcome: 'rejected'), + step(sequence: 2, stage: 'review', outcome: 'success'), + ].cast>(); + + test('no requested visit selects the stage most recent recorded visit', () { + final selection = selectStageVisit(repeatedVisits(), 'review'); + expect(selection.hasVisit, isTrue); + expect(selection.index, 1); + expect(selection.step!['sequence'], 5); + expect(selection.visitNumber, 2); + }); + + test('an explicit visit selects that recorded visit', () { + final selection = selectStageVisit( + repeatedVisits(), + 'review', + visitIndex: 0, + ); + expect(selection.step!['sequence'], 2); + expect(selection.visitNumber, 1); + }); + + test('out-of-range indexes clamp to the nearest recorded visit', () { + final late = selectStageVisit(repeatedVisits(), 'review', visitIndex: 99); + expect(late.index, 1); + expect(late.step!['sequence'], 5); + expect(late.correctedRequest(99), isTrue); + + final early = selectStageVisit( + repeatedVisits(), + 'review', + visitIndex: -4, + ); + expect(early.index, 0); + expect(early.step!['sequence'], 2); + expect(early.correctedRequest(-4), isTrue); + expect(early.correctedRequest(null), isFalse); + }); + + test('a stage with no recorded visit returns no fabricated step', () { + final selection = selectStageVisit(repeatedVisits(), 'never-ran'); + expect(selection.hasVisit, isFalse); + expect(selection.step, isNull); + expect(selection.index, 0); + expect(selection.visitNumber, 0); + + final empty = selectStageVisit(const >[], 'review'); + expect(empty.hasVisit, isFalse); + expect(empty.step, isNull); + }); + + test('an absent capture for one stage does not hide another stage', () { + final steps = [ + step(sequence: 1, stage: 'a', outcome: 'success', target: 'b'), + ].cast>(); + expect(selectStageVisit(steps, 'a').hasVisit, isTrue); + expect(selectStageVisit(steps, 'b').hasVisit, isFalse); + }); + }); +} From e8bde4f5787f8780d9ea6cf8770556721f35e5f8 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 15:32:21 +0100 Subject: [PATCH 47/84] docs(app): record verified export-fix landing and safe installation gate --- app/WORK.md | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/app/WORK.md b/app/WORK.md index 9d4dff9a..ce3293fe 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -21,7 +21,7 @@ All work under app/. Existing applications remain running and unchanged. | R2b | Native cancel-run confirmation | run51 →52 / correction5449370 | manager reran23 action tests + analyze, pass; known refusal now immediate and dismissible while resync pending | merged main; ancestry verified | reusable component only; wiring/browser pending | | X1 | Native search and result targets | run49 / flutter/x1-search | Code computed success; WAITING truncated2MiB export | held, review not reached | pending | | I1 | App-owned socket/session + live Runs shell registration | run50 / flutter/r1-native | Code computed success; WAITING truncated2MiB export | held, review not reached | not deployed | -| E1 | Narrow authorized server export-bound fix | run53 / fix/session-export-limit | API v8, Flash; bounded export/repair regressions | pending | no service restart authorized by pipeline | +| E1 | Narrow authorized server export-bound fix | run53 / commit22801a9 | manager reproduced landing-test env failure on unchanged main; full Go suite/build/vet pass with only test-process URL env unset | merged main, ancestry verified | NOT installed; operator restart approval/window pending | | R2c | Native retry/restart confirmation | run54 / commit178f22a | manager reran17 focused tests + analyze, pass; exact modes/stable intent keys checked | main804e531, ancestry verified | reusable only; wiring/browser pending | | R2d | Native rename-run dialog | run55 / commitf2643a0 | manager reran11 focused tests + analyze, pass; clean scoped diff | main3dde288, ancestry verified | reusable only; screen/list update wiring pending | | S1a | Saved schedules repository/revision safety | run56 / commitb963965 | manager reran18 focused tests + analyze, pass; revision/unknown field preservation checked | maina290858, ancestry verified | — | @@ -65,6 +65,22 @@ flutter analyze was clean. These cover landed source/components only, not the six unreviewed export-blocked feature branches or visible screen delivery. ### Current delivery blocker — session export cap +The fix is now merged: rendered file cap8MiB, source cap8MiB unchanged, within +ordinary artifact allowance. Pipeline read-only scratch exports of all six exact +sessions were complete at2.25–4.28MiB, establishing the fix is sufficient. +Run53 automatic delivery failed in pre-existing TestHumanRunAttentionNotification +because the test inherited the running service's PIPELINES_WEB_PUBLIC_URL. Manager +reproduced that same failure on unchanged main with a harmless example URL; no +notification source/test was edited. All packages pass on candidate with only that +test-process env var unset; build/vet/diff pass. Manager landed checked source +directly (no coding-stage replay), and refreshed installed managed Pipelines skill +from current source via go run ./cmd/pipelines skill install. +Installed server is unchanged. Deployment safety inspection found57/58/59 active; +no restart or binary replacement performed. Need explicit operator approval for +installation/restart after active work settles before exact export-only repairs. +Old CLI service status cannot resolve its expected launchd label; do not guess a +service or restart unrelated processes. Inspect authoritative supervisor first. + User asked about failed runs; explicit status inspection found runs34/37/39/42/ 49/50 are waiting, not failed: each Code visit1 computed success and is quiescent, but export is partial/truncated at exactly2097152 bytes. Exact recorded native From 4548d66235ee68660fbe0976c560e4764ccc5051 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 15:32:31 +0100 Subject: [PATCH 48/84] docs(app): record committed P2a candidate and merged main --- app/notes/P2a.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/app/notes/P2a.md b/app/notes/P2a.md index 2e7d1e48..9e15821f 100644 --- a/app/notes/P2a.md +++ b/app/notes/P2a.md @@ -107,6 +107,7 @@ Focused coverage is the requested matrix: pipeline, schedule, workflow or service was created, changed or restarted. - **Mobile unverified.** Only web-targeted Flutter tests and analysis ran; no Android/iOS build, emulator, ADB or device. -- **Not committed, pushed or deployed.** The stage instruction for this visit - forbids commit/push/deploy, so the candidate remains as new untracked files - in the `flutter/p2-model` worktree for the manager to inspect and land. +- **Committed, not deployed.** The reviewed slice is commit `2c10507` on + `flutter/p2-model`; the branch was then merged with current `main` (merge + `da48208`). No push, install, preview server or canonical-URL change was made + by this landing stage; server-side checks and the actual land follow. From 8ea892959aefee9aa6de96ac2fefcd65f9e3cd16 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 15:33:22 +0100 Subject: [PATCH 49/84] docs(app): record final P2a merge and landing state --- app/notes/P2a.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/app/notes/P2a.md b/app/notes/P2a.md index 9e15821f..a77dc77d 100644 --- a/app/notes/P2a.md +++ b/app/notes/P2a.md @@ -108,6 +108,7 @@ Focused coverage is the requested matrix: - **Mobile unverified.** Only web-targeted Flutter tests and analysis ran; no Android/iOS build, emulator, ADB or device. - **Committed, not deployed.** The reviewed slice is commit `2c10507` on - `flutter/p2-model`; the branch was then merged with current `main` (merge - `da48208`). No push, install, preview server or canonical-URL change was made - by this landing stage; server-side checks and the actual land follow. + `flutter/p2-model`; current `main` was merged in after review (final merge + `f07ada0`, which includes `main` `e8bde4f`). No push, install, preview server + or canonical-URL change was made by this landing stage; server-side checks and + the actual land follow. From 0bfbe706f42f43201b2c0978ca31b5239531fe75 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 15:35:43 +0100 Subject: [PATCH 50/84] docs(app): accept graph and template checks while preserving install window --- app/WORK.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/app/WORK.md b/app/WORK.md index ce3293fe..85aeab3b 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -25,9 +25,9 @@ All work under app/. Existing applications remain running and unchanged. | R2c | Native retry/restart confirmation | run54 / commit178f22a | manager reran17 focused tests + analyze, pass; exact modes/stable intent keys checked | main804e531, ancestry verified | reusable only; wiring/browser pending | | R2d | Native rename-run dialog | run55 / commitf2643a0 | manager reran11 focused tests + analyze, pass; clean scoped diff | main3dde288, ancestry verified | reusable only; screen/list update wiring pending | | S1a | Saved schedules repository/revision safety | run56 / commitb963965 | manager reran18 focused tests + analyze, pass; revision/unknown field preservation checked | maina290858, ancestry verified | — | -| T1a | Templates/validate/create-only requests | run57 / flutter/t1-data | Task v6, Flash; nonvisual independent slice | pending | — | +| T1a | Templates/validate/create-only requests | run57 / flutter/t1-data | manager reran13 focused tests + analyze, pass; exact create-only/source preservation checked | accepted for main | — | | S1b | Native read-only schedule list | run58 / flutter/s1-list | Task v6, Flash; separate from editor | pending | pending | -| P2a | Graph identities/recorded-visit model | run59 / flutter/p2-model | Task v6, Flash; separate from layout/rendering | pending | — | +| P2a | Graph identities/recorded-visit model | run59 / commit2c10507 | manager reran41 focused tests + analyze, pass; scoped 4 pure domain files | merged main, ancestry verified | no renderer/layout yet | ## Next ready work - P1 pipelines list/detail/source/version; P2 graph and stage/visit selection. @@ -80,6 +80,10 @@ no restart or binary replacement performed. Need explicit operator approval for installation/restart after active work settles before exact export-only repairs. Old CLI service status cannot resolve its expected launchd label; do not guess a service or restart unrelated processes. Inspect authoritative supervisor first. +Graph lane59 is finished/landed. New launches are temporarily held to allow a +quiescent installation window once operator restart approval arrives; native +schedule list58 continues, template data57 is finished/accepted. This is a +deployment dependency, not a reason to replay or discard completed feature work. User asked about failed runs; explicit status inspection found runs34/37/39/42/ 49/50 are waiting, not failed: each Code visit1 computed success and is quiescent, From edfd5ecb057ecf559965244098b94a4fb262e1ce Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 15:36:02 +0100 Subject: [PATCH 51/84] docs(app): confirm template request layer landed --- app/WORK.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/WORK.md b/app/WORK.md index 85aeab3b..835dd6fc 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -25,7 +25,7 @@ All work under app/. Existing applications remain running and unchanged. | R2c | Native retry/restart confirmation | run54 / commit178f22a | manager reran17 focused tests + analyze, pass; exact modes/stable intent keys checked | main804e531, ancestry verified | reusable only; wiring/browser pending | | R2d | Native rename-run dialog | run55 / commitf2643a0 | manager reran11 focused tests + analyze, pass; clean scoped diff | main3dde288, ancestry verified | reusable only; screen/list update wiring pending | | S1a | Saved schedules repository/revision safety | run56 / commitb963965 | manager reran18 focused tests + analyze, pass; revision/unknown field preservation checked | maina290858, ancestry verified | — | -| T1a | Templates/validate/create-only requests | run57 / flutter/t1-data | manager reran13 focused tests + analyze, pass; exact create-only/source preservation checked | accepted for main | — | +| T1a | Templates/validate/create-only requests | run57 / candidateef2f463 | manager reran13 focused tests + analyze, pass; exact create-only/source preservation checked | merged main, ancestry verified | — | | S1b | Native read-only schedule list | run58 / flutter/s1-list | Task v6, Flash; separate from editor | pending | pending | | P2a | Graph identities/recorded-visit model | run59 / commit2c10507 | manager reran41 focused tests + analyze, pass; scoped 4 pure domain files | merged main, ancestry verified | no renderer/layout yet | From 2f4d934458b66d6097cd51f35ee7d1fa48129be3 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 15:59:15 +0100 Subject: [PATCH 52/84] docs(app): prepare minimal export-only deployment and verified rollback --- app/WORK.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/app/WORK.md b/app/WORK.md index 835dd6fc..820b7bb3 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -80,6 +80,16 @@ no restart or binary replacement performed. Need explicit operator approval for installation/restart after active work settles before exact export-only repairs. Old CLI service status cannot resolve its expected launchd label; do not guess a service or restart unrelated processes. Inspect authoritative supervisor first. +Preparation completed after user asked what manager was doing: authoritative +launchd label is net.awan.pipelines.server (not old CLI's net.a-wan.pipelines), +running installed binary under ~/.local/share/pipelines/bin with original DB +and OpenCode endpoint retained. Built a deployment candidate from the exact +running9ee2e00 revision plus ONLY export fix22801a9: branch +deploy/export-limit-only, commitb4627e2. All six new export regressions pass on +that exact candidate. Staged binary in approved OpenCode temp directory is +pipelines-server-exportfix-b4627e2; rollback copy is +pipelines-server-before-exportfix-66779. Installed binary/launchd registration +remain untouched. This avoids deploying unrelated newer main changes. Graph lane59 is finished/landed. New launches are temporarily held to allow a quiescent installation window once operator restart approval arrives; native schedule list58 continues, template data57 is finished/accepted. This is a From 2227faad40c74e994d337d32511cd71dac5d1afb Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 16:08:22 +0100 Subject: [PATCH 53/84] docs(app): resolve export blocker and resume seven preserved feature reviews --- app/AGENTS.md | 1 + app/WORK.md | 40 +++++++++++++++++++++++++++++++--------- 2 files changed, 32 insertions(+), 9 deletions(-) diff --git a/app/AGENTS.md b/app/AGENTS.md index 7752342a..bee8f407 100644 --- a/app/AGENTS.md +++ b/app/AGENTS.md @@ -7,6 +7,7 @@ - Develop and test ONLY web now. No ADB, emulators, device changes, Android/iOS builds or installs. Keep source portable to all three targets. Explicitly report mobile as unverified. - Small cohesive files (aim below 250 lines; split by responsibility, not arbitrary fragments). Each task owns a directory and its tests. Do not edit another lane or root pubspec/main unless assigned. - Code quality is a delivery requirement. No minified implementations, silent capability fallbacks, fake data masking missing features, or workarounds that bypass the real defect. A pipeline success does not waive missing behavior, native controls, regression coverage or rendered evidence. Label incomplete work honestly and complete it before claiming parity. +- The manager drives authorized routine integration and recovery without repeatedly stopping for permission. Feature implementation stays in pipelines where appropriate; infrastructure blockers can be resolved directly within the user's authorized scope. Verify quiescence, preserve data and rollback, act, and report actual results. Ask only for genuinely new scope or unresolved destructive choices. ## Shared contract - `lib/core/api_gateway.dart`: `JsonMap` alias; `ApiGateway.call(type, [fields])` yields the entire decoded reply envelope; `frames` yields unsolicited server envelopes. Gateway owns request IDs. Do not put domain interpretation in transport. diff --git a/app/WORK.md b/app/WORK.md index 820b7bb3..9a843b90 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -12,21 +12,21 @@ All work under app/. Existing applications remain running and unchanged. | F3 | Run models, live event fold, actions | run 32 + 1515ebe | 11 regressions/analyze pass; 5 source files 105–226 lines | main 37d0823, ancestry verified | — | | F4 | Chat models, history/live fold, request facade | run 33 / flutter/f4-chat | pipeline passed; wire omissions carried into C1 | pending C1 adapter fixes | — | | F5 | Isolated authenticated web preview tooling | run 30 + ae352bb | 6 proxy fixtures incl auth/bytes/origin/idle sockets pass | main 160ab45, ancestry verified | http://127.0.0.1:8096/ | -| P1 | Pipeline list/detail/source/version browser | run34 / flutter/p1-pipelines | Code computed success; WAITING truncated2MiB export | held, review not reached | pending | -| C1 | Chat session browser and management | 35 →36 →42 / flutter/f4-chat | Code42 computed success; WAITING truncated2MiB export | held, final review not reached | pending | -| N1 | Connection settings/preferences | run37 / flutter/n1-settings | Code computed success; WAITING truncated2MiB export | held, review not reached | pending | +| P1 | Pipeline list/detail/source/version browser | run34 / flutter/p1-pipelines | original export repaired; Review resumed | pending review/landing | pending | +| C1 | Chat session browser and management | 35 →36 →42 / flutter/f4-chat | original export42 repaired; Review resumed | pending review/landing | pending | +| N1 | Connection settings/preferences | run37 / flutter/n1-settings | original export repaired; Review resumed | pending review/landing | pending | | R1 | Run list/detail/live timeline | controller43 + list48 + detail46 accepted | manager merged all three on flutter/r1-native; reran 25 combined tests + analyze, pass | candidate integrated, held for I1 | I1 run50 wiring + browser verification | -| D1 | Recorded changes/diff viewer | run39 / flutter/d1-diff-viewer | Code computed success; WAITING truncated2MiB export | held, review not reached | pending | +| D1 | Recorded changes/diff viewer | run39 / flutter/d1-diff-viewer | original export repaired; Review resumed | pending review/landing | pending | | R2a | Human-decision native confirm | run47 / commit42b21b8 | manager inspected source + reran 7 exact-confirm/refusal/native tests + analyze, pass | main3e6f950, ancestry verified | reusable component only; wiring/browser pending | | R2b | Native cancel-run confirmation | run51 →52 / correction5449370 | manager reran23 action tests + analyze, pass; known refusal now immediate and dismissible while resync pending | merged main; ancestry verified | reusable component only; wiring/browser pending | -| X1 | Native search and result targets | run49 / flutter/x1-search | Code computed success; WAITING truncated2MiB export | held, review not reached | pending | -| I1 | App-owned socket/session + live Runs shell registration | run50 / flutter/r1-native | Code computed success; WAITING truncated2MiB export | held, review not reached | not deployed | -| E1 | Narrow authorized server export-bound fix | run53 / commit22801a9 | manager reproduced landing-test env failure on unchanged main; full Go suite/build/vet pass with only test-process URL env unset | merged main, ancestry verified | NOT installed; operator restart approval/window pending | +| X1 | Native search and result targets | run49 / flutter/x1-search | original export repaired; Review resumed | pending review/landing | pending | +| I1 | App-owned socket/session + live Runs shell registration | run50 / flutter/r1-native | original export repaired; Review resumed | pending review/landing | not deployed | +| E1 | Narrow authorized server export-bound fix | run53 / source22801a9 / deployb4627e2 | bounded regressions + full isolated Go suite pass; exact installed revision verified | source merged; deployed minimal patch on original server revision | installed; seven exact exports complete, Review resumed | | R2c | Native retry/restart confirmation | run54 / commit178f22a | manager reran17 focused tests + analyze, pass; exact modes/stable intent keys checked | main804e531, ancestry verified | reusable only; wiring/browser pending | | R2d | Native rename-run dialog | run55 / commitf2643a0 | manager reran11 focused tests + analyze, pass; clean scoped diff | main3dde288, ancestry verified | reusable only; screen/list update wiring pending | | S1a | Saved schedules repository/revision safety | run56 / commitb963965 | manager reran18 focused tests + analyze, pass; revision/unknown field preservation checked | maina290858, ancestry verified | — | | T1a | Templates/validate/create-only requests | run57 / candidateef2f463 | manager reran13 focused tests + analyze, pass; exact create-only/source preservation checked | merged main, ancestry verified | — | -| S1b | Native read-only schedule list | run58 / flutter/s1-list | Task v6, Flash; separate from editor | pending | pending | +| S1b | Native read-only schedule list | run58 / flutter/s1-list | original export repaired; Review resumed | pending review/landing | pending | | P2a | Graph identities/recorded-visit model | run59 / commit2c10507 | manager reran41 focused tests + analyze, pass; scoped 4 pure domain files | merged main, ancestry verified | no renderer/layout yet | ## Next ready work @@ -64,7 +64,29 @@ At804e531 manager ran the integrated main Flutter suite: 98tests passed and flutter analyze was clean. These cover landed source/components only, not the six unreviewed export-blocked feature branches or visible screen delivery. -### Current delivery blocker — session export cap +### Export blocker RESOLVED — direct manager recovery +User explicitly directed manager to perform routine unblock/install without +waiting for further decisions. Confirmed ZERO active runs and quiescent original +Code sessions, backed up SQLite via backup API plus installed binary/plist under +~/.local/share/pipelines/backups/exportfix-b4627e2 (private directory), atomically +replaced only the server binary and restarted exact launchd job +gui/501/net.awan.pipelines.server. No web/ntfy/OpenCode service was restarted. +Installed ping commit is b4627e29755c3496f5caee5a9c316d8bf24f0713; SHA256 +f70b4e17324262cf5275927c40f617838fefc0d9217946eeaf6d3a320c786fac. +Rollback binary remains saved, DB/session/workspaces untouched. + +Export-only repair of34/37/39/42/49/50/58 visit1 ALL returned complete, +untruncated, 2.25–4.28MiB. Original Code session IDs and output hashes match the +pre-install checkpoint, with one Code visit each; all seven moved to Review, +export_pending_sequence0. Evidence in approved OpenCode temp: +export-recovery-before.json, export-recovery-repair-results.json and +export-recovery-after.json. EOF/reset errors on old background waits were the +expected restart disconnect, NOT run failures. Reattached seven waits using a +private CLI built from the sameb4627e2 source; installed global CLI left alone. +No coding-stage replay, evidence overwrite or gate bypass. Network preview still +responds302 to protected login at http://10.0.0.249:8096/. Implementation/reviews +now proceed in parallel; the prior install-approval notes below are historical. + The fix is now merged: rendered file cap8MiB, source cap8MiB unchanged, within ordinary artifact allowance. Pipeline read-only scratch exports of all six exact sessions were complete at2.25–4.28MiB, establishing the fix is sufficient. From e219a4cfcd5d2ecf586f4d5c2a17d0fdebb3c901 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 16:13:33 +0100 Subject: [PATCH 54/84] docs(app): continue independent graph-layout and artifact-model lanes --- app/WORK.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/WORK.md b/app/WORK.md index 9a843b90..8b01ab70 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -28,6 +28,8 @@ All work under app/. Existing applications remain running and unchanged. | T1a | Templates/validate/create-only requests | run57 / candidateef2f463 | manager reran13 focused tests + analyze, pass; exact create-only/source preservation checked | merged main, ancestry verified | — | | S1b | Native read-only schedule list | run58 / flutter/s1-list | original export repaired; Review resumed | pending review/landing | pending | | P2a | Graph identities/recorded-visit model | run59 / commit2c10507 | manager reran41 focused tests + analyze, pass; scoped 4 pure domain files | merged main, ancestry verified | no renderer/layout yet | +| P2b | Content-sized graph node layout | run60 / flutter/p2-layout | Task v6, Flash; explicit measured extents, no fixed CSS dimensions | running | — | +| A1a | Artifact records/grouping/safe URL navigation | run61 / flutter/a1-data | Task v6, Flash; pure data/security fixtures | running | — | ## Next ready work - P1 pipelines list/detail/source/version; P2 graph and stage/visit selection. From c1f140bc78ae2aa6f5801afac16c1b76c89a5464 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 16:25:17 +0100 Subject: [PATCH 55/84] feat(app): add deterministic content-sized graph node layout Pure-Dart SCC ranking and column placement over the landed graph identities. Every extent and gap is caller supplied; missing measurements are rejected rather than defaulted. Focused tests cover linear, diamond, cycle, self-loop, disconnected, terminal, expanded-text and invalid-input cases. --- .../graph/layout/graph_node_layout.dart | 142 +++++++++++ .../features/graph/layout/graph_ranks.dart | 191 +++++++++++++++ .../features/graph/layout/layout_models.dart | 129 ++++++++++ app/notes/P2b.md | 100 ++++++++ .../layout/graph_layout_validation_test.dart | 96 ++++++++ .../graph/layout/graph_node_layout_test.dart | 228 ++++++++++++++++++ .../graph/layout/graph_ranks_test.dart | 116 +++++++++ .../graph/layout/layout_fixtures.dart | 102 ++++++++ 8 files changed, 1104 insertions(+) create mode 100644 app/lib/features/graph/layout/graph_node_layout.dart create mode 100644 app/lib/features/graph/layout/graph_ranks.dart create mode 100644 app/lib/features/graph/layout/layout_models.dart create mode 100644 app/notes/P2b.md create mode 100644 app/test/features/graph/layout/graph_layout_validation_test.dart create mode 100644 app/test/features/graph/layout/graph_node_layout_test.dart create mode 100644 app/test/features/graph/layout/graph_ranks_test.dart create mode 100644 app/test/features/graph/layout/layout_fixtures.dart diff --git a/app/lib/features/graph/layout/graph_node_layout.dart b/app/lib/features/graph/layout/graph_node_layout.dart new file mode 100644 index 00000000..767426ea --- /dev/null +++ b/app/lib/features/graph/layout/graph_node_layout.dart @@ -0,0 +1,142 @@ +import 'dart:math' as math; + +import '../domain/graph_definition.dart'; +import 'graph_ranks.dart'; +import 'layout_models.dart'; + +/// Places definition nodes in topological columns. +/// +/// Nodes keep definition order inside a rank, each column is as wide as its +/// widest measured node, and columns are top-aligned. A node is centred in its +/// column, so heterogeneous widths and text-expanded heights stay separated by +/// [GraphLayoutConfig.rowGap] inside a rank and [GraphLayoutConfig.columnGap] +/// between ranks. Nothing is clipped to a fixed box: the supplied measured +/// width and height are used verbatim and the returned bounds include them. +/// +/// [nodes] and [edges] normally come from `graphNodes`/`graphEdges`. Edges whose +/// source or target is not one of [nodes] are ignored, so an unknown target can +/// never invent a node. A measurement is required for every node; a missing one +/// is an error rather than a made-up size. Extra measurement entries are +/// ignored because they cannot become nodes. +GraphLayout layoutGraphNodes({ + required List nodes, + required List edges, + required Map extents, + required GraphLayoutConfig config, +}) { + _validateNodeKeys(nodes); + final ranks = assignGraphRanks(nodes, edges); + final measured = {}; + final missing = []; + for (final node in nodes) { + final extent = extents[node.key]; + if (extent == null) { + missing.add(node.key); + } else { + measured[node.key] = extent; + } + } + if (missing.isNotEmpty) { + throw ArgumentError.value( + missing, + 'extents', + 'missing measured extents for graph nodes', + ); + } + + final columns = List>.generate( + ranks.rankCount, + (_) => [], + ); + for (final node in nodes) { + columns[ranks.rankOf[node.key]!].add(node); + } + + final columnWidths = [ + for (final column in columns) + column.fold( + 0, + (width, node) => math.max(width, measured[node.key]!.width), + ), + ]; + final columnHeights = [ + for (final column in columns) + _columnHeight(column, measured, config.rowGap), + ]; + final columnX = []; + var nextX = config.padding; + for (var rank = 0; rank < columns.length; rank += 1) { + columnX.add(nextX); + nextX += columnWidths[rank]; + if (rank + 1 < columns.length) nextX += config.columnGap; + } + + final boxes = []; + for (var rank = 0; rank < columns.length; rank += 1) { + var nextY = config.padding; + for (final node in columns[rank]) { + final extent = measured[node.key]!; + boxes.add( + GraphNodeBox( + key: node.key, + terminal: node.terminal, + stageIndex: node.stageIndex, + rank: rank, + x: columnX[rank] + (columnWidths[rank] - extent.width) / 2, + y: nextY, + width: extent.width, + height: extent.height, + ), + ); + nextY += extent.height + config.rowGap; + } + } + + final width = + config.padding * 2 + + columnWidths.fold(0, (sum, column) => sum + column) + + config.columnGap * math.max(0, columns.length - 1); + final height = + config.padding * 2 + + columnHeights.fold( + 0, + (tallest, column) => math.max(tallest, column), + ); + + return GraphLayout( + nodes: boxes, + width: width, + height: height, + rankCount: ranks.rankCount, + ranks: ranks.rankOf, + ); +} + +void _validateNodeKeys(List nodes) { + final seen = {}; + for (final node in nodes) { + if (node.key.isEmpty) { + throw ArgumentError.value( + node.key, + 'nodes', + 'node key must not be empty', + ); + } + if (!seen.add(node.key)) { + throw ArgumentError.value(node.key, 'nodes', 'duplicate graph node key'); + } + } +} + +double _columnHeight( + List column, + Map measured, + double rowGap, +) { + if (column.isEmpty) return 0; + var height = 0.0; + for (final node in column) { + height += measured[node.key]!.height; + } + return height + rowGap * (column.length - 1); +} diff --git a/app/lib/features/graph/layout/graph_ranks.dart b/app/lib/features/graph/layout/graph_ranks.dart new file mode 100644 index 00000000..f7558db2 --- /dev/null +++ b/app/lib/features/graph/layout/graph_ranks.dart @@ -0,0 +1,191 @@ +import 'dart:collection'; +import 'dart:math' as math; + +import '../domain/graph_definition.dart'; + +/// Deterministic 0-based ranks for a graph definition's nodes. +/// +/// Ranks come from the condensation DAG: every strongly connected component +/// shares one rank, and a component sits one past its deepest predecessor +/// (longest path). Self loops and cycles therefore stay finite, a cycle's +/// members do not drift apart, and disconnected nodes stay at rank 0. Edges +/// whose endpoints are not definition nodes are ignored: an unknown target +/// never invents a node. +class GraphRanks { + GraphRanks({ + required Map rankOf, + required this.rankCount, + required List> components, + }) : rankOf = Map.unmodifiable(rankOf), + components = List.unmodifiable(>[ + for (final component in components) List.unmodifiable(component), + ]); + + /// Every definition key's rank, in definition order. + final Map rankOf; + + /// Number of distinct ranks, 0 for an empty node set. + final int rankCount; + + /// Strongly connected components as keys, each sorted by definition order and + /// the list sorted by its first member. + final List> components; +} + +/// One DFS frame for the iterative Tarjan walk. +class _Frame { + _Frame(this.node); + + final int node; + int nextChild = 0; +} + +/// Assigns ranks to exactly the supplied [nodes]. +/// +/// [edges] is read for ordering only; it never adds nodes. Duplicate edges are +/// harmless. The walk is iterative, so a deep chain cannot overflow the call +/// stack, and the work is linear in nodes plus edges. +GraphRanks assignGraphRanks(List nodes, List edges) { + final indexOf = {}; + for (var index = 0; index < nodes.length; index += 1) { + indexOf[nodes[index].key] = index; + } + + final adjacency = List>.generate(nodes.length, (_) => []); + final seenPairs = {}; + for (final edge in edges) { + final source = indexOf[edge.source]; + final target = indexOf[edge.target]; + if (source == null || target == null) continue; + if (!seenPairs.add(source * nodes.length + target)) continue; + adjacency[source].add(target); + } + + final components = _components(adjacency); + final componentOf = List.filled(nodes.length, -1); + for (var component = 0; component < components.length; component += 1) { + for (final node in components[component]) { + componentOf[node] = component; + } + } + + // Condensation edges and their indegrees. + final successors = List>.generate(components.length, (_) => {}); + final indegree = List.filled(components.length, 0); + for (var source = 0; source < adjacency.length; source += 1) { + final from = componentOf[source]; + for (final target in adjacency[source]) { + final to = componentOf[target]; + if (from == to) continue; + if (successors[from].add(to)) indegree[to] += 1; + } + } + + // Longest-path ranks over the condensation. Queue order only has to be a + // topological order; the resulting rank per component is unique. + final ranks = List.filled(components.length, 0); + final ready = ListQueue(); + for (var component = 0; component < components.length; component += 1) { + if (indegree[component] == 0) ready.add(component); + } + var settled = 0; + while (ready.isNotEmpty) { + final component = ready.removeFirst(); + settled += 1; + for (final next in successors[component]) { + ranks[next] = math.max(ranks[next], ranks[component] + 1); + indegree[next] -= 1; + if (indegree[next] == 0) ready.add(next); + } + } + if (settled != components.length) { + // The condensation cannot contain a cycle by construction; stop rather than + // return a silently truncated layout. + throw StateError('graph condensation was not acyclic'); + } + + final componentKeys = >[ + for (final component in components) + [for (final node in component) nodes[node].key], + ]; + final componentOrder = [ + for (var component = 0; component < components.length; component += 1) + component, + ]..sort((a, b) => components[a].first.compareTo(components[b].first)); + + final rankOf = {}; + var rankCount = 0; + for (var index = 0; index < nodes.length; index += 1) { + final rank = ranks[componentOf[index]]; + rankOf[nodes[index].key] = rank; + if (rank + 1 > rankCount) rankCount = rank + 1; + } + + return GraphRanks( + rankOf: rankOf, + rankCount: rankCount, + components: >[ + for (final component in componentOrder) componentKeys[component], + ], + ); +} + +/// Tarjan's strongly connected components, emitted sinks first. +/// +/// Iterative rather than recursive so a long chain cannot exhaust the stack. +/// Members are sorted by definition index, which keeps every output stable. +List> _components(List> adjacency) { + final discovery = List.filled(adjacency.length, -1); + final low = List.filled(adjacency.length, 0); + final onStack = List.filled(adjacency.length, false); + final stack = []; + final components = >[]; + var nextDiscovery = 0; + + for (var root = 0; root < adjacency.length; root += 1) { + if (discovery[root] != -1) continue; + discovery[root] = low[root] = nextDiscovery; + nextDiscovery += 1; + stack.add(root); + onStack[root] = true; + final callStack = <_Frame>[_Frame(root)]; + + while (callStack.isNotEmpty) { + final frame = callStack.last; + final node = frame.node; + if (frame.nextChild < adjacency[node].length) { + final child = adjacency[node][frame.nextChild]; + frame.nextChild += 1; + if (discovery[child] == -1) { + discovery[child] = low[child] = nextDiscovery; + nextDiscovery += 1; + stack.add(child); + onStack[child] = true; + callStack.add(_Frame(child)); + } else if (onStack[child]) { + low[node] = math.min(low[node], discovery[child]); + } + continue; + } + + callStack.removeLast(); + if (callStack.isNotEmpty) { + final parent = callStack.last.node; + low[parent] = math.min(low[parent], low[node]); + } + if (low[node] == discovery[node]) { + final component = []; + while (stack.isNotEmpty) { + final member = stack.removeLast(); + onStack[member] = false; + component.add(member); + if (member == node) break; + } + component.sort(); + components.add(component); + } + } + } + + return components; +} diff --git a/app/lib/features/graph/layout/layout_models.dart b/app/lib/features/graph/layout/layout_models.dart new file mode 100644 index 00000000..4a8dac4e --- /dev/null +++ b/app/lib/features/graph/layout/layout_models.dart @@ -0,0 +1,129 @@ +/// Pure geometry for a workflow graph's node layout. +/// +/// Every size and gap is supplied by the caller. The native renderer measures +/// each node after text layout (including the platform's text scaling), so this +/// library never assumes a node width, font, palette or device class. +/// +/// No Flutter imports: rectangles are plain numbers so the same result can be +/// built into widgets, a canvas or a test fixture. +library; + +void _requireFiniteNonNegative(String name, double value) { + if (!value.isFinite || value < 0) { + throw ArgumentError.value(value, name, 'must be finite and non-negative'); + } +} + +/// One caller-measured node extent, in logical pixels. +/// +/// A width or height may be zero for an empty label; the layout still keeps the +/// node separate from its neighbours through the configured gaps. +class NodeExtent { + NodeExtent({required this.width, required this.height}) { + _requireFiniteNonNegative('width', width); + _requireFiniteNonNegative('height', height); + } + + final double width; + final double height; +} + +/// The gaps a caller reserves around measured nodes. +/// +/// [columnGap] separates adjacent ranks, [rowGap] separates nodes sharing a +/// rank, and [padding] is the outer margin included in [GraphLayout] bounds. +class GraphLayoutConfig { + GraphLayoutConfig({ + required this.columnGap, + required this.rowGap, + this.padding = 0, + }) { + _requireFiniteNonNegative('columnGap', columnGap); + _requireFiniteNonNegative('rowGap', rowGap); + _requireFiniteNonNegative('padding', padding); + } + + final double columnGap; + final double rowGap; + final double padding; +} + +/// One placed node. +/// +/// [key], [terminal] and [stageIndex] are the definition node's own identity, +/// copied unchanged. [x]/[y] are the measured rectangle's top-left corner in +/// graph space and [rank] is its 0-based topological column. +class GraphNodeBox { + const GraphNodeBox({ + required this.key, + required this.terminal, + required this.stageIndex, + required this.rank, + required this.x, + required this.y, + required this.width, + required this.height, + }); + + final String key; + final bool terminal; + final int? stageIndex; + final int rank; + final double x; + final double y; + final double width; + final double height; + + double get right => x + width; + double get bottom => y + height; + + @override + bool operator ==(Object other) => + other is GraphNodeBox && + other.key == key && + other.terminal == terminal && + other.stageIndex == stageIndex && + other.rank == rank && + other.x == x && + other.y == y && + other.width == width && + other.height == height; + + @override + int get hashCode => + Object.hash(key, terminal, stageIndex, rank, x, y, width, height); +} + +/// An immutable node layout: every placed box plus the total graph bounds. +/// +/// [nodes] is ordered by rank first and definition order inside a rank; use +/// [ranks] or [nodeFor] for keyed lookup. [width] and [height] include the +/// caller's padding; every box's [right] and [bottom] stay inside them. +/// [ranks] exposes each definition key's 0-based rank; [rankCount] is the +/// number of columns (0 for an empty node set). +class GraphLayout { + GraphLayout({ + required List nodes, + required this.width, + required this.height, + required this.rankCount, + required Map ranks, + }) : nodes = List.unmodifiable(nodes), + ranks = Map.unmodifiable(ranks); + + final List nodes; + final Map ranks; + final double width; + final double height; + final int rankCount; + + bool get isEmpty => nodes.isEmpty; + + /// The placed box for [key], or null when the definition has no such node. + GraphNodeBox? nodeFor(String key) { + for (final node in nodes) { + if (node.key == key) return node; + } + return null; + } +} diff --git a/app/notes/P2b.md b/app/notes/P2b.md new file mode 100644 index 00000000..91d5e07a --- /dev/null +++ b/app/notes/P2b.md @@ -0,0 +1,100 @@ +# P2b — deterministic pure node layout + +## What changed + +New app-only, pure-Dart files. No existing file, server, web client, legacy +client, shell, `main.dart`, pubspec, other feature or platform source was edited. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/graph/layout/layout_models.dart` | 127 | measured extents, gap config, immutable node box, layout + ranks | +| `lib/features/graph/layout/graph_ranks.dart` | 191 | deterministic SCC ranks over the landed definition nodes/edges | +| `lib/features/graph/layout/graph_node_layout.dart` | 142 | column/row placement, bounds, validation | +| `test/features/graph/layout/layout_fixtures.dart` | 102 | shared definitions and measured extents | +| `test/features/graph/layout/graph_ranks_test.dart` | 116 | linear/diamond/cycle/self-loop/disconnected/unknown/long-chain ranks | +| `test/features/graph/layout/graph_node_layout_test.dart` | 224 | ordering, terminals, heterogeneous and expanded extents, bounds, determinism | +| `test/features/graph/layout/graph_layout_validation_test.dart` | 96 | empty input, missing/extra measurements, duplicate keys, invalid sizes | + +No layout widgets, painters, edge routing, styling or shell wiring were added. + +## Public API + +```dart +GraphRanks assignGraphRanks(List nodes, List edges); + +GraphLayout layoutGraphNodes({ + required List nodes, + required List edges, + required Map extents, + required GraphLayoutConfig config, +}); +``` + +`NodeExtent` is the caller's measured width/height after text layout. +`GraphLayoutConfig` takes `columnGap`, `rowGap` and an optional outer `padding`. +No node size, font, colour or device value is assumed in the library. + +`GraphLayout` returns an unmodifiable `nodes` list of `GraphNodeBox` +(`key`, `terminal`, `stageIndex`, `rank`, `x`, `y`, `width`, `height`), an +unmodifiable `ranks` map, `rankCount`, and total `width`/`height` including +padding. Node keys, terminal flags and stage indices are copied from the +landed `graphNodes` identities unchanged. + +## Ranking behavior + +Ranks are read from the definition supplied by the caller; the existing +`graphNodes`/`graphEdges` helpers remain the source of identities. + +- Iterative Tarjan strongly connected components (no recursion; a 2000-stage + chain is covered), then longest-path ranks over the condensation DAG. +- Every member of a cycle shares one rank, so cyclic routes cannot recurse or + push members apart. Self loops are internal supervision and add no rank. +- Disconnected stages and disconnected terminals stay at rank 0. +- Edges whose source or target is not a node are ignored. An unknown or empty + target never creates a node or a rank. +- Ranking is linear in nodes plus edges and stable for repeated input. + +## Placement behavior + +- One column per rank; nodes keep definition order inside a rank. +- A column is as wide as its widest measured node; columns are separated by + `columnGap` and top-aligned. +- Nodes are centred in their column and stacked with exactly `rowGap` between + measured boxes (centres are compared in the heterogeneous test). +- Supplied widths/heights are placed verbatim, so expanded text is never + clipped to a fixed box; growing the extents grows the total bounds. +- Bounds include every box: tests assert `right <= width` and + `bottom <= height` for every fixture. +- The result is immutable and identical for identical input. + +Measurements are required for every node; a missing key throws +`ArgumentError` rather than inventing a default size. Extra measurements are +ignored because they cannot become nodes. Duplicate/empty node keys, negative +or non-finite gaps and extents are rejected. + +## Checks actually run + +``` +flutter pub get +dart format lib/features/graph/layout test/features/graph/layout +flutter test test/features/graph/layout # 21 passed +flutter analyze # No issues found! +flutter test # 173 passed +git diff --check # clean +``` + +Tests cover linear, diamond, cycle, self-loop, disconnected, terminals, +unknown/empty targets, heterogeneous extents, 2.6x expanded text, determinism, +bounds and invalid input. + +## Honest limits + +- **Nodes only.** Edge routing, ports, labels, lanes, hit testing, selection + highlighting, painting and native controls are separate later items. +- **Not rendered.** A pure nonvisual slice has no browser behavior to capture; + no screenshot or browser check applies. +- **No server or device.** Tests use local fixtures only; no run, pipeline, + schedule, service, emulator, ADB, Android/iOS build or live chat was touched. +- **Mobile unverified.** Only web-targeted Flutter test/analyze ran. +- **Uncommitted candidate.** Per this stage's instruction the slice is left in + the worktree; no commit, push or deployment was made. diff --git a/app/test/features/graph/layout/graph_layout_validation_test.dart b/app/test/features/graph/layout/graph_layout_validation_test.dart new file mode 100644 index 00000000..dd70f7ee --- /dev/null +++ b/app/test/features/graph/layout/graph_layout_validation_test.dart @@ -0,0 +1,96 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/layout/graph_node_layout.dart'; +import 'package:pipelines_app/features/graph/layout/layout_models.dart'; + +import 'layout_fixtures.dart'; + +/// Invalid and boundary input for the pure layout engine. +void main() { + test('an empty definition yields empty padded bounds', () { + final layout = layoutGraphNodes( + nodes: const [], + edges: const [], + extents: const {}, + config: layoutConfig(columnGap: 30, rowGap: 10, padding: 6), + ); + + expect(layout.isEmpty, isTrue); + expect(layout.rankCount, 0); + expect(layout.width, 12); + expect(layout.height, 12); + expect(layout.ranks, isEmpty); + }); + + test('missing measurements are reported rather than invented', () { + final graph = linearGraphFixture(); + final nodes = graphNodes(graph); + final extents = uniformExtents(nodes)..remove('build'); + + expect( + () => layoutGraphNodes( + nodes: nodes, + edges: graphEdges(graph), + extents: extents, + config: layoutConfig(), + ), + throwsArgumentError, + ); + }); + + test('extra measurements are ignored because they cannot become nodes', () { + final graph = linearGraphFixture(); + final nodes = graphNodes(graph); + final extents = uniformExtents(nodes) + ..['ghost'] = NodeExtent(width: 20, height: 20); + + final layout = layoutGraphNodes( + nodes: nodes, + edges: graphEdges(graph), + extents: extents, + config: layoutConfig(), + ); + + expect(layout.nodeFor('ghost'), isNull); + expect(layout.nodes.length, nodes.length); + }); + + test('duplicate or empty node keys are rejected', () { + const stageNode = GraphNode(key: 'a', terminal: false, stageIndex: 0); + expect( + () => layoutGraphNodes( + nodes: const [stageNode, stageNode], + edges: const [], + extents: {'a': NodeExtent(width: 10, height: 10)}, + config: layoutConfig(), + ), + throwsArgumentError, + ); + expect( + () => layoutGraphNodes( + nodes: const [ + GraphNode(key: '', terminal: false, stageIndex: 0), + ], + edges: const [], + extents: const {}, + config: layoutConfig(), + ), + throwsArgumentError, + ); + }); + + test('invalid gaps and extents are rejected', () { + expect( + () => GraphLayoutConfig(columnGap: -1, rowGap: 8), + throwsArgumentError, + ); + expect( + () => GraphLayoutConfig(columnGap: 8, rowGap: double.nan), + throwsArgumentError, + ); + expect( + () => NodeExtent(width: double.infinity, height: 10), + throwsArgumentError, + ); + }); +} diff --git a/app/test/features/graph/layout/graph_node_layout_test.dart b/app/test/features/graph/layout/graph_node_layout_test.dart new file mode 100644 index 00000000..bbaf2408 --- /dev/null +++ b/app/test/features/graph/layout/graph_node_layout_test.dart @@ -0,0 +1,228 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/layout/graph_node_layout.dart'; +import 'package:pipelines_app/features/graph/layout/layout_models.dart'; + +import 'layout_fixtures.dart'; + +GraphLayout _layout( + Map graph, { + Map? extents, + GraphLayoutConfig? config, +}) { + final nodes = graphNodes(graph); + return layoutGraphNodes( + nodes: nodes, + edges: graphEdges(graph), + extents: extents ?? uniformExtents(nodes), + config: config ?? layoutConfig(), + ); +} + +void _expectWithinBounds(GraphLayout layout) { + for (final box in layout.nodes) { + expect(box.x, greaterThanOrEqualTo(0), reason: '${box.key} left'); + expect(box.y, greaterThanOrEqualTo(0), reason: '${box.key} top'); + expect( + box.right, + lessThanOrEqualTo(layout.width), + reason: '${box.key} right inside width', + ); + expect( + box.bottom, + lessThanOrEqualTo(layout.height), + reason: '${box.key} bottom inside height', + ); + } +} + +void _expectSeparated(GraphLayout layout) { + for (var first = 0; first < layout.nodes.length; first += 1) { + for (var second = first + 1; second < layout.nodes.length; second += 1) { + final a = layout.nodes[first]; + final b = layout.nodes[second]; + final separated = + a.right <= b.x || + b.right <= a.x || + a.bottom <= b.y || + b.bottom <= a.y; + expect(separated, isTrue, reason: '${a.key} overlaps ${b.key}'); + } + } +} + +void main() { + test('linear nodes keep declaration order and terminal identity', () { + final layout = _layout(linearGraphFixture()); + + expect(layout.rankCount, 4); + expect(layout.nodes.map((box) => box.key), [ + 'plan', + 'build', + 'ship', + failureEnd, + successEnd, + ]); + expect(layout.ranks, { + 'plan': 0, + 'build': 1, + 'ship': 2, + failureEnd: 3, + successEnd: 3, + }); + expect(layout.nodeFor('plan')!.stageIndex, 0); + expect(layout.nodeFor('build')!.stageIndex, 1); + expect(layout.nodeFor('ship')!.stageIndex, 2); + expect(layout.nodeFor(failureEnd)!.terminal, isTrue); + expect(layout.nodeFor(failureEnd)!.stageIndex, isNull); + expect(layout.nodeFor(successEnd)!.terminal, isTrue); + expect( + layout.nodeFor(successEnd)!.y - layout.nodeFor(failureEnd)!.bottom, + layoutConfig().rowGap, + ); + expect(layout.nodeFor(failureEnd)!.x, layout.nodeFor(successEnd)!.x); + expect(layout.nodeFor('plan')!.x, layoutConfig().padding); + expect(layout.nodeFor('plan')!.y, layoutConfig().padding); + expect( + layout.nodeFor('build')!.x - layout.nodeFor('plan')!.right, + layoutConfig().columnGap, + ); + expect(layout.width, 560); + expect(layout.height, 140); + _expectWithinBounds(layout); + _expectSeparated(layout); + }); + + test('diamond ranks place siblings in one column', () { + final layout = _layout(diamondGraphFixture()); + + final b = layout.nodeFor('b')!; + final c = layout.nodeFor('c')!; + expect(b.rank, 1); + expect(c.rank, 1); + expect(b.x, c.x); + expect(c.y - b.bottom, layoutConfig().rowGap); + expect(layout.nodeFor('d')!.rank, 2); + expect(layout.nodeFor('d')!.x, greaterThan(b.right)); + _expectWithinBounds(layout); + _expectSeparated(layout); + }); + + test('cycles share a column and terminals still follow them', () { + final layout = _layout(cycleGraph()); + + final a = layout.nodeFor('a')!; + final b = layout.nodeFor('b')!; + expect(a.rank, 0); + expect(b.rank, 0); + expect(b.y - a.bottom, layoutConfig().rowGap); + expect(layout.nodeFor(failureEnd)!.rank, 1); + expect(layout.nodeFor(successEnd)!.rank, 1); + _expectWithinBounds(layout); + _expectSeparated(layout); + }); + + test('self loops and disconnected stages stay finite and separate', () { + final selfLoop = _layout(selfLoopGraphFixture()); + expect(selfLoop.nodeFor('a')!.rank, 0); + expect(selfLoop.nodeFor('b')!.rank, 1); + + final disconnected = _layout(disconnectedGraph()); + expect(disconnected.nodeFor('a')!.rank, 0); + expect(disconnected.nodeFor('b')!.rank, 0); + expect(disconnected.nodeFor('c')!.rank, 0); + expect( + disconnected.nodeFor('b')!.y, + greaterThan(disconnected.nodeFor('a')!.bottom), + ); + _expectWithinBounds(selfLoop); + _expectSeparated(selfLoop); + _expectWithinBounds(disconnected); + _expectSeparated(disconnected); + }); + + test('unknown edge targets add no node and no column', () { + final graph = incompleteGraphFixture(); + final layout = _layout(graph); + + expect( + layout.nodes.map((box) => box.key), + graphNodes(graph).map((node) => node.key), + ); + expect(layout.nodeFor('ghost'), isNull); + expect(layout.ranks.containsKey('ghost'), isFalse); + _expectWithinBounds(layout); + _expectSeparated(layout); + }); + + test('heterogeneous measured widths stay inside their columns', () { + final layout = _layout( + diamondGraphFixture(), + extents: heterogeneousExtents(), + ); + + for (final entry in heterogeneousExtents().entries) { + final box = layout.nodeFor(entry.key)!; + expect(box.width, entry.value.width, reason: '${entry.key} width'); + expect(box.height, entry.value.height, reason: '${entry.key} height'); + } + final b = layout.nodeFor('b')!; + final c = layout.nodeFor('c')!; + expect(b.rank, c.rank); + expect(b.x + b.width / 2, c.x + c.width / 2); + expect(c.y - b.bottom, layoutConfig().rowGap); + expect(layout.width, greaterThan(0)); + expect(layout.width, 770); + expect(layout.height, 236); + _expectWithinBounds(layout); + _expectSeparated(layout); + }); + + test('expanded text extents grow the canvas without overlap or clipping', () { + final base = _layout( + diamondGraphFixture(), + extents: heterogeneousExtents(), + ); + final expandedExtents = scaledExtents(heterogeneousExtents(), 2.6); + final expanded = _layout(diamondGraphFixture(), extents: expandedExtents); + + expect(expanded.width, greaterThan(base.width)); + expect(expanded.height, greaterThan(base.height)); + for (final entry in expandedExtents.entries) { + final box = expanded.nodeFor(entry.key)!; + expect(box.width, entry.value.width, reason: '${entry.key} width'); + expect(box.height, entry.value.height, reason: '${entry.key} height'); + } + _expectWithinBounds(expanded); + _expectSeparated(expanded); + }); + + test('the same input produces the same immutable layout', () { + final graph = diamondGraphFixture(); + final nodes = graphNodes(graph); + final edges = graphEdges(graph); + final extents = uniformExtents(nodes, width: 133, height: 77); + + final first = layoutGraphNodes( + nodes: nodes, + edges: edges, + extents: extents, + config: layoutConfig(), + ); + final second = layoutGraphNodes( + nodes: nodes, + edges: edges, + extents: extents, + config: layoutConfig(), + ); + + expect(second.nodes, first.nodes); + expect(second.ranks, first.ranks); + expect(second.width, first.width); + expect(second.height, first.height); + expect(second.rankCount, first.rankCount); + expect(() => second.nodes.add(first.nodes.first), throwsUnsupportedError); + expect(() => second.ranks['a'] = 99, throwsUnsupportedError); + }); +} diff --git a/app/test/features/graph/layout/graph_ranks_test.dart b/app/test/features/graph/layout/graph_ranks_test.dart new file mode 100644 index 00000000..320ba287 --- /dev/null +++ b/app/test/features/graph/layout/graph_ranks_test.dart @@ -0,0 +1,116 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/layout/graph_ranks.dart'; + +import 'layout_fixtures.dart'; + +GraphRanks _ranksFor(Map graph) { + return assignGraphRanks(graphNodes(graph), graphEdges(graph)); +} + +void main() { + test('linear definitions rank one stage per column', () { + final ranks = _ranksFor(linearGraphFixture()); + + expect(ranks.rankOf, { + 'plan': 0, + 'build': 1, + 'ship': 2, + failureEnd: 3, + successEnd: 3, + }); + expect(ranks.rankCount, 4); + expect(ranks.components, >[ + ['plan'], + ['build'], + ['ship'], + [failureEnd], + [successEnd], + ]); + }); + + test('diamond fan-out shares a rank and converges after it', () { + final ranks = _ranksFor(diamondGraphFixture()); + + expect(ranks.rankOf['a'], 0); + expect(ranks.rankOf['b'], ranks.rankOf['c']); + expect(ranks.rankOf['b'], 1); + expect(ranks.rankOf['d'], 2); + expect(ranks.rankOf[failureEnd], 1); + expect(ranks.rankOf[successEnd], 3); + expect(ranks.rankCount, 4); + }); + + test('a cycle collapses to one shared rank instead of recursing', () { + final ranks = _ranksFor(cycleGraph()); + + expect(ranks.rankOf['a'], 0); + expect(ranks.rankOf['b'], 0); + expect(ranks.rankOf[failureEnd], 1); + expect(ranks.rankOf[successEnd], 1); + expect(ranks.rankCount, 2); + expect(ranks.components, contains(equals(['a', 'b']))); + }); + + test('a self edge stays inside its own component and adds no rank', () { + final ranks = _ranksFor(selfLoopGraphFixture()); + + expect(ranks.rankOf, { + 'a': 0, + 'b': 1, + failureEnd: 2, + successEnd: 2, + }); + expect(ranks.components, contains(equals(['a']))); + expect(ranks.components, contains(equals(['b']))); + }); + + test('disconnected stages stay at rank zero', () { + final ranks = _ranksFor(disconnectedGraph()); + + expect(ranks.rankOf['a'], 0); + expect(ranks.rankOf['b'], 0); + expect(ranks.rankOf['c'], 0); + expect(ranks.rankOf[failureEnd], 1); + expect(ranks.rankOf[successEnd], 1); + expect(ranks.rankCount, 2); + }); + + test('unknown and empty edge targets never become ranks or nodes', () { + final graph = incompleteGraphFixture(); + final nodes = graphNodes(graph); + final ranks = assignGraphRanks(nodes, graphEdges(graph)); + + expect(nodes.map((node) => node.key), isNot(contains('ghost'))); + expect(ranks.rankOf.containsKey('ghost'), isFalse); + expect(ranks.rankOf.containsKey(''), isFalse); + expect(ranks.rankOf['a'], 0); + expect(ranks.rankOf['b'], 0); + expect(ranks.rankOf[failureEnd], 1); + expect(ranks.rankOf[successEnd], 1); + }); + + test('ranks are stable across repeated assignments', () { + final graph = diamondGraphFixture(); + final nodes = graphNodes(graph); + final edges = graphEdges(graph); + + final first = assignGraphRanks(nodes, edges); + final second = assignGraphRanks(nodes, edges); + + expect(second.rankOf, first.rankOf); + expect(second.rankCount, first.rankCount); + expect(second.components, first.components); + }); + + test('a long chain is walked iteratively without overflow', () { + const length = 2000; + final ranks = _ranksFor(chainGraph(length)); + + expect(ranks.rankCount, length + 1); + expect(ranks.rankOf['s0'], 0); + expect(ranks.rankOf['s${length - 1}'], length - 1); + expect(ranks.rankOf[successEnd], length); + }); +} diff --git a/app/test/features/graph/layout/layout_fixtures.dart b/app/test/features/graph/layout/layout_fixtures.dart new file mode 100644 index 00000000..e67a6051 --- /dev/null +++ b/app/test/features/graph/layout/layout_fixtures.dart @@ -0,0 +1,102 @@ +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/layout/layout_models.dart'; + +import '../domain/graph_fixtures.dart' as domain; + +/// Small definitions and measured extents shared by the layout tests. + +GraphLayoutConfig layoutConfig({ + double columnGap = 24, + double rowGap = 12, + double padding = 4, +}) { + return GraphLayoutConfig( + columnGap: columnGap, + rowGap: rowGap, + padding: padding, + ); +} + +/// One measured size for every node, optionally scaled to simulate text growth. +Map uniformExtents( + Iterable nodes, { + double width = 120, + double height = 60, + double scale = 1, +}) { + return { + for (final node in nodes) + node.key: NodeExtent(width: width * scale, height: height * scale), + }; +} + +Map scaledExtents( + Map base, + double scale, +) { + return { + for (final entry in base.entries) + entry.key: NodeExtent( + width: entry.value.width * scale, + height: entry.value.height * scale, + ), + }; +} + +/// Deliberately uneven measured boxes for the diamond definition. +Map heterogeneousExtents() { + return { + 'a': NodeExtent(width: 210, height: 84), + 'b': NodeExtent(width: 92, height: 44), + 'c': NodeExtent(width: 148, height: 126), + 'd': NodeExtent(width: 104, height: 58), + failureEnd: NodeExtent(width: 72, height: 34), + successEnd: NodeExtent(width: 228, height: 96), + }; +} + +/// Two stages in a cycle; both terminals are reached from inside the cycle. +Map cycleGraph() => { + 'stages': [ + domain.stage( + 'a', + edges: {'success': 'b', 'error': '#'}, + fallbackError: true, + ), + domain.stage( + 'b', + edges: {'success': 'a', 'error': '#success'}, + ), + ], +}; + +/// Two independent routes and a stage with no edges at all. +Map disconnectedGraph() => { + 'stages': [ + domain.stage('a', edges: {'success': '#success'}), + domain.stage('b', edges: {'success': '#failure'}), + domain.stage('c'), + ], +}; + +Map linearGraphFixture() => domain.linearGraph(); + +Map diamondGraphFixture() => domain.diamondGraph(); + +Map selfLoopGraphFixture() => domain.selfLoopGraph(); + +Map incompleteGraphFixture() => domain.incompleteGraph(); + +/// A long chain, used to prove the iterative rank walk cannot overflow. +Map chainGraph(int length) => { + 'stages': [ + for (var index = 0; index < length; index += 1) + domain.stage( + 's$index', + edges: { + 'success': index + 1 < length ? 's${index + 1}' : '#success', + }, + ), + ], +}; From 0344ef10d1622d2cccedcb0ff8d812984d42352f Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 16:26:27 +0100 Subject: [PATCH 56/84] docs(app): record verified tailnet HTTPS preview access --- app/WORK.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/app/WORK.md b/app/WORK.md index 8b01ab70..bf36d6a8 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -152,6 +152,15 @@ HTML login redirect 302 and unauthenticated JS 401 via the LAN address. Existing proxy/API services remain unchanged. Bind command uses --host 0.0.0.0 explicitly; the source default remains loopback for safety. +HTTPS access fixed for the user's Tailscale URL: +https://alans-macbook-pro.tail6bf4dc.ts.net:8096/. Port8096 originally spoke only +plain HTTP; added tailnet-only Tailscale Serve HTTPS8096 → http://127.0.0.1:8096. +Existing Serve443→8787 and8443→8095 routes preserved. Verified trusted certificate +(curl ssl_verify_result0), protected root302 to login, login200, unauthenticated +JS401; LAN HTTP still302. No Funnel/public-Internet exposure or auth disabling. +Prior Serve config saved in approved temp tailscale-serve-before-preview8096.json; +remove ONLY this route with tailscale serve --https=8096 off if rollback needed. + ### Manager integration findings - F3 candidate omitted `lib/features/runs/data/runs_repository.dart`: root runtime-data ignore matched source. Main 718442d adds an app-only exception; From a9237ee0231ad5c4306e03f4d08ebba100ebc54d Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 16:35:20 +0100 Subject: [PATCH 57/84] docs(app): record measured graph layout landing and next routing slice --- app/WORK.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/app/WORK.md b/app/WORK.md index bf36d6a8..2b5cc144 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -28,8 +28,9 @@ All work under app/. Existing applications remain running and unchanged. | T1a | Templates/validate/create-only requests | run57 / candidateef2f463 | manager reran13 focused tests + analyze, pass; exact create-only/source preservation checked | merged main, ancestry verified | — | | S1b | Native read-only schedule list | run58 / flutter/s1-list | original export repaired; Review resumed | pending review/landing | pending | | P2a | Graph identities/recorded-visit model | run59 / commit2c10507 | manager reran41 focused tests + analyze, pass; scoped 4 pure domain files | merged main, ancestry verified | no renderer/layout yet | -| P2b | Content-sized graph node layout | run60 / flutter/p2-layout | Task v6, Flash; explicit measured extents, no fixed CSS dimensions | running | — | +| P2b | Content-sized graph node layout | run60 / commitc1f140b | manager checked caller-supplied extents + reran21 tests/analyze, pass | mainec9e889, ancestry verified | geometry only, no renderer | | A1a | Artifact records/grouping/safe URL navigation | run61 / flutter/a1-data | Task v6, Flash; pure data/security fixtures | running | — | +| P2c | Edge routes and measured label geometry | run62 / flutter/p2-routes | Task v6, Flash; separate from painter/widgets | running | — | ## Next ready work - P1 pipelines list/detail/source/version; P2 graph and stage/visit selection. @@ -114,10 +115,10 @@ that exact candidate. Staged binary in approved OpenCode temp directory is pipelines-server-exportfix-b4627e2; rollback copy is pipelines-server-before-exportfix-66779. Installed binary/launchd registration remain untouched. This avoids deploying unrelated newer main changes. -Graph lane59 is finished/landed. New launches are temporarily held to allow a -quiescent installation window once operator restart approval arrives; native -schedule list58 continues, template data57 is finished/accepted. This is a -deployment dependency, not a reason to replay or discard completed feature work. +The temporary launch pause ended after the direct, safe server installation. +Graph/model/layout lanes have progressed, and independent small tasks continue +alongside the seven restored feature reviews. No repeat approval gate remains +for routine authorized recovery/integration. User asked about failed runs; explicit status inspection found runs34/37/39/42/ 49/50 are waiting, not failed: each Code visit1 computed success and is quiescent, From 51140cd3b7a7ec80fb4b03230473fc7b28755349 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 16:41:30 +0100 Subject: [PATCH 58/84] feat(app): add native omni-search screen over the search gateway Pure request/parse/row logic in lib/features/search/domain, a gateway-backed repository, and Material plus Cupertino bodies. The header and rows share one scroll view, and the server's truncation, scan and cap facts stay visible even when a bounded scan returns no matches. Tests cover the exact search envelope, token parsing, stale replies, retry, truncation bounds and platform layouts. A Web-only fixture and CDP probe support rendered verification; the screen is not yet registered in the shell. --- .../search/data/search_repository.dart | 28 ++ .../search/domain/search_controller.dart | 236 +++++++++++++++++ .../features/search/domain/search_format.dart | 43 +++ .../features/search/domain/search_models.dart | 87 +++++++ .../features/search/domain/search_query.dart | 82 ++++++ .../features/search/domain/search_row.dart | 226 ++++++++++++++++ app/lib/features/search/search_screen.dart | 228 ++++++++++++++++ .../search/ui/cupertino_search_body.dart | 174 +++++++++++++ .../search/ui/material_search_body.dart | 166 ++++++++++++ .../search/ui/search_result_view.dart | 59 +++++ app/notes/X1.md | 121 +++++++++ .../search_controller_failure_test.dart | 90 +++++++ .../search/search_controller_test.dart | 240 +++++++++++++++++ .../features/search/search_query_test.dart | 118 +++++++++ .../search/search_repository_test.dart | 106 ++++++++ app/test/features/search/search_row_test.dart | 161 ++++++++++++ .../search/search_screen_states_test.dart | 146 +++++++++++ .../features/search/search_screen_test.dart | 223 ++++++++++++++++ .../features/search/search_test_support.dart | 50 ++++ app/tool/search_fixture/main.dart | 190 ++++++++++++++ app/tool/search_probe.mjs | 246 ++++++++++++++++++ 21 files changed, 3020 insertions(+) create mode 100644 app/lib/features/search/data/search_repository.dart create mode 100644 app/lib/features/search/domain/search_controller.dart create mode 100644 app/lib/features/search/domain/search_format.dart create mode 100644 app/lib/features/search/domain/search_models.dart create mode 100644 app/lib/features/search/domain/search_query.dart create mode 100644 app/lib/features/search/domain/search_row.dart create mode 100644 app/lib/features/search/search_screen.dart create mode 100644 app/lib/features/search/ui/cupertino_search_body.dart create mode 100644 app/lib/features/search/ui/material_search_body.dart create mode 100644 app/lib/features/search/ui/search_result_view.dart create mode 100644 app/notes/X1.md create mode 100644 app/test/features/search/search_controller_failure_test.dart create mode 100644 app/test/features/search/search_controller_test.dart create mode 100644 app/test/features/search/search_query_test.dart create mode 100644 app/test/features/search/search_repository_test.dart create mode 100644 app/test/features/search/search_row_test.dart create mode 100644 app/test/features/search/search_screen_states_test.dart create mode 100644 app/test/features/search/search_screen_test.dart create mode 100644 app/test/features/search/search_test_support.dart create mode 100644 app/tool/search_fixture/main.dart create mode 100644 app/tool/search_probe.mjs diff --git a/app/lib/features/search/data/search_repository.dart b/app/lib/features/search/data/search_repository.dart new file mode 100644 index 00000000..391aac13 --- /dev/null +++ b/app/lib/features/search/data/search_repository.dart @@ -0,0 +1,28 @@ +import '../../../core/api_gateway.dart'; +import '../domain/search_models.dart'; + +/// Search protocol requests over the application's shared gateway. +/// +/// The request body is exactly `SearchRequest{query, kind, limit}` with +/// `limit: 0`, so the server applies its own default cap (`SearchDefaultLimit`, +/// 50) instead of the client choosing a larger one. +class SearchRepository { + SearchRepository(this._gateway); + + final ApiGateway _gateway; + + /// Returns the bounded `search_results` body, or null when an older server + /// answered without it (its default `pong`) so the caller can report the + /// "cannot search" sentence rather than showing a false empty success. + Future search({ + required String query, + required SearchKind kind, + }) async { + final reply = await _gateway.call('search', { + 'search': {'query': query, 'kind': kind.wire, 'limit': 0}, + }); + final results = reply['search_results']; + if (results is! Map) return null; + return SearchResponse.fromJson(Map.from(results)); + } +} diff --git a/app/lib/features/search/domain/search_controller.dart b/app/lib/features/search/domain/search_controller.dart new file mode 100644 index 00000000..b9a3f8f8 --- /dev/null +++ b/app/lib/features/search/domain/search_controller.dart @@ -0,0 +1,236 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import '../../../core/api_gateway.dart'; +import '../data/search_repository.dart'; +import 'search_models.dart'; +import 'search_query.dart'; +import 'search_row.dart'; + +/// The body the results area shows, in the browser's precedence order: an error +/// takes precedence over retained results, a refresh keeps results on screen, +/// and a first load shows the searching row. +enum SearchBodyKind { idle, searching, results, empty, error } + +/// Debounced, stale-safe omni-search state. It owns no widgets and no socket: +/// the screen listens to it and the repository talks to the shared gateway. +class OmniSearchController extends ChangeNotifier { + OmniSearchController({ + required this.repository, + this.debounce = const Duration(milliseconds: 250), + }); + + final SearchRepository repository; + final Duration debounce; + final SearchSequencer _sequencer = SearchSequencer(); + + Timer? _timer; + bool _disposed = false; + + String _query = ''; + SearchKind _selectedKind = SearchKind.all; + List _results = const []; + bool _loading = false; + bool _loaded = false; + bool _truncated = false; + int _scannedSteps = 0; + int _scannedBytes = 0; + int _cap = 0; + int _scanBoundBytes = 0; + String? _error; + + String get query => _query; + SearchKind get selectedKind => _selectedKind; + ParsedSearchQuery get parsed => parseSearchQuery(_query, _selectedKind); + List get results => _results; + bool get loading => _loading; + bool get loaded => _loaded; + bool get truncated => _truncated; + int get scannedSteps => _scannedSteps; + int get scannedBytes => _scannedBytes; + int get cap => _cap; + int get scanBoundBytes => _scanBoundBytes; + String? get error => _error; + + /// The results already in hand, re-narrowed to the effective kind so the list + /// always matches the control while a narrowed request loads. + List get shownResults { + final kind = parsed.kind; + if (kind == SearchKind.all) return _results; + return _results + .where((hit) => hit['kind'] == kind.wire) + .toList(growable: false); + } + + SearchBodyKind get bodyKind { + if (_error != null) return SearchBodyKind.error; + if (shownResults.isNotEmpty) return SearchBodyKind.results; + if (_loading && _results.isEmpty) return SearchBodyKind.searching; + if (emptyMessage != null) return SearchBodyKind.empty; + return SearchBodyKind.idle; + } + + /// A thin progress report above retained results while a newer query loads. + bool get showProgress => _loading && _results.isNotEmpty; + + String? get emptyMessage { + if (_error != null || _loading || shownResults.isNotEmpty) return null; + final effective = parsed; + if (effective.query.trim().isEmpty) { + if (!_loaded || effective.kind == SearchKind.all) return null; + final label = effective.kind.label.toLowerCase(); + return _truncated + ? "No $label found within the server's scan limit." + : 'No $label yet.'; + } + final bounded = _truncated ? " within the server's scan limit" : ''; + if (effective.kind == SearchKind.all) { + return 'No matches for "${effective.query}"$bounded.'; + } + return 'No ${effective.kind.label.toLowerCase()} match ' + '"${effective.query}"$bounded.'; + } + + /// The server's own result/scan bounds, so a capped answer is not presented as + /// a complete one. A truncated reply keeps its warning even with no rows; + /// before any loaded reply there is nothing to report. + String? get boundsText { + if (!_loaded) return null; + // A new first load has no current result set yet, so do not carry the + // previous reply's warning while the searching state is on screen. + if (_loading && _results.isEmpty) return null; + if (_results.isEmpty && !_truncated) return null; + final count = _results.length; + final parts = []; + if (_truncated) { + parts.add("Results truncated by the server's result or scan limit."); + } + parts.add('$count ${count == 1 ? 'result' : 'results'}'); + if (_cap > 0) parts.add('cap $_cap'); + parts.add('scanned $_scannedSteps steps'); + parts.add('${humanBytes(_scannedBytes)} scanned'); + if (_scanBoundBytes > 0) { + parts.add('scan limit ${humanBytes(_scanBoundBytes)}'); + } + return parts.join(' · '); + } + + /// Record a keystroke. Blank text with no kind clears locally and sends + /// nothing; valid kind-only browsing is sendable like the browser's search. + void updateQuery(String value) { + _query = value; + _error = null; + _cancelTimer(); + final effective = parsed; + if (!searchQuerySendable(effective.query, effective.kind)) { + _sequencer.edit(''); + _clearResults(); + _notify(); + return; + } + _loading = true; + final edit = _sequencer.edit(value); + _notify(); + _timer = Timer(debounce, () { + _timer = null; + final sent = _sequencer.begin(edit); + if (sent != null) unawaited(_send(sent)); + }); + } + + /// A kind change removes recognised type tokens from the visible text and + /// sends at once, matching the browser's selector behaviour. + void selectKind(SearchKind kind) { + _query = parseSearchQuery(_query, _selectedKind).query; + _selectedKind = kind; + _error = null; + _notify(); + unawaited(sendNow()); + } + + /// Enter: send the current query immediately, skipping the debounce. + Future submit() => sendNow(); + + /// Retry the current query after a failure. + Future retry() => sendNow(); + + Future sendNow() async { + _cancelTimer(); + final effective = parseSearchQuery(_query, _selectedKind); + if (!searchQuerySendable(effective.query, effective.kind)) { + _sequencer.edit(''); + _clearResults(); + _notify(); + return; + } + final sent = _sequencer.begin(_sequencer.edit(_query)); + if (sent == null) return; + await _send(sent); + } + + Future _send(SearchEdit sent) async { + final effective = parseSearchQuery(sent.query, _selectedKind); + _loading = true; + _error = null; + _notify(); + try { + final response = await repository.search( + query: effective.query.trim(), + kind: effective.kind, + ); + if (!_sequencer.accepts(sent.token) || _disposed) return; + if (response == null) { + _loading = false; + _loaded = true; + _error = unsupportedSearchCopy; + _notify(); + return; + } + _results = response.results; + _truncated = response.truncated; + _scannedSteps = response.scannedSteps; + _scannedBytes = response.scannedBytes; + _cap = response.cap; + _scanBoundBytes = response.scanBoundBytes; + _loading = false; + _loaded = true; + _error = null; + _notify(); + } catch (error) { + if (!_sequencer.accepts(sent.token) || _disposed) return; + _loading = false; + _loaded = true; + _error = searchFailureText(error); + _notify(); + } + } + + void _clearResults() { + _results = const []; + _truncated = false; + _scannedSteps = 0; + _scannedBytes = 0; + _cap = 0; + _scanBoundBytes = 0; + _loading = false; + _loaded = false; + _error = null; + } + + void _cancelTimer() { + _timer?.cancel(); + _timer = null; + } + + void _notify() { + if (!_disposed) notifyListeners(); + } + + @override + void dispose() { + _disposed = true; + _cancelTimer(); + super.dispose(); + } +} diff --git a/app/lib/features/search/domain/search_format.dart b/app/lib/features/search/domain/search_format.dart new file mode 100644 index 00000000..8e2f480a --- /dev/null +++ b/app/lib/features/search/domain/search_format.dart @@ -0,0 +1,43 @@ +/// Human bytes with the shared binary units (`2.0 KiB`), matching the browser. +String humanBytes(int size) { + const unit = 1024; + if (size < unit) return '$size B'; + var divisor = unit; + var exponent = 0; + var scaled = size ~/ unit; + while (scaled >= unit && exponent < 5) { + divisor *= unit; + exponent++; + scaled ~/= unit; + } + return '${(size / divisor).toStringAsFixed(1)} ${'KMGTPE'[exponent]}iB'; +} + +const _months = [ + 'Jan', + 'Feb', + 'Mar', + 'Apr', + 'May', + 'Jun', + 'Jul', + 'Aug', + 'Sep', + 'Oct', + 'Nov', + 'Dec', +]; + +/// An RFC3339 timestamp as the app's one human local rendering (`20 Oct 12:00`), +/// or null when blank/unparseable so the caller omits the value rather than +/// printing a blank. +String? formatSearchTimestamp(String value) { + final text = value.trim(); + if (text.isEmpty) return null; + final instant = DateTime.tryParse(text); + if (instant == null) return null; + final local = instant.toLocal(); + final hour = local.hour.toString().padLeft(2, '0'); + final minute = local.minute.toString().padLeft(2, '0'); + return '${local.day} ${_months[local.month - 1]} $hour:$minute'; +} diff --git a/app/lib/features/search/domain/search_models.dart b/app/lib/features/search/domain/search_models.dart new file mode 100644 index 00000000..671e38d9 --- /dev/null +++ b/app/lib/features/search/domain/search_models.dart @@ -0,0 +1,87 @@ +import '../../../core/api_gateway.dart'; + +/// The server's search narrowing vocabulary (`internal/protocol/search.go`), +/// in the control's display order. The empty [wire] value means every kind. +enum SearchKind { + all('', 'All kinds'), + pipeline('pipeline', 'Pipelines'), + run('run', 'Runs'), + step('step', 'Steps'), + field('field', 'Fields'), + artifact('artifact', 'Artifacts'), + version('version', 'Versions'); + + const SearchKind(this.wire, this.label); + + final String wire; + final String label; + + /// A stale or unknown value falls back to [SearchKind.all] rather than + /// inventing an option the server does not accept. + static SearchKind fromWire(String? wire) { + for (final kind in values) { + if (kind.wire == wire) return kind; + } + return SearchKind.all; + } +} + +/// A query after `t:`/`type:` tokens have been recognised. [query] is the text +/// the server should match; [kind] is the effective narrowing. +class ParsedSearchQuery { + const ParsedSearchQuery(this.query, this.kind, this.hasType); + + final String query; + final SearchKind kind; + final bool hasType; +} + +/// The bounded `search_results` body from the server. Every bound the server +/// reports is kept, so the screen can show a truncation/scan indicator instead +/// of pretending a capped reply was complete. +class SearchResponse { + const SearchResponse({ + this.query = '', + this.kind = SearchKind.all, + this.results = const [], + this.truncated = false, + this.scannedSteps = 0, + this.scannedBytes = 0, + this.cap = 0, + this.scanBoundBytes = 0, + }); + + factory SearchResponse.fromJson(JsonMap json) { + final rows = json['results']; + return SearchResponse( + query: '${json['query'] ?? ''}', + kind: SearchKind.fromWire('${json['kind'] ?? ''}'), + results: rows is List + ? rows + .whereType() + .map((row) => Map.from(row)) + .toList(growable: false) + : const [], + truncated: json['truncated'] == true, + scannedSteps: _integer(json['scanned_steps']), + scannedBytes: _integer(json['scanned_bytes']), + cap: _integer(json['cap']), + scanBoundBytes: _integer(json['scan_bound_bytes']), + ); + } + + final String query; + final SearchKind kind; + final List results; + final bool truncated; + final int scannedSteps; + final int scannedBytes; + final int cap; + final int scanBoundBytes; +} + +int _integer(Object? value) { + if (value is int) return value; + if (value is num) return value.toInt(); + return int.tryParse('$value') ?? 0; +} diff --git a/app/lib/features/search/domain/search_query.dart b/app/lib/features/search/domain/search_query.dart new file mode 100644 index 00000000..a7971540 --- /dev/null +++ b/app/lib/features/search/domain/search_query.dart @@ -0,0 +1,82 @@ +import 'search_models.dart'; + +/// Wording for a server that cannot answer `search`: an explicit rejection +/// naming an unknown/unsupported command, or a reply without +/// `search_results`. Kept verbatim from the web client's AppViewModel copy. +const unsupportedSearchCopy = + 'This server does not support search. Update the Pipelines server, then try again.'; + +/// Unquoted, whitespace-delimited `t:`/`type:` tokens; the last supported token +/// wins. Unknown tokens and quoted text stay literal, including their whitespace. +/// The selector is a fallback; explicitly changing it removes tokens in the view. +/// +/// This is the same token grammar as `web/src/search.js`, so `"t:run"`, +/// `t:unknown`, `prefix"t:run"` and `\t:run` all remain searchable text. +ParsedSearchQuery parseSearchQuery( + String value, [ + SearchKind selectedKind = SearchKind.all, +]) { + var kind = selectedKind; + var hasType = false; + final query = value.replaceAllMapped(_tokenPattern, (match) { + final token = match[0] ?? ''; + final type = _typePattern.firstMatch(token); + if (type == null) return token; + final candidate = SearchKind.fromWire(type.group(1)!.toLowerCase()); + if (candidate == SearchKind.all) return token; + kind = candidate; + hasType = true; + return ''; + }); + return ParsedSearchQuery(query, kind, hasType); +} + +final _tokenPattern = RegExp( + r'''(?:[^\s"'\\]|\\[\s\S]|"(?:[^"\\]|\\[\s\S])*(?:"|$)|'(?:[^'\\]|\\[\s\S])*(?:'|$))+''', +); +final _typePattern = RegExp(r'^(?:t|type):([a-z]+)$', caseSensitive: false); + +/// Text searches and valid kind-only browsing are sendable. Empty text with no +/// supported kind clears locally, without an all-kind scan. +bool searchQuerySendable(String query, SearchKind kind) => + query.trim().isNotEmpty || kind != SearchKind.all; + +/// The message for a failed search: the unsupported sentence for a missing +/// payload or an unknown-command rejection, otherwise the server's own text. +String searchFailureText(Object? error) { + if (error == null) return unsupportedSearchCopy; + final message = error.toString().trim(); + if (message.isEmpty) return unsupportedSearchCopy; + if (_unsupportedCommand.hasMatch(message)) return unsupportedSearchCopy; + return message; +} + +final _unsupportedCommand = RegExp( + r'\b(unknown|unsupported|unrecognised|unrecognized)\b[\s\S]*\bcommand\b', + caseSensitive: false, +); + +/// One recorded edit being debounced. +class SearchEdit { + const SearchEdit(this.token, this.query); + + final int token; + final String query; +} + +/// Query sequencing: a burst of keystrokes collapses into one request, and a +/// reply is accepted only for the newest recorded edit, so a stale reply can +/// never overwrite a newer one. Recording an edit (a keystroke, or an empty +/// edit when the field clears) is enough to invalidate an in-flight reply. +class SearchSequencer { + int _newest = 0; + + SearchEdit edit(String query) => SearchEdit(++_newest, query); + + SearchEdit? begin(SearchEdit? edit) { + if (edit == null || edit.token != _newest) return null; + return edit; + } + + bool accepts(int token) => token == _newest; +} diff --git a/app/lib/features/search/domain/search_row.dart b/app/lib/features/search/domain/search_row.dart new file mode 100644 index 00000000..283feca7 --- /dev/null +++ b/app/lib/features/search/domain/search_row.dart @@ -0,0 +1,226 @@ +import '../../../core/api_gateway.dart'; +import 'search_format.dart'; + +export 'search_format.dart' show humanBytes, formatSearchTimestamp; + +/// One run of a field snippet, split so the first case-insensitive occurrence of +/// the query can be emphasised without colour or markup. +class SearchSnippetSpan { + const SearchSnippetSpan(this.text, {required this.matched}); + + final String text; + final bool matched; +} + +/// A render-ready search row. [target] is the server's own stable target token; +/// it is null for an unknown/absent payload or a reply without a target, and +/// such a row is read-only — the client never guesses a route. +class SearchRowView { + const SearchRowView({ + required this.title, + required this.secondary, + required this.kindLabel, + required this.snippetSpans, + required this.target, + this.snippet, + this.recency, + }); + + final String title; + final String secondary; + final String kindLabel; + final String? snippet; + final List snippetSpans; + final String? recency; + final String? target; + + bool get openable => target != null; +} + +/// One rendered search row, mirroring the browser's per-kind row text. Every +/// server-provided string is only ever compared or rendered as text. +SearchRowView searchRowView(JsonMap hit, String query) { + final pipeline = _map(hit['pipeline']); + final version = _map(hit['version']); + final run = _map(hit['run']); + final step = _map(hit['step']); + final field = _map(hit['field']); + final artifact = _map(hit['artifact']); + + final recency = formatSearchTimestamp('${hit['recency'] ?? ''}'); + final target = _serverTarget(hit); + + if (pipeline != null) { + return SearchRowView( + title: _nonBlank(pipeline['name']) ?? 'pipeline ${_num(pipeline['id'])}', + secondary: + 'pipeline ${_num(pipeline['id'])} · v${_num(pipeline['version'])}' + ' · ${_stageCount(pipeline['stages'])}', + kindLabel: 'Pipeline', + snippetSpans: const [], + recency: recency, + target: target, + ); + } + if (version != null) { + final hash = _nonBlank(version['content_hash']); + return SearchRowView( + title: + 'pipeline ${_num(version['pipeline_id'])}' + ' · v${_num(version['version'])}', + secondary: _join([ + hash == null ? null : 'content $hash', + formatSearchTimestamp('${version['created_at'] ?? ''}'), + ]), + kindLabel: 'Pipeline version', + snippetSpans: const [], + recency: recency, + target: target, + ); + } + if (run != null) { + final name = _nonBlank(run['pipeline_name']); + return SearchRowView( + title: 'run #${_num(run['id'])}${name == null ? '' : ' · $name'}', + secondary: _join([ + _nonBlank(run['status']), + _nonBlank(run['workspace']), + formatSearchTimestamp('${run['created_at'] ?? ''}'), + ]), + kindLabel: 'Run', + snippetSpans: const [], + recency: recency, + target: target, + ); + } + if (step != null) { + final stage = _nonBlank(step['stage']) ?? 'step'; + return SearchRowView( + title: + 'run #${_num(step['run_id'])} · $stage' + ' visit ${_num(step['visit'])}', + secondary: _stepSecondary(step), + kindLabel: 'Step', + snippetSpans: const [], + recency: recency, + target: target, + ); + } + if (field != null) { + final snippet = '${field['snippet'] ?? ''}'; + return SearchRowView( + title: + 'run #${_num(field['run_id'])} · step ${_num(field['sequence'])}' + ' · ${_nonBlank(field['field']) ?? 'field'}', + secondary: snippet, + kindLabel: 'Field', + snippet: snippet, + snippetSpans: snippetSpans(snippet, query), + recency: recency, + target: target, + ); + } + if (artifact != null) { + return SearchRowView( + title: _nonBlank(artifact['name']) ?? 'artifact', + secondary: _join([ + 'run #${_num(artifact['run_id'])}', + 'step ${_num(artifact['sequence'])}', + _nonBlank(artifact['content_type']), + humanBytes(_num(artifact['size_bytes'])), + ]), + kindLabel: 'Artifact', + snippetSpans: const [], + recency: recency, + target: target, + ); + } + final kind = _nonBlank(hit['kind']); + return SearchRowView( + title: _nonBlank(hit['target']) ?? 'Unrecognised result', + secondary: kind == null ? 'read-only' : 'kind "$kind" · read-only', + kindLabel: 'Unrecognised result', + snippetSpans: const [], + recency: recency, + target: target, + ); +} + +/// Splits [snippet] so the first case-insensitive occurrence of [query] is a +/// distinct matched span. A blank query or absent match leaves the whole +/// snippet unmatched, so no text is ever dropped. +List snippetSpans(String snippet, String query) { + if (snippet.isEmpty) return const []; + final needle = query.trim(); + if (needle.isEmpty) { + return [SearchSnippetSpan(snippet, matched: false)]; + } + final index = snippet.toLowerCase().indexOf(needle.toLowerCase()); + if (index < 0) return [SearchSnippetSpan(snippet, matched: false)]; + final end = index + needle.length; + return [ + if (index > 0) + SearchSnippetSpan(snippet.substring(0, index), matched: false), + SearchSnippetSpan(snippet.substring(index, end), matched: true), + if (end < snippet.length) + SearchSnippetSpan(snippet.substring(end), matched: false), + ]; +} + +String _stepSecondary(JsonMap step) { + final diagnostic = '${step['diagnostic'] ?? ''}'; + String? line; + for (final candidate in diagnostic.split(RegExp(r'\r?\n'))) { + if (candidate.trim().isNotEmpty) { + line = candidate; + break; + } + } + final target = _nonBlank(step['target']); + final joined = _join([ + _nonBlank(step['outcome']), + target == null ? null : '→ $target', + line?.trim(), + ]); + return joined.isEmpty ? 'step ${_num(step['sequence'])}' : joined; +} + +/// The server's own target token, never a target the client invents. A known +/// payload is not enough: an absent token makes the row read-only. +String? _serverTarget(JsonMap hit) { + final target = _nonBlank(hit['target']); + if (target == null) return null; + final known = [ + 'pipeline', + 'version', + 'run', + 'step', + 'field', + 'artifact', + ].any((key) => _map(hit[key]) != null); + return known ? target : null; +} + +String _stageCount(Object? count) { + final n = _num(count); + return '$n ${n == 1 ? 'stage' : 'stages'}'; +} + +Map? _map(Object? value) { + if (value is! Map) return null; + return Map.from(value); +} + +String? _nonBlank(Object? value) { + final text = '${value ?? ''}'; + return text.trim().isEmpty ? null : text; +} + +int _num(Object? value) { + if (value is int) return value; + if (value is num) return value.toInt(); + return int.tryParse('${value ?? ''}') ?? 0; +} + +String _join(List parts) => + parts.whereType().where((part) => part.isNotEmpty).join(' · '); diff --git a/app/lib/features/search/search_screen.dart b/app/lib/features/search/search_screen.dart new file mode 100644 index 00000000..3c2e80ce --- /dev/null +++ b/app/lib/features/search/search_screen.dart @@ -0,0 +1,228 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../core/api_gateway.dart'; +import 'data/search_repository.dart'; +import 'domain/search_controller.dart'; +import 'domain/search_models.dart'; +import 'ui/cupertino_search_body.dart'; +import 'ui/material_search_body.dart'; + +/// Native omni-search over the Pipelines server: a standard search field, an +/// explicit kind selector, and a flat result list whose rows open the server's +/// own target through [onOpen]. The screen never mutates server state and never +/// guesses a route for an unknown or targetless hit. +class SearchScreen extends StatefulWidget { + const SearchScreen({ + super.key, + required this.gateway, + required this.onOpen, + this.cupertino, + }); + + final ApiGateway gateway; + final ValueChanged onOpen; + + /// Lets the shell state the surface it composed. When omitted, iOS/macOS use + /// Cupertino controls and every other platform uses Material. + final bool? cupertino; + + @override + State createState() => _SearchScreenState(); +} + +class _SearchScreenState extends State { + late final OmniSearchController _controller; + late final TextEditingController _text; + + @override + void initState() { + super.initState(); + _controller = OmniSearchController( + repository: SearchRepository(widget.gateway), + ); + _text = TextEditingController(); + _controller.addListener(_onState); + } + + void _onState() { + final query = _controller.query; + if (_text.text != query) { + _text.value = TextEditingValue( + text: query, + selection: TextSelection.collapsed(offset: query.length), + ); + } + if (mounted) setState(() {}); + } + + void _clear() { + _text.clear(); + _controller.updateQuery(''); + } + + void _selectKind(SearchKind kind) => _controller.selectKind(kind); + + bool get _showHint { + final body = _controller.bodyKind; + return body == SearchBodyKind.idle || body == SearchBodyKind.empty; + } + + Future _pickKind(BuildContext context) async { + final selected = await showCupertinoModalPopup( + context: context, + builder: (context) => CupertinoActionSheet( + title: const Text('Kind'), + actions: [ + for (final kind in SearchKind.values) + CupertinoActionSheetAction( + onPressed: () => Navigator.pop(context, kind), + isDefaultAction: kind == _controller.parsed.kind, + child: Text(kind.label), + ), + ], + cancelButton: CupertinoActionSheetAction( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + ), + ); + if (selected != null) _selectKind(selected); + } + + @override + void dispose() { + _controller.removeListener(_onState); + _controller.dispose(); + _text.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final cupertino = + widget.cupertino ?? + switch (Theme.of(context).platform) { + TargetPlatform.iOS || TargetPlatform.macOS => true, + _ => false, + }; + return cupertino ? _cupertinoScreen() : _materialScreen(); + } + + Widget _materialScreen() => Scaffold( + appBar: AppBar(title: const Text('Search')), + body: SafeArea( + child: MaterialSearchBody( + controller: _controller, + query: _controller.parsed.query, + onOpen: widget.onOpen, + header: _materialHeader(), + ), + ), + ); + + Widget _materialHeader() => Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + spacing: 8, + children: [ + SearchBar( + key: const ValueKey('search.field'), + controller: _text, + autoFocus: true, + hintText: 'Search pipelines, runs and artifacts', + leading: const Icon(Icons.search), + trailing: [ + if (_text.text.isNotEmpty) + IconButton( + key: const ValueKey('search.clear'), + onPressed: _clear, + tooltip: 'Clear search', + icon: const Icon(Icons.close), + ), + ], + textInputAction: TextInputAction.search, + onChanged: _controller.updateQuery, + onSubmitted: (_) => _controller.submit(), + ), + InputDecorator( + decoration: const InputDecoration( + labelText: 'Kind', + border: OutlineInputBorder(), + ), + child: DropdownButtonHideUnderline( + child: DropdownButton( + key: const ValueKey('search.kind'), + value: _controller.parsed.kind, + isExpanded: true, + onChanged: (kind) { + if (kind != null) _selectKind(kind); + }, + items: [ + for (final kind in SearchKind.values) + DropdownMenuItem(value: kind, child: Text(kind.label)), + ], + ), + ), + ), + if (_showHint) const Text(_tokenHint), + if (_controller.boundsText case final bounds?) Text(bounds), + ], + ), + ); + + Widget _cupertinoScreen() => CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar(middle: Text('Search')), + child: SafeArea( + child: CupertinoSearchBody( + controller: _controller, + query: _controller.parsed.query, + onOpen: widget.onOpen, + header: _cupertinoHeader(context), + ), + ), + ); + + Widget _cupertinoHeader(BuildContext context) => Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + spacing: 8, + children: [ + CupertinoSearchTextField( + key: const ValueKey('search.field'), + controller: _text, + autofocus: true, + placeholder: 'Search pipelines, runs and artifacts', + onChanged: _controller.updateQuery, + onSubmitted: (_) => _controller.submit(), + onSuffixTap: _clear, + ), + Align( + alignment: AlignmentDirectional.centerStart, + child: CupertinoButton( + key: const ValueKey('search.kind'), + padding: EdgeInsets.zero, + onPressed: () => _pickKind(context), + child: Row( + mainAxisSize: MainAxisSize.max, + spacing: 6, + children: [ + Expanded(child: Text('Kind: ${_controller.parsed.kind.label}')), + const Icon(CupertinoIcons.chevron_down), + ], + ), + ), + ), + if (_showHint) const Text(_tokenHint), + if (_controller.boundsText case final bounds?) Text(bounds), + ], + ), + ); +} + +const _tokenHint = + 'Filter with t:pipeline or type:artifact (pipeline, run, step, field, ' + 'artifact, version). Last type wins; choosing Kind replaces it. Quote ' + 'tokens to search literally.'; diff --git a/app/lib/features/search/ui/cupertino_search_body.dart b/app/lib/features/search/ui/cupertino_search_body.dart new file mode 100644 index 00000000..2f29d3b0 --- /dev/null +++ b/app/lib/features/search/ui/cupertino_search_body.dart @@ -0,0 +1,174 @@ +import 'package:flutter/cupertino.dart'; + +import '../../../core/api_gateway.dart'; +import '../domain/search_controller.dart'; +import '../domain/search_row.dart'; +import 'search_result_view.dart'; + +/// The Cupertino search view: native search/kind controls and grouped list rows +/// in one scroll view, with standard activity and retry controls. +class CupertinoSearchBody extends StatelessWidget { + const CupertinoSearchBody({ + super.key, + required this.controller, + required this.query, + required this.onOpen, + required this.header, + }); + + final OmniSearchController controller; + final String query; + final ValueChanged onOpen; + final Widget header; + + @override + Widget build(BuildContext context) { + return CustomScrollView( + slivers: [ + SliverToBoxAdapter(child: header), + if (controller.showProgress) + const SliverToBoxAdapter( + child: Padding( + padding: EdgeInsets.symmetric(vertical: 8), + child: CupertinoActivityIndicator(), + ), + ), + ..._content(context), + ], + ); + } + + List _content(BuildContext context) { + switch (controller.bodyKind) { + case SearchBodyKind.error: + return [ + SliverFillRemaining( + hasScrollBody: false, + child: _CupertinoError( + message: controller.error!, + onRetry: controller.retry, + ), + ), + ]; + case SearchBodyKind.searching: + return const [ + SliverFillRemaining( + hasScrollBody: false, + child: _CupertinoSearching(), + ), + ]; + case SearchBodyKind.results: + return [ + SliverToBoxAdapter( + child: CupertinoListSection.insetGrouped( + children: [ + for (final hit in controller.shownResults) + _CupertinoResult(hit: hit, query: query, onOpen: onOpen), + ], + ), + ), + ]; + case SearchBodyKind.empty: + return [ + SliverFillRemaining( + hasScrollBody: false, + child: _CupertinoMessage(message: controller.emptyMessage!), + ), + ]; + case SearchBodyKind.idle: + return const [ + SliverFillRemaining( + hasScrollBody: false, + child: _CupertinoMessage( + message: 'Search pipelines, runs and artifacts.', + ), + ), + ]; + } + } +} + +class _CupertinoResult extends StatelessWidget { + const _CupertinoResult({ + required this.hit, + required this.query, + required this.onOpen, + }); + + final JsonMap hit; + final String query; + final ValueChanged onOpen; + + @override + Widget build(BuildContext context) { + final row = searchRowView(hit, query); + return CupertinoListTile( + key: ValueKey('search.result.${hit['target']}'), + leading: Icon(searchCupertinoIcon('${hit['kind'] ?? ''}')), + title: Text(row.title), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + spacing: 2, + children: [searchRowMeta(row), searchRowSnippet(context, row)], + ), + onTap: row.openable ? () => onOpen(hit) : null, + ); + } +} + +class _CupertinoSearching extends StatelessWidget { + const _CupertinoSearching(); + + @override + Widget build(BuildContext context) => const Center( + child: Padding( + padding: EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + spacing: 12, + children: [CupertinoActivityIndicator(), Text('Searching…')], + ), + ), + ); +} + +class _CupertinoMessage extends StatelessWidget { + const _CupertinoMessage({required this.message}); + + final String message; + + @override + Widget build(BuildContext context) => Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Text(message, textAlign: TextAlign.center), + ), + ); +} + +class _CupertinoError extends StatelessWidget { + const _CupertinoError({required this.message, required this.onRetry}); + + final String message; + final Future Function() onRetry; + + @override + Widget build(BuildContext context) => Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + spacing: 12, + children: [ + Text(message, textAlign: TextAlign.center), + CupertinoButton.filled( + key: const ValueKey('search.retry'), + onPressed: onRetry, + child: const Text('Retry'), + ), + ], + ), + ), + ); +} diff --git a/app/lib/features/search/ui/material_search_body.dart b/app/lib/features/search/ui/material_search_body.dart new file mode 100644 index 00000000..462f75ee --- /dev/null +++ b/app/lib/features/search/ui/material_search_body.dart @@ -0,0 +1,166 @@ +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../domain/search_controller.dart'; +import '../domain/search_row.dart'; +import 'search_result_view.dart'; + +/// The Material search view: the controls header and a flat native result list +/// in one scroll view, so text scaling can never clip the controls or a row. +class MaterialSearchBody extends StatelessWidget { + const MaterialSearchBody({ + super.key, + required this.controller, + required this.query, + required this.onOpen, + required this.header, + }); + + final OmniSearchController controller; + final String query; + final ValueChanged onOpen; + final Widget header; + + @override + Widget build(BuildContext context) { + return CustomScrollView( + slivers: [ + SliverToBoxAdapter(child: header), + if (controller.showProgress) + const SliverToBoxAdapter(child: LinearProgressIndicator()), + ..._content(context), + ], + ); + } + + List _content(BuildContext context) { + switch (controller.bodyKind) { + case SearchBodyKind.error: + return [ + SliverFillRemaining( + hasScrollBody: false, + child: _SearchError( + message: controller.error!, + onRetry: controller.retry, + ), + ), + ]; + case SearchBodyKind.searching: + return const [ + SliverFillRemaining(hasScrollBody: false, child: _Searching()), + ]; + case SearchBodyKind.results: + return [ + SliverList.builder( + itemCount: controller.shownResults.length, + itemBuilder: (context, index) { + final hit = controller.shownResults[index]; + return _MaterialResult(hit: hit, query: query, onOpen: onOpen); + }, + ), + ]; + case SearchBodyKind.empty: + return [ + SliverFillRemaining( + hasScrollBody: false, + child: _SearchMessage(message: controller.emptyMessage!), + ), + ]; + case SearchBodyKind.idle: + return const [ + SliverFillRemaining( + hasScrollBody: false, + child: _SearchMessage( + message: 'Search pipelines, runs and artifacts.', + ), + ), + ]; + } + } +} + +class _MaterialResult extends StatelessWidget { + const _MaterialResult({ + required this.hit, + required this.query, + required this.onOpen, + }); + + final JsonMap hit; + final String query; + final ValueChanged onOpen; + + @override + Widget build(BuildContext context) { + final row = searchRowView(hit, query); + return ListTile( + key: ValueKey('search.result.${hit['target']}'), + leading: Icon(searchMaterialIcon('${hit['kind'] ?? ''}')), + title: Text(row.title), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + spacing: 2, + children: [searchRowMeta(row), searchRowSnippet(context, row)], + ), + onTap: row.openable ? () => onOpen(hit) : null, + ); + } +} + +class _Searching extends StatelessWidget { + const _Searching(); + + @override + Widget build(BuildContext context) => const Center( + child: Padding( + padding: EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + spacing: 12, + children: [CircularProgressIndicator(), Text('Searching…')], + ), + ), + ); +} + +class _SearchMessage extends StatelessWidget { + const _SearchMessage({required this.message}); + + final String message; + + @override + Widget build(BuildContext context) => Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Text(message, textAlign: TextAlign.center), + ), + ); +} + +class _SearchError extends StatelessWidget { + const _SearchError({required this.message, required this.onRetry}); + + final String message; + final Future Function() onRetry; + + @override + Widget build(BuildContext context) => Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + spacing: 12, + children: [ + Text(message, textAlign: TextAlign.center), + FilledButton.tonalIcon( + key: const ValueKey('search.retry'), + onPressed: onRetry, + icon: const Icon(Icons.refresh), + label: const Text('Retry'), + ), + ], + ), + ), + ); +} diff --git a/app/lib/features/search/ui/search_result_view.dart b/app/lib/features/search/ui/search_result_view.dart new file mode 100644 index 00000000..fef687f3 --- /dev/null +++ b/app/lib/features/search/ui/search_result_view.dart @@ -0,0 +1,59 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../domain/search_row.dart'; + +/// Kind, recency and read-only affordance for one row. Deliberately unstyled +/// beyond weight so Material and Cupertino inherit their own system typography +/// and colours, including dark mode and text scaling. +Widget searchRowMeta(SearchRowView row) { + final parts = [row.kindLabel, if (row.recency != null) row.recency!]; + return Text( + parts.join(' · '), + style: const TextStyle(fontWeight: FontWeight.w600), + ); +} + +/// The snippet with the first query occurrence emphasised by weight, never by +/// parsing server text as markup or by a bespoke colour. +Widget searchRowSnippet(BuildContext context, SearchRowView row) { + final snippet = row.snippet; + if (snippet == null) { + return row.secondary.isEmpty + ? const SizedBox.shrink() + : Text(row.secondary); + } + return Text.rich( + TextSpan( + children: [ + for (final span in row.snippetSpans) + TextSpan( + text: span.text, + style: span.matched + ? const TextStyle(fontWeight: FontWeight.bold) + : null, + ), + ], + ), + ); +} + +IconData searchMaterialIcon(String kind) => switch (kind) { + 'pipeline' => Icons.account_tree_outlined, + 'version' => Icons.layers_outlined, + 'run' => Icons.play_circle_outline, + 'step' => Icons.arrow_forward, + 'field' => Icons.notes, + 'artifact' => Icons.attach_file, + _ => Icons.help_outline, +}; + +IconData searchCupertinoIcon(String kind) => switch (kind) { + 'pipeline' => CupertinoIcons.arrow_branch, + 'version' => CupertinoIcons.square_stack_3d_up, + 'run' => CupertinoIcons.play_circle, + 'step' => CupertinoIcons.arrow_right, + 'field' => CupertinoIcons.doc_text, + 'artifact' => CupertinoIcons.paperclip, + _ => CupertinoIcons.question_circle, +}; diff --git a/app/notes/X1.md b/app/notes/X1.md new file mode 100644 index 00000000..72e19645 --- /dev/null +++ b/app/notes/X1.md @@ -0,0 +1,121 @@ +# X1 — Omni-search + +## Scope and API + +Implemented the `search` feature under `lib/features/search/` with no +`main.dart`, shell, pubspec, server, web or Android edits. + +Entry point: + +```dart +SearchScreen( + gateway: apiGateway, // required ApiGateway + onOpen: (hit) { ... }, // required ValueChanged + cupertino: null, // optional; omitted = iOS/macOS Cupertino, else Material +) +``` + +`onOpen` always receives the server's original result map unchanged, including +its `target`. Unknown/absent payloads and results without a target are +read-only and never call `onOpen`; the client never invents a route or mutates +server state. + +Request shape is exact and shared-gateway only: + +```json +{"type":"search","search":{"query":"plan","kind":"","limit":0}} +``` + +`limit` is always `0` (server default cap), never a client-chosen larger value. + +## Behaviour + +- `t:`/`type:` tokens: unquoted, whitespace-delimited, case-insensitive, last + supported token wins; quoted, escaped, unknown and trailing-punctuation + tokens stay literal. The parser mirrors `web/src/search.js`. +- Kind selector: All kinds / Pipelines / Runs / Steps / Fields / Artifacts / + Versions. Changing it removes recognised type tokens from the field and sends + at once, like the browser's selector. +- Empty text with All kinds clears locally and sends nothing. Blank text with a + valid kind is a kind-only browse, matching the server/browser contract. +- 250 ms debounce; Enter sends at once. Every request carries a monotonically + increasing token, and replies for superseded edits are dropped. +- Loading, searching, retained-results refresh progress, empty (query-specific + and kind-only wording) and error are distinct. A truncated reply with no rows + says the server's scan limit was reached and keeps its truncation/scan bounds + on screen instead of claiming a complete empty; a complete empty has no bounds + line. A reply without `search_results` and an unknown-command rejection use + the server-upgrade sentence; any other failure shows the server's own text. + Error state offers Retry. +- Rows show the kind derived from the server payload (`Unrecognised result` for + an unknown payload), title, snippet (first case-insensitive query occurrence in + bold), and recency. Bounds show result count, cap, scanned steps/bytes, scan + limit and a truncation sentence when the server reports it, including for a + truncated reply with zero rows. +- In-hand results are re-narrowed by the effective kind while a narrowed request + loads, so the list always agrees with the control. +- Standard platform controls only: Material `SearchBar`, dropdown, + `LinearProgressIndicator`, `CircularProgressIndicator`, `ListTile`, + `FilledButton.tonalIcon`; Cupertino `CupertinoSearchTextField`, action-sheet + kind picker, `CupertinoListSection`/`CupertinoListTile`, + `CupertinoActivityIndicator`, `CupertinoButton.filled`. No CSS port, custom + palette, fixed row/bubble dimensions or bespoke buttons. Typography and + colours come from the ambient Material/Cupertino theme; rows and the header + scroll in one `CustomScrollView` so 2× text never clips. + +## Automated checks + +Run from `app/` with `/Users/alan/development/flutter/bin/flutter`: + +- `flutter test test/features/search` — **36 passed** (controller, repository, + query/token parser, row/snippet/routing, Material + Cupertino widget tests). +- `flutter test` — **65 passed** (whole app suite, including existing transport, + runs and shell tests). +- `flutter analyze` — **No issues found**. +- `flutter build web` (default `lib/main.dart`) — **succeeded**. +- `flutter build web -t tool/search_fixture/main.dart` — **succeeded** for the + rendered probe. +- `node --check tool/search_probe.mjs` — passed. +- `git diff --no-index --check /dev/null ` on every touched file — no + whitespace errors (all task files are untracked, so plain `git diff --check` + would not see them). + +Tests were written before the implementation (initial run failed on missing +symbols). Coverage includes the exact envelope, token parsing, selector token +clearing, no-request empty state, stale success and failure replies, +error/retry, truncation/bounds (including a truncated reply with zero rows), +per-kind row text, snippet spans, read-only hits, `onOpen` targets, and +MaterialApp/CupertinoApp at 390/1000 wide with 2× text. + +## Rendered browser evidence + +Built the Web-only fixture (`tool/search_fixture/main.dart`) and drove real +headless Chrome through CDP with `tool/search_probe.mjs` on an OS-assigned +loopback port. The probe typed `plan` into the real field, asserted five rows, +the server snippet, recency and truncation/scanned bounds, then clicked the +pipeline row and asserted that the fixture receiver got `pipeline:24`. It also +typed `needle` with no matching fixtures and asserted the Material and Cupertino +truncated-empty copy plus the retained `Results truncated … 0 results … scanned +2000 steps … scan limit 1.0 MiB` line, capturing both. + +Captures are in the run's shared artifacts: + +- `/Users/alan/.local/share/pipelines/data/artifacts/49/public/x1-search/x1-search-material-phone.png` — 390×844, Material controls, five mixed-kind results with recency/snippet/bounds. +- `/Users/alan/.local/share/pipelines/data/artifacts/49/public/x1-search/x1-search-material-desktop.png` — 1280×800, same results. +- `/Users/alan/.local/share/pipelines/data/artifacts/49/public/x1-search/x1-search-cupertino-phone.png` — 390×844, Cupertino search field/kind picker/grouped rows, dark system theme. +- `/Users/alan/.local/share/pipelines/data/artifacts/49/public/x1-search/x1-search-open-target.png` — the row click landing on `Opened pipeline target: pipeline:24`. +- `/Users/alan/.local/share/pipelines/data/artifacts/49/public/x1-search/x1-search-truncated-empty.png` — 390×844 Material, zero rows with the server's scan-limit sentence and truncation/scan bounds. +- `/Users/alan/.local/share/pipelines/data/artifacts/49/public/x1-search/x1-search-truncated-empty-cupertino.png` — 390×844 Cupertino dark, the same bounded empty state. + +The fixture and probe are development-only entry points; they are not imported +by `lib/main.dart` and are not part of the production routing. The browser run +used a static fake gateway, not a live Pipelines server or operator data. + +## Not verified / open items + +- No shell registration or navigation wiring was added (manager owns + `main.dart`/`shell/`); the screen is exported for that integration. +- No real server, operator chat/run, or production URL was used. +- Mobile targets (Android/iOS) were **not** built, installed or exercised; + only Web was rendered and tested. Source is kept portable. +- No commit, push, deployment or canonical URL change was made. diff --git a/app/test/features/search/search_controller_failure_test.dart b/app/test/features/search/search_controller_failure_test.dart new file mode 100644 index 00000000..43f217c1 --- /dev/null +++ b/app/test/features/search/search_controller_failure_test.dart @@ -0,0 +1,90 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/search/domain/search_controller.dart'; +import 'package:pipelines_app/features/search/domain/search_query.dart'; +import 'search_test_support.dart'; + +void main() { + test('a server error is shown, and retry issues a fresh request', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('plan'); + await pumpEventQueue(); + gateway.fail(0, StateError('server is down')); + await pumpEventQueue(); + + expect(controller.bodyKind, SearchBodyKind.error); + expect(controller.error, contains('server is down')); + + final retry = controller.retry(); + await pumpEventQueue(); + expect(gateway.calls, hasLength(2)); + expect(gateway.lastSearch, {'query': 'plan', 'kind': '', 'limit': 0}); + + gateway.succeed( + 1, + envelope([ + { + 'kind': 'pipeline', + 'target': 'pipeline:7', + 'pipeline': {'id': 7}, + }, + ]), + ); + await retry; + expect(controller.error, isNull); + expect(controller.results, hasLength(1)); + expect(controller.bodyKind, SearchBodyKind.results); + }); + + test('a stale failure never replaces the newest query state', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('first'); + await pumpEventQueue(); + controller.updateQuery('second'); + await pumpEventQueue(); + + gateway.fail(0, StateError('stale failure')); + await pumpEventQueue(); + + expect(controller.error, isNull); + expect(controller.loading, isTrue); + expect(controller.bodyKind, SearchBodyKind.searching); + + gateway.succeed( + 1, + envelope([ + { + 'kind': 'pipeline', + 'target': 'pipeline:9', + 'pipeline': {'id': 9}, + }, + ]), + ); + await pumpEventQueue(); + expect(controller.error, isNull); + expect(controller.results.single['target'], 'pipeline:9'); + expect(controller.bodyKind, SearchBodyKind.results); + }); + + test( + 'a missing search_results payload reports the unsupported copy', + () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('plan'); + await pumpEventQueue(); + gateway.succeed(0, {'type': 'pong'}); + await pumpEventQueue(); + + expect(controller.bodyKind, SearchBodyKind.error); + expect(controller.error, unsupportedSearchCopy); + }, + ); +} diff --git a/app/test/features/search/search_controller_test.dart b/app/test/features/search/search_controller_test.dart new file mode 100644 index 00000000..f9d90fe3 --- /dev/null +++ b/app/test/features/search/search_controller_test.dart @@ -0,0 +1,240 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/search/domain/search_controller.dart'; +import 'package:pipelines_app/features/search/domain/search_models.dart'; +import 'search_test_support.dart'; + +void main() { + test('empty query with no kind is idle and sends no request', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery(' '); + await pumpEventQueue(); + + expect(gateway.calls, isEmpty); + expect(controller.bodyKind, SearchBodyKind.idle); + expect(controller.results, isEmpty); + expect(controller.loaded, isFalse); + expect(controller.loading, isFalse); + }); + + test('the request carries the parsed query, kind and limit 0', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('t:run Plan TYPE:artifact'); + await pumpEventQueue(); + + expect(gateway.calls, hasLength(1)); + expect(gateway.lastSearch, { + 'query': 'Plan', + 'kind': 'artifact', + 'limit': 0, + }); + }); + + test( + 'a kind selector change removes type tokens and sends at once', + () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('plan t:run'); + await pumpEventQueue(); + expect(gateway.lastSearch['kind'], 'run'); + + controller.selectKind(SearchKind.pipeline); + await pumpEventQueue(); + + expect(controller.query.trim(), 'plan'); + expect(controller.query, isNot(contains('t:run'))); + expect(controller.selectedKind, SearchKind.pipeline); + expect(gateway.calls, hasLength(2)); + expect(gateway.lastSearch, { + 'query': 'plan', + 'kind': 'pipeline', + 'limit': 0, + }); + }, + ); + + test( + 'kind-only browsing sends a blank query and reports the empty copy', + () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.selectKind(SearchKind.pipeline); + await pumpEventQueue(); + expect(gateway.lastSearch, {'query': '', 'kind': 'pipeline', 'limit': 0}); + expect(controller.bodyKind, SearchBodyKind.searching); + + gateway.succeed(0, envelope(const [])); + await pumpEventQueue(); + expect(controller.bodyKind, SearchBodyKind.empty); + expect(controller.emptyMessage, 'No pipelines yet.'); + }, + ); + + test('the latest query wins and a stale reply is dropped', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('first'); + await pumpEventQueue(); + controller.updateQuery('second'); + await pumpEventQueue(); + expect(gateway.calls, hasLength(2)); + + gateway.succeed( + 0, + envelope([ + { + 'kind': 'run', + 'target': 'run:1', + 'run': {'id': 1}, + }, + ]), + ); + await pumpEventQueue(); + expect(controller.results, isEmpty); + expect(controller.loading, isTrue); + expect(controller.bodyKind, SearchBodyKind.searching); + + gateway.succeed( + 1, + envelope([ + { + 'kind': 'run', + 'target': 'run:2', + 'run': {'id': 2}, + }, + ]), + ); + await pumpEventQueue(); + expect(controller.results.single['target'], 'run:2'); + expect(controller.loading, isFalse); + expect(controller.bodyKind, SearchBodyKind.results); + }); + + test('truncation and scan bounds come from the server envelope', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('plan'); + await pumpEventQueue(); + gateway.succeed( + 0, + envelope( + [ + { + 'kind': 'field', + 'target': 'run:11:4:output', + 'field': {'run_id': 11}, + }, + ], + truncated: true, + scannedSteps: 2000, + scannedBytes: 1048576, + cap: 50, + ), + ); + await pumpEventQueue(); + + expect(controller.truncated, isTrue); + expect(controller.scannedSteps, 2000); + expect(controller.scannedBytes, 1048576); + expect(controller.cap, 50); + expect(controller.boundsText, contains('truncated')); + expect(controller.boundsText, contains('cap 50')); + expect(controller.boundsText, contains('2000 steps')); + }); + + test( + 'a truncated empty reply reports the scan bound instead of a complete empty', + () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('needle'); + await pumpEventQueue(); + gateway.succeed( + 0, + envelope( + const [], + truncated: true, + scannedSteps: 2000, + scannedBytes: 1048576, + cap: 50, + ), + ); + await pumpEventQueue(); + + expect(controller.bodyKind, SearchBodyKind.empty); + expect( + controller.emptyMessage, + 'No matches for "needle" within the server\'s scan limit.', + ); + expect(controller.boundsText, contains('Results truncated')); + expect(controller.boundsText, contains('0 results')); + expect(controller.boundsText, contains('2000 steps')); + expect(controller.boundsText, contains('scan limit 1.0 MiB')); + }, + ); + + test( + 'a complete empty reply stays a plain empty with no bounds line', + () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('needle'); + await pumpEventQueue(); + gateway.succeed(0, envelope(const [])); + await pumpEventQueue(); + + expect(controller.bodyKind, SearchBodyKind.empty); + expect(controller.emptyMessage, 'No matches for "needle".'); + expect(controller.boundsText, isNull); + }, + ); + + test('in-hand kind narrowing keeps the list honest while loading', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('plan'); + await pumpEventQueue(); + gateway.succeed( + 0, + envelope([ + { + 'kind': 'run', + 'target': 'run:1', + 'run': {'id': 1}, + }, + { + 'kind': 'pipeline', + 'target': 'pipeline:7', + 'pipeline': {'id': 7}, + }, + ]), + ); + await pumpEventQueue(); + expect(controller.shownResults, hasLength(2)); + + controller.selectKind(SearchKind.run); + await pumpEventQueue(); + expect(controller.shownResults, hasLength(1)); + expect(controller.shownResults.single['target'], 'run:1'); + }); +} diff --git a/app/test/features/search/search_query_test.dart b/app/test/features/search/search_query_test.dart new file mode 100644 index 00000000..942a9b73 --- /dev/null +++ b/app/test/features/search/search_query_test.dart @@ -0,0 +1,118 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/search/domain/search_models.dart'; +import 'package:pipelines_app/features/search/domain/search_query.dart'; + +const unsupported = + 'This server does not support search. Update the Pipelines server, then try again.'; + +void main() { + test('kind vocabulary is exactly the server vocabulary, All kinds first', () { + expect(SearchKind.values.map((kind) => kind.wire), [ + '', + 'pipeline', + 'run', + 'step', + 'field', + 'artifact', + 'version', + ]); + expect(SearchKind.values.map((kind) => kind.label), [ + 'All kinds', + 'Pipelines', + 'Runs', + 'Steps', + 'Fields', + 'Artifacts', + 'Versions', + ]); + expect(SearchKind.fromWire('run'), SearchKind.run); + expect(SearchKind.fromWire(''), SearchKind.all); + expect(SearchKind.fromWire('prompts'), SearchKind.all); + expect(SearchKind.fromWire(null), SearchKind.all); + }); + + test('both type aliases and kinds are case insensitive', () { + for (final kind in SearchKind.values.where( + (kind) => kind != SearchKind.all, + )) { + for (final prefix in ['t', 'type', 'T', 'TyPe']) { + final parsed = parseSearchQuery( + '$prefix:${kind.wire.toUpperCase()} plan', + ); + expect(parsed.query, ' plan'); + expect(parsed.kind, kind); + expect(parsed.hasType, isTrue); + } + } + }); + + test('normal, quoted and unsupported text is preserved byte for byte', () { + const preserved = [ + ' ordinary text\twith\nspacing ', + '"t:pipeline" "hello world"', + "'type:artifact'", + '"escaped \\" t:run"', + '"unclosed t:run', + 't:prompt type:unknown t: t:PIPELINES', + 'not:t:run t:run,', + 'prefix"t:run"', + '\\t:run', + ]; + for (final query in preserved) { + final parsed = parseSearchQuery(query, SearchKind.field); + expect(parsed.query, query); + expect(parsed.kind, SearchKind.field); + expect(parsed.hasType, isFalse); + } + expect( + parseSearchQuery('t:artifact "t:pipeline" report').query, + ' "t:pipeline" report', + ); + }); + + test('last supported token wins over the selector; unknown tokens stay', () { + final parsed = parseSearchQuery( + 't:run plan TYPE:artifact t:unknown', + SearchKind.pipeline, + ); + expect(parsed.query, ' plan t:unknown'); + expect(parsed.kind, SearchKind.artifact); + expect(parsed.hasType, isTrue); + expect(parseSearchQuery('plan', SearchKind.step).kind, SearchKind.step); + }); + + test('type-only query is distinguishable from literal and blank input', () { + final typed = parseSearchQuery('t:pipeline'); + expect(typed.query, ''); + expect(typed.kind, SearchKind.pipeline); + expect(typed.hasType, isTrue); + final blank = parseSearchQuery(''); + expect(blank.query, ''); + expect(blank.kind, SearchKind.all); + expect(blank.hasType, isFalse); + }); + + test('blank text is sendable only with a supported nonempty kind', () { + for (final kind in SearchKind.values) { + expect(searchQuerySendable(' \n\t ', kind), kind != SearchKind.all); + } + expect(searchQuerySendable('', SearchKind.all), isFalse); + expect(searchQuerySendable('plan', SearchKind.all), isTrue); + expect(searchQuerySendable(' plan ', SearchKind.all), isTrue); + }); + + test( + 'failure copy distinguishes an unsupported server from a plain error', + () { + expect(searchFailureText(null), unsupported); + expect(searchFailureText(' '), unsupported); + expect(searchFailureText('unknown command: search'), unsupported); + expect(searchFailureText('unsupported command'), unsupported); + expect(searchFailureText('boom'), 'boom'); + expect( + searchFailureText('request timed out after 30000ms'), + 'request timed out after 30000ms', + ); + }, + ); +} diff --git a/app/test/features/search/search_repository_test.dart b/app/test/features/search/search_repository_test.dart new file mode 100644 index 00000000..1760b363 --- /dev/null +++ b/app/test/features/search/search_repository_test.dart @@ -0,0 +1,106 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/search/data/search_repository.dart'; +import 'package:pipelines_app/features/search/domain/search_models.dart'; + +class RecordingGateway implements ApiGateway { + String? type; + JsonMap fields = {}; + JsonMap reply = {}; + Object? failure; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + this.type = type; + this.fields = Map.of(fields); + if (failure case final error?) throw error; + return reply; + } + + @override + Stream get frames => const Stream.empty(); +} + +void main() { + test( + 'search sends exactly search/query/kind/limit and parses bounds', + () async { + final gateway = RecordingGateway() + ..reply = { + 'search_results': { + 'query': 'plan', + 'kind': 'run', + 'results': [ + { + 'kind': 'run', + 'target': 'run:11', + 'run': {'id': 11}, + }, + ], + 'truncated': true, + 'scanned_steps': 27, + 'scanned_bytes': 4096, + 'cap': 50, + 'scan_bound_bytes': 1048576, + }, + }; + final repository = SearchRepository(gateway); + + final response = await repository.search( + query: 'plan', + kind: SearchKind.run, + ); + + expect(gateway.type, 'search'); + expect(gateway.fields, { + 'search': {'query': 'plan', 'kind': 'run', 'limit': 0}, + }); + expect(response, isNotNull); + expect(response!.query, 'plan'); + expect(response.kind, SearchKind.run); + expect(response.results.single['target'], 'run:11'); + expect(response.truncated, isTrue); + expect(response.scannedSteps, 27); + expect(response.scannedBytes, 4096); + expect(response.cap, 50); + expect(response.scanBoundBytes, 1048576); + }, + ); + + test('all-kinds search still sends the empty kind field', () async { + final gateway = RecordingGateway() + ..reply = { + 'search_results': {'results': []}, + }; + await SearchRepository(gateway).search(query: 'plan', kind: SearchKind.all); + expect(gateway.fields, { + 'search': {'query': 'plan', 'kind': '', 'limit': 0}, + }); + }); + + test( + 'a reply without search_results is null, not an empty success', + () async { + final gateway = RecordingGateway()..reply = {'type': 'pong'}; + final response = await SearchRepository( + gateway, + ).search(query: 'plan', kind: SearchKind.all); + expect(response, isNull); + }, + ); + + test('server refusals propagate to the caller unchanged', () async { + final gateway = RecordingGateway() + ..failure = StateError('permission denied'); + await expectLater( + SearchRepository(gateway).search(query: 'plan', kind: SearchKind.all), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'permission denied', + ), + ), + ); + }); +} diff --git a/app/test/features/search/search_row_test.dart b/app/test/features/search/search_row_test.dart new file mode 100644 index 00000000..086f2246 --- /dev/null +++ b/app/test/features/search/search_row_test.dart @@ -0,0 +1,161 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/search/domain/search_row.dart'; + +JsonMap pipelineHit([JsonMap overrides = const {}]) => { + 'kind': 'pipeline', + 'target': 'pipeline:7', + 'pipeline': { + 'id': 7, + 'name': 'release', + 'version': 3, + 'stages': 4, + ...overrides, + }, +}; + +JsonMap versionHit() => { + 'kind': 'version', + 'target': 'pipeline:9:v2', + 'recency': '2026-01-01T00:00:00Z', + 'version': { + 'pipeline_id': 9, + 'version': 2, + 'content_hash': 'abc', + 'created_at': '2026-01-01T00:00:00Z', + }, +}; + +JsonMap runHit([JsonMap overrides = const {}]) => { + 'kind': 'run', + 'target': 'run:11', + 'run': { + 'id': 11, + 'pipeline_name': 'release', + 'status': 'succeeded', + 'created_at': '2026-01-01T00:00:00Z', + ...overrides, + }, +}; + +JsonMap stepHit([JsonMap overrides = const {}]) => { + 'kind': 'step', + 'target': 'run:11:4', + 'step': { + 'run_id': 11, + 'sequence': 4, + 'stage': 'builder', + 'visit': 2, + 'outcome': 'success', + ...overrides, + }, +}; + +JsonMap fieldHit([JsonMap overrides = const {}]) => { + 'kind': 'field', + 'target': 'run:11:4:output', + 'matched_field': 'output', + 'field': { + 'run_id': 11, + 'sequence': 4, + 'field': 'output', + 'snippet': 'the release is ready', + ...overrides, + }, +}; + +JsonMap artifactHit([JsonMap overrides = const {}]) => { + 'kind': 'artifact', + 'target': '/artifacts/11/4/notes.md', + 'artifact': { + 'run_id': 11, + 'sequence': 4, + 'name': 'notes.md', + 'content_type': 'text/markdown', + 'size_bytes': 2048, + ...overrides, + }, +}; + +void main() { + test('per-kind rows mirror the browser titles and secondary lines', () { + final pipeline = searchRowView(pipelineHit(), 'release'); + expect(pipeline.title, 'release'); + expect(pipeline.secondary, 'pipeline 7 · v3 · 4 stages'); + expect(pipeline.kindLabel, 'Pipeline'); + expect(pipeline.target, 'pipeline:7'); + + final blankName = searchRowView(pipelineHit({'name': ' '}), 'x'); + expect(blankName.title, 'pipeline 7'); + + final version = searchRowView(versionHit(), 'release'); + expect(version.title, 'pipeline 9 · v2'); + expect(version.secondary, startsWith('content abc · ')); + expect(version.recency, isNotNull); + + final run = searchRowView(runHit(), 'release'); + expect(run.title, 'run #11 · release'); + expect(run.secondary, startsWith('succeeded · ')); + expect(run.secondary.split(' · '), hasLength(2)); + + final unnamed = searchRowView(runHit({'pipeline_name': ''}), ''); + expect(unnamed.title, 'run #11'); + + final step = searchRowView(stepHit({'target': '#success'}), ''); + expect(step.title, 'run #11 · builder visit 2'); + expect(step.secondary, 'success · → #success'); + + final artifact = searchRowView(artifactHit(), 'notes'); + expect(artifact.title, 'notes.md'); + expect(artifact.secondary, 'run #11 · step 4 · text/markdown · 2.0 KiB'); + }); + + test('a field snippet marks the first case-insensitive query occurrence', () { + final row = searchRowView(fieldHit(), 'RELEASE'); + expect(row.snippet, 'the release is ready'); + expect(row.snippetSpans.map((span) => (span.text, span.matched)), [ + ('the ', false), + ('release', true), + (' is ready', false), + ]); + expect(row.snippetSpans.where((span) => span.matched), hasLength(1)); + + final absent = searchRowView(fieldHit({'snippet': 'no match'}), 'absent'); + expect(absent.snippetSpans.single.matched, isFalse); + expect(absent.snippetSpans.single.text, 'no match'); + + final blank = searchRowView(fieldHit({'snippet': ''}), 'release'); + expect(blank.snippetSpans, isEmpty); + }); + + test('unknown or targetless hits are read-only and never open a guess', () { + final unknown = searchRowView({ + 'kind': 'future_kind', + 'target': 'widget:7', + }, 'x'); + expect(unknown.title, 'widget:7'); + expect(unknown.secondary, 'kind "future_kind" · read-only'); + expect(unknown.openable, isFalse); + expect(unknown.target, isNull); + expect(unknown.kindLabel, 'Unrecognised result'); + + final targetless = searchRowView({ + 'kind': 'run', + 'run': {'id': 11}, + }, 'x'); + expect(targetless.openable, isFalse); + expect(targetless.target, isNull); + + expect(searchRowView(pipelineHit(), '').openable, isTrue); + expect(searchRowView(versionHit(), '').openable, isTrue); + expect(searchRowView(artifactHit(), '').openable, isTrue); + }); + + test('byte sizes use the shared binary rendering', () { + expect(humanBytes(0), '0 B'); + expect(humanBytes(1023), '1023 B'); + expect(humanBytes(1024), '1.0 KiB'); + expect(humanBytes(2048), '2.0 KiB'); + expect(humanBytes(1048576), '1.0 MiB'); + }); +} diff --git a/app/test/features/search/search_screen_states_test.dart b/app/test/features/search/search_screen_states_test.dart new file mode 100644 index 00000000..71292861 --- /dev/null +++ b/app/test/features/search/search_screen_states_test.dart @@ -0,0 +1,146 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/search/search_screen.dart'; + +class RecordingGateway implements ApiGateway { + RecordingGateway(this.reply); + + final JsonMap Function(String query, String kind) reply; + final calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add(Map.of(fields)); + final search = Map.from(fields['search'] as Map); + return reply(search['query'] as String, search['kind'] as String); + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap response( + List results, { + bool truncated = false, + int scannedSteps = 2, + int scannedBytes = 128, +}) => { + 'search_results': { + 'results': results, + 'truncated': truncated, + 'scanned_steps': scannedSteps, + 'scanned_bytes': scannedBytes, + 'cap': 50, + 'scan_bound_bytes': 1 << 20, + }, +}; + +final pipeline = { + 'kind': 'pipeline', + 'target': 'pipeline:7', + 'pipeline': {'id': 7, 'name': 'Release planner', 'version': 3, 'stages': 4}, +}; + +Widget material(Widget child) => MaterialApp(home: child); + +void main() { + testWidgets( + 'a fresh screen sends no request and idle is not an empty result', + (tester) async { + final gateway = RecordingGateway((_, _) => response([pipeline])); + await tester.pumpWidget( + material(SearchScreen(gateway: gateway, onOpen: (_) {})), + ); + + expect(gateway.calls, isEmpty); + expect( + find.text('Search pipelines, runs and artifacts.'), + findsOneWidget, + ); + expect(find.textContaining('No matches'), findsNothing); + }, + ); + + testWidgets('an empty server result shows the query-specific empty copy', ( + tester, + ) async { + final gateway = RecordingGateway((_, _) => response(const [])); + await tester.pumpWidget( + material(SearchScreen(gateway: gateway, onOpen: (_) {})), + ); + + await tester.enterText(find.byKey(const ValueKey('search.field')), 'zzz'); + await tester.pump(const Duration(milliseconds: 300)); + await tester.pumpAndSettle(); + + expect(gateway.calls, hasLength(1)); + expect(find.text('No matches for "zzz".'), findsOneWidget); + expect(find.text('Searching…'), findsNothing); + }); + + testWidgets( + 'a truncated empty reply keeps the server scan warning on screen', + (tester) async { + final gateway = RecordingGateway( + (_, _) => response( + const [], + truncated: true, + scannedSteps: 2000, + scannedBytes: 1048576, + ), + ); + await tester.pumpWidget( + material(SearchScreen(gateway: gateway, onOpen: (_) {})), + ); + + await tester.enterText( + find.byKey(const ValueKey('search.field')), + 'needle', + ); + await tester.pump(const Duration(milliseconds: 300)); + await tester.pumpAndSettle(); + + expect( + find.text('No matches for "needle" within the server\'s scan limit.'), + findsOneWidget, + ); + expect(find.textContaining('Results truncated'), findsOneWidget); + expect(find.textContaining('scanned 2000 steps'), findsOneWidget); + expect(find.textContaining('scan limit 1.0 MiB'), findsOneWidget); + }, + ); + + testWidgets('changing Kind clears a typed token and requests the new kind', ( + tester, + ) async { + tester.view.physicalSize = const Size(390, 844); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final gateway = RecordingGateway((_, _) => response([pipeline])); + await tester.pumpWidget( + material(SearchScreen(gateway: gateway, onOpen: (_) {})), + ); + + await tester.enterText( + find.byKey(const ValueKey('search.field')), + 'plan t:run', + ); + await tester.pump(const Duration(milliseconds: 300)); + await tester.pumpAndSettle(); + expect((gateway.calls.single['search'] as Map)['kind'], 'run'); + + await tester.tap(find.byKey(const ValueKey('search.kind'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Pipelines').last); + await tester.pumpAndSettle(); + + final field = tester.widget( + find.byKey(const ValueKey('search.field')), + ); + expect(field.controller!.text.trim(), 'plan'); + expect(field.controller!.text, isNot(contains('t:run'))); + expect((gateway.calls.last['search'] as Map)['kind'], 'pipeline'); + }); +} diff --git a/app/test/features/search/search_screen_test.dart b/app/test/features/search/search_screen_test.dart new file mode 100644 index 00000000..7c1b7eeb --- /dev/null +++ b/app/test/features/search/search_screen_test.dart @@ -0,0 +1,223 @@ +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/features/search/domain/search_models.dart'; +import 'package:pipelines_app/features/search/search_screen.dart'; + +class ImmediateGateway implements ApiGateway { + ImmediateGateway(this.reply); + + final JsonMap Function(String query, String kind) reply; + final calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add(Map.of(fields)); + final search = Map.from(fields['search'] as Map); + return reply(search['query'] as String, search['kind'] as String); + } + + @override + Stream get frames => const Stream.empty(); +} + +class FailingThenSucceedingGateway implements ApiGateway { + FailingThenSucceedingGateway(this.success); + + final JsonMap success; + var calls = 0; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls++; + if (calls == 1) throw StateError('unknown command: search'); + return success; + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap hit({ + required String kind, + required String target, + required Map payload, +}) => {'kind': kind, 'target': target, ...payload}; + +JsonMap response(List results) => { + 'search_results': { + 'results': results, + 'truncated': false, + 'scanned_steps': 4, + 'scanned_bytes': 512, + 'cap': 50, + 'scan_bound_bytes': 1 << 20, + }, +}; + +final pipeline = hit( + kind: 'pipeline', + target: 'pipeline:7', + payload: { + 'pipeline': {'id': 7, 'name': 'Release planner', 'version': 3, 'stages': 4}, + }, +); +final field = hit( + kind: 'field', + target: 'run:11:4:output', + payload: { + 'matched_field': 'output', + 'field': { + 'run_id': 11, + 'sequence': 4, + 'field': 'output', + 'snippet': 'the release is ready', + }, + }, +); + +void useNarrowSurface(WidgetTester tester) { + tester.view.physicalSize = const Size(390, 844); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); +} + +Widget largeText(Widget child) => MediaQuery( + data: const MediaQueryData(textScaler: TextScaler.linear(2)), + child: child, +); + +Future search(WidgetTester tester, String query) async { + await tester.enterText(find.byKey(const ValueKey('search.field')), query); + await tester.pump(const Duration(milliseconds: 300)); + await tester.pumpAndSettle(); +} + +void main() { + for (final width in [390.0, 1000.0]) { + testWidgets( + 'Material search is native and usable at width $width and 2x text', + (tester) async { + useNarrowSurface(tester); + tester.view.physicalSize = Size(width, 844); + final gateway = ImmediateGateway((_, _) => response([pipeline, field])); + JsonMap? opened; + await tester.pumpWidget( + MaterialApp( + home: largeText( + SearchScreen( + gateway: gateway, + onOpen: (value) => opened = value, + cupertino: false, + ), + ), + ), + ); + + expect(find.byType(SearchBar), findsOneWidget); + expect(find.byType(DropdownButton), findsOneWidget); + expect(find.text('All kinds'), findsOneWidget); + expect(gateway.calls, isEmpty); + + await search(tester, 'release'); + + expect(gateway.calls.single, { + 'search': {'query': 'release', 'kind': '', 'limit': 0}, + }); + expect(find.text('Release planner'), findsOneWidget); + expect(find.textContaining('the release is ready'), findsOneWidget); + expect(find.textContaining('4 results'), findsNothing); + expect(tester.takeException(), isNull); + + await tester.tap( + find.byKey(const ValueKey('search.result.pipeline:7')), + ); + expect(opened?['target'], 'pipeline:7'); + expect(opened?['kind'], 'pipeline'); + }, + ); + } + + testWidgets( + 'Cupertino search uses native controls and opens the real target', + (tester) async { + useNarrowSurface(tester); + final gateway = ImmediateGateway((_, _) => response([pipeline])); + JsonMap? opened; + await tester.pumpWidget( + CupertinoApp( + home: largeText( + SearchScreen( + gateway: gateway, + onOpen: (value) => opened = value, + cupertino: true, + ), + ), + ), + ); + + expect(find.byType(CupertinoSearchTextField), findsOneWidget); + await search(tester, 'release'); + + expect(find.text('Release planner'), findsOneWidget); + expect(tester.takeException(), isNull); + await tester.tap(find.byKey(const ValueKey('search.result.pipeline:7'))); + expect(opened?['target'], 'pipeline:7'); + }, + ); + + testWidgets('a read-only hit cannot be opened', (tester) async { + useNarrowSurface(tester); + final unknown = hit( + kind: 'future_kind', + target: 'widget:7', + payload: const {}, + ); + final gateway = ImmediateGateway((_, _) => response([unknown])); + JsonMap? opened; + await tester.pumpWidget( + MaterialApp( + home: SearchScreen( + gateway: gateway, + onOpen: (value) => opened = value, + cupertino: false, + ), + ), + ); + await search(tester, 'widget'); + + expect(find.textContaining('read-only'), findsOneWidget); + await tester.tap(find.byKey(const ValueKey('search.result.widget:7'))); + expect(opened, isNull); + }); + + testWidgets('an unsupported server shows its sentence and retry recovers', ( + tester, + ) async { + useNarrowSurface(tester); + final gateway = FailingThenSucceedingGateway(response([pipeline])); + await tester.pumpWidget( + MaterialApp( + home: SearchScreen(gateway: gateway, onOpen: (_) {}, cupertino: false), + ), + ); + await search(tester, 'release'); + + expect( + find.text( + 'This server does not support search. Update the Pipelines server, then try again.', + ), + findsOneWidget, + ); + expect(find.byKey(const ValueKey('search.retry')), findsOneWidget); + + await tester.tap(find.byKey(const ValueKey('search.retry'))); + await tester.pumpAndSettle(); + + expect(gateway.calls, 2); + expect(find.text('Release planner'), findsOneWidget); + expect(find.byKey(const ValueKey('search.retry')), findsNothing); + }); +} diff --git a/app/test/features/search/search_test_support.dart b/app/test/features/search/search_test_support.dart new file mode 100644 index 00000000..fdad7425 --- /dev/null +++ b/app/test/features/search/search_test_support.dart @@ -0,0 +1,50 @@ +import 'dart:async'; + +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/search/data/search_repository.dart'; +import 'package:pipelines_app/features/search/domain/search_controller.dart'; + +class QueuedGateway implements ApiGateway { + final calls = []; + final pending = >[]; + + @override + Future call(String type, [JsonMap fields = const {}]) { + calls.add(Map.of(fields)); + final completer = Completer(); + pending.add(completer); + return completer.future; + } + + @override + Stream get frames => const Stream.empty(); + + void succeed(int index, JsonMap reply) => pending[index].complete(reply); + void fail(int index, Object error) => pending[index].completeError(error); + + JsonMap get lastSearch => + Map.from((calls.last['search'] as Map)); +} + +JsonMap envelope( + List results, { + bool truncated = false, + int scannedSteps = 0, + int scannedBytes = 0, + int cap = 50, + int scanBoundBytes = 1 << 20, +}) => { + 'search_results': { + 'results': results, + 'truncated': truncated, + 'scanned_steps': scannedSteps, + 'scanned_bytes': scannedBytes, + 'cap': cap, + 'scan_bound_bytes': scanBoundBytes, + }, +}; + +OmniSearchController controllerFor(ApiGateway gateway) => OmniSearchController( + repository: SearchRepository(gateway), + debounce: Duration.zero, +); diff --git a/app/tool/search_fixture/main.dart b/app/tool/search_fixture/main.dart new file mode 100644 index 00000000..1328cd07 --- /dev/null +++ b/app/tool/search_fixture/main.dart @@ -0,0 +1,190 @@ +// Web-only fixture entrypoint for rendered search evidence. It is not part of +// the application's `main.dart`; build it explicitly with: +// flutter build web -t tool/search_fixture/main.dart +// `?cupertino=1` renders the same screen inside a CupertinoApp. +import 'dart:convert'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/search/search_screen.dart'; + +void main() { + final cupertino = Uri.base.queryParameters['cupertino'] == '1'; + runApp( + cupertino + ? const CupertinoApp( + title: 'Search fixture', + home: _FixtureHost(cupertino: true), + ) + : const MaterialApp( + title: 'Search fixture', + home: _FixtureHost(cupertino: false), + ), + ); +} + +class _FixtureHost extends StatelessWidget { + const _FixtureHost({required this.cupertino}); + + final bool cupertino; + + @override + Widget build(BuildContext context) => SearchScreen( + gateway: const _FixtureGateway(), + cupertino: cupertino, + onOpen: (hit) { + final route = cupertino + ? CupertinoPageRoute( + builder: (_) => _Opened(hit: hit, cupertino: true), + ) + : MaterialPageRoute( + builder: (_) => _Opened(hit: hit, cupertino: false), + ); + Navigator.of(context).push(route); + }, + ); +} + +class _Opened extends StatelessWidget { + const _Opened({required this.hit, required this.cupertino}); + + final JsonMap hit; + final bool cupertino; + + @override + Widget build(BuildContext context) { + final body = Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Text( + 'Opened ${hit['kind']} target: ${hit['target']}', + textAlign: TextAlign.center, + ), + ), + ); + if (cupertino) { + return CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar(middle: Text('Opened')), + child: body, + ); + } + return Scaffold( + appBar: AppBar(title: const Text('Opened')), + body: body, + ); + } +} + +class _FixtureGateway implements ApiGateway { + const _FixtureGateway(); + + @override + Future call(String type, [JsonMap fields = const {}]) async { + if (type != 'search') throw StateError('unexpected request: $type'); + final request = Map.from(fields['search'] as Map); + final query = '${request['query'] ?? ''}'.trim().toLowerCase(); + final kind = '${request['kind'] ?? ''}'; + await Future.delayed(const Duration(milliseconds: 180)); + var hits = _fixtureHits + .where((hit) { + if (kind.isNotEmpty && hit['kind'] != kind) return false; + if (query.isEmpty) return true; + return jsonEncode(hit).toLowerCase().contains(query); + }) + .toList(growable: false); + return { + 'search_results': { + 'query': request['query'], + 'kind': kind, + 'results': hits, + 'truncated': true, + 'scanned_steps': 2000, + 'scanned_bytes': 1048576, + 'cap': 50, + 'scan_bound_bytes': 1048576, + }, + }; + } + + @override + Stream get frames => const Stream.empty(); +} + +const _fixtureHits = [ + { + 'kind': 'pipeline', + 'target': 'pipeline:24', + 'score': 3, + 'recency': '2026-10-20T09:18:00Z', + 'pipeline': {'id': 24, 'name': 'Plan and land', 'version': 5, 'stages': 4}, + }, + { + 'kind': 'run', + 'target': 'run:457', + 'score': 2, + 'recency': '2026-10-20T08:42:00Z', + 'run': { + 'id': 457, + 'pipeline_name': 'Plan and land', + 'status': 'succeeded', + 'workspace': '/Users/alan/repos/pipelines', + 'created_at': '2026-10-20T08:12:00Z', + 'finished_at': '2026-10-20T08:42:00Z', + }, + }, + { + 'kind': 'field', + 'target': 'run:457:3:input', + 'score': 1, + 'matched_field': 'input', + 'recency': '2026-10-20T08:20:00Z', + 'field': { + 'run_id': 457, + 'sequence': 3, + 'field': 'input', + 'snippet': 'Plan the change before implementing it', + }, + }, + { + 'kind': 'artifact', + 'target': '/artifacts/457/2/plan.md', + 'score': 1, + 'recency': '2026-10-20T08:24:00Z', + 'artifact': { + 'run_id': 457, + 'sequence': 2, + 'name': 'plan.md', + 'content_type': 'text/markdown', + 'size_bytes': 2048, + 'url': '/artifacts/457/2/plan.md', + }, + }, + { + 'kind': 'version', + 'target': 'pipeline:22:v6', + 'score': 2, + 'recency': '2026-10-18T16:05:00Z', + 'version': { + 'pipeline_id': 22, + 'version': 6, + 'content_hash': '9f2c1ad', + 'created_at': '2026-10-18T16:05:00Z', + }, + }, + { + 'kind': 'step', + 'target': 'run:457:1', + 'score': 1, + 'recency': '2026-10-20T08:14:00Z', + 'step': { + 'run_id': 457, + 'sequence': 1, + 'stage': 'planner', + 'visit': 1, + 'outcome': 'success', + 'target': '#success', + 'diagnostic': 'plan accepted', + }, + }, +]; diff --git a/app/tool/search_probe.mjs b/app/tool/search_probe.mjs new file mode 100644 index 00000000..172efb1f --- /dev/null +++ b/app/tool/search_probe.mjs @@ -0,0 +1,246 @@ +// Real Chrome evidence for the Flutter search screen. Serves the fixture build +// from build/web on an OS-assigned loopback port and drives the page through +// Chrome DevTools Protocol, like tool/shell_probe.mjs. Usage: +// flutter build web -t tool/search_fixture/main.dart +// OPENCODE_ARTIFACT_DIR= node tool/search_probe.mjs +import { createServer } from 'node:http'; +import { readFile, mkdtemp, 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'; + +const root = join(process.cwd(), 'build/web'); +const artifactDir = process.env.OPENCODE_ARTIFACT_DIR; +if (!artifactDir) throw new Error('OPENCODE_ARTIFACT_DIR is required for captures'); +const mime = { + '.html': 'text/html', + '.js': 'text/javascript', + '.json': 'application/json', + '.wasm': 'application/wasm', + '.png': 'image/png', + '.ico': 'image/x-icon', + '.ttf': 'font/ttf', + '.otf': 'font/otf', +}; +const server = createServer(async (req, res) => { + try { + const path = resolve( + root, + '.' + decodeURIComponent(new URL(req.url, 'http://localhost').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', + }) + .end(file); + } catch { + res.writeHead(404).end('not found'); + } +}); +server.listen(0, '127.0.0.1'); +await once(server, 'listening'); +const port = server.address().port; +const profile = await mkdtemp(join(tmpdir(), 'x1-search-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; +}); +const waitFor = async (fn) => { + for (let i = 0; i < 100; i++) { + const value = await fn(); + if (value) return value; + await delay(100); + } + throw new Error('Timed out waiting for Chrome DevTools'); +}; +const result = { captures: [], evidence: {} }; +let ws; +try { + const endpoint = await waitFor(() => + stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1], + ); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + ws.addEventListener('message', (event) => { + const msg = JSON.parse(event.data); + if (msg.id && pending.has(msg.id)) { + pending.get(msg.id)(msg); + pending.delete(msg.id); + } + }); + const send = (method, params = {}, sessionId) => + new Promise((resolve) => { + const callId = ++id; + pending.set(callId, resolve); + 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); + 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)}`); + } + return response.result?.result?.value; + }; + const clickMatching = (needle) => + evaluate(`(() => { + const needle = ${JSON.stringify(needle)}; + const nodes = [...document.querySelectorAll('flt-semantics')]; + const e = nodes.find(x => x.hasAttribute('flt-tappable') && + (x.getAttribute('aria-label') || x.innerText || '').includes(needle)); + if (!e) return false; + e.click(); + return true; + })()`); + const capture = async (name, width, height) => { + await send( + 'Emulation.setDeviceMetricsOverride', + { width, height, deviceScaleFactor: 1, mobile: width < 600 }, + session, + ); + await delay(350); + const data = ( + await send( + 'Page.captureScreenshot', + { format: 'png', captureBeyondViewport: false }, + session, + ) + ).result.data; + const path = join(artifactDir, `${name}.png`); + await writeFile(path, Buffer.from(data, 'base64')); + result.captures.push(path); + }; + const load = async (url, width, height) => { + await send( + 'Emulation.setDeviceMetricsOverride', + { width, height, deviceScaleFactor: 1, mobile: width < 600 }, + session, + ); + const navigation = await send('Page.navigate', { url }, session); + if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation)); + await delay(3500); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(900); + }; + const typeText = async (query) => { + const focused = await evaluate(`(() => { + const input = document.querySelector('input[type="search"]') || document.querySelector('input.flt-text-editing'); + if (!input) return false; input.focus(); return true; })()`); + if (!focused) throw new Error('Search input not found'); + await delay(400); + const inserted = await send('Input.insertText', { text: query }, session); + if (inserted.error) throw new Error(JSON.stringify(inserted)); + await delay(1400); + return (await evaluate('document.body.innerText')).trim(); + }; + const typeQuery = async (query) => { + const trimmed = await typeText(query); + if (!trimmed.includes('Plan and land')) { + throw new Error(`Results missing after typing: ${JSON.stringify(trimmed)}`); + } + return { + typed: query, + resultTitles: ['Plan and land', 'run #457 · Plan and land', 'run #457 · step 3 · input', + 'plan.md', 'run #457 · planner visit 1'].filter((title) => trimmed.includes(title)), + showsServerSnippet: trimmed.includes('Plan the change before implementing it'), + showsRecency: /\d{1,2} [A-Z][a-z]{2} \d{2}:\d{2}/.test(trimmed), + showsBounds: + trimmed.includes('Results truncated') && + trimmed.includes('cap 50') && + trimmed.includes('scanned 2000 steps'), + }; + }; + const typeTruncatedEmpty = async (query) => { + const text = await typeText(query); + const emptyCopy = `No matches for "${query}" within the server's scan limit.`; + const missing = [ + emptyCopy, 'Results truncated', '0 results', + 'scanned 2000 steps', 'scan limit 1.0 MiB', + ].filter((needle) => !text.includes(needle)); + if (missing.length) throw new Error(`Truncated empty missing ${JSON.stringify(missing)}`); + return { typed: query, emptyCopy, showsTruncationWarning: true, showsBounds: true }; + }; + + const base = `http://127.0.0.1:${port}/`; + await load(base, 390, 844); + result.evidence.materialPhone = await typeQuery('plan'); + await capture('x1-search-material-phone', 390, 844); + if (!(await clickMatching('Plan and land'))) { + throw new Error('Could not open the pipeline row'); + } + await delay(700); + const opened = await evaluate('document.body.innerText'); + if (!opened.includes('pipeline:24')) { + throw new Error(`Opened target missing: ${JSON.stringify(opened)}`); + } + result.evidence.opened = 'pipeline:24'; + await capture('x1-search-open-target', 390, 844); + + await load(base, 1280, 800); + result.evidence.materialDesktop = await typeQuery('plan'); + await capture('x1-search-material-desktop', 1280, 800); + + await load(`${base}?cupertino=1`, 390, 844); + result.evidence.cupertinoPhone = await typeQuery('plan'); + await capture('x1-search-cupertino-phone', 390, 844); + + await load(base, 390, 844); + result.evidence.materialTruncatedEmpty = await typeTruncatedEmpty('needle'); + await capture('x1-search-truncated-empty', 390, 844); + + await load(`${base}?cupertino=1`, 390, 844); + result.evidence.cupertinoTruncatedEmpty = + await typeTruncatedEmpty('needle'); + await capture('x1-search-truncated-empty-cupertino', 390, 844); + + console.log(JSON.stringify(result, 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 }); +} From b381290f349a1d7085ad2b38b0b8f51a061208c1 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 16:51:38 +0100 Subject: [PATCH 59/84] feat(app): add deterministic orthogonal graph edge routing Pure-Dart P2c slice: interval-aware ports and corridors, label-aware lane spacing, measured label placement with fallback shelf, skipped diagnostics and routing bounds. 20 focused tests plus existing suite and web build pass. --- .../features/graph/routing/corridor_plan.dart | 105 +++++++ .../graph/routing/edge_label_placement.dart | 175 ++++++++++++ .../graph/routing/edge_route_planner.dart | 265 ++++++++++++++++++ .../graph/routing/graph_edge_routing.dart | 135 +++++++++ .../graph/routing/route_geometry.dart | 175 ++++++++++++ .../features/graph/routing/route_models.dart | 261 +++++++++++++++++ .../graph/routing/routing_inputs.dart | 64 +++++ app/notes/P2c.md | 116 ++++++++ .../routing/graph_edge_routing_test.dart | 191 +++++++++++++ .../routing/graph_routing_geometry_test.dart | 161 +++++++++++ .../graph_routing_validation_test.dart | 222 +++++++++++++++ .../graph/routing/routing_assertions.dart | 215 ++++++++++++++ .../graph/routing/routing_fixtures.dart | 143 ++++++++++ 13 files changed, 2228 insertions(+) create mode 100644 app/lib/features/graph/routing/corridor_plan.dart create mode 100644 app/lib/features/graph/routing/edge_label_placement.dart create mode 100644 app/lib/features/graph/routing/edge_route_planner.dart create mode 100644 app/lib/features/graph/routing/graph_edge_routing.dart create mode 100644 app/lib/features/graph/routing/route_geometry.dart create mode 100644 app/lib/features/graph/routing/route_models.dart create mode 100644 app/lib/features/graph/routing/routing_inputs.dart create mode 100644 app/notes/P2c.md create mode 100644 app/test/features/graph/routing/graph_edge_routing_test.dart create mode 100644 app/test/features/graph/routing/graph_routing_geometry_test.dart create mode 100644 app/test/features/graph/routing/graph_routing_validation_test.dart create mode 100644 app/test/features/graph/routing/routing_assertions.dart create mode 100644 app/test/features/graph/routing/routing_fixtures.dart diff --git a/app/lib/features/graph/routing/corridor_plan.dart b/app/lib/features/graph/routing/corridor_plan.dart new file mode 100644 index 00000000..33909013 --- /dev/null +++ b/app/lib/features/graph/routing/corridor_plan.dart @@ -0,0 +1,105 @@ +import 'dart:math' as math; + +import '../layout/layout_models.dart'; +import 'route_geometry.dart'; +import 'route_models.dart'; + +/// One vertical-corridor request from a wrapping route. +/// +/// A route needs a track right of its source and a track beside its target; +/// both gaps are 0-based column gaps (`rankCount` is the right free gap). +class CorridorRequest { + const CorridorRequest({ + required this.edgeId, + required this.sourceGap, + required this.targetGap, + }); + + final int edgeId; + final int sourceGap; + final int targetGap; +} + +/// Assigned x coordinates for every wrapping route's two vertical tracks. +class CorridorPlan { + CorridorPlan({ + required Map sourceX, + required Map targetX, + }) : sourceX = Map.unmodifiable(sourceX), + targetX = Map.unmodifiable(targetX); + + final Map sourceX; + final Map targetX; +} + +/// Spreads corridor requests across the free band of each column gap. +/// +/// Requests keep edge-id order, so equal input yields equal coordinates. Tracks +/// are distinct inside a gap; a narrow gap compresses the spacing instead of +/// pushing a corridor into a node column. +CorridorPlan planCorridors({ + required GraphLayout layout, + required List requests, + required RoutingConfig config, +}) { + final ordered = [...requests] + ..sort((a, b) => a.edgeId.compareTo(b.edgeId)); + final slots = >{}; + for (final request in ordered) { + slots + .putIfAbsent(request.sourceGap, () => <_Slot>[]) + .add(_Slot(request.edgeId, source: true)); + slots + .putIfAbsent(request.targetGap, () => <_Slot>[]) + .add(_Slot(request.edgeId, source: false)); + } + + final gaps = ColumnGaps( + nodes: layout.nodes, + rankCount: layout.rankCount, + layoutWidth: layout.width, + ); + final sourceX = {}; + final targetX = {}; + final gapKeys = slots.keys.toList()..sort(); + for (final gapKey in gapKeys) { + final gapSlots = slots[gapKey]!; + final band = gaps.band(gapKey, config.nodeClearance); + final positions = _trackPositions( + band, + gapSlots.length, + config.corridorSpacing, + ); + for (var index = 0; index < gapSlots.length; index += 1) { + if (gapSlots[index].source) { + sourceX[gapSlots[index].edgeId] = positions[index]; + } else { + targetX[gapSlots[index].edgeId] = positions[index]; + } + } + } + return CorridorPlan(sourceX: sourceX, targetX: targetX); +} + +List _trackPositions(GapBand band, int count, double spacing) { + if (count == 0) return const []; + if (band.open) { + return [ + for (var index = 0; index < count; index += 1) band.lo + spacing * index, + ]; + } + final width = band.hi - band.lo; + if (count == 1) return [(band.lo + band.hi) / 2]; + if (width <= 0) return List.filled(count, band.lo); + final step = math.min(spacing, width / (count - 1)); + return [ + for (var index = 0; index < count; index += 1) band.lo + step * index, + ]; +} + +class _Slot { + const _Slot(this.edgeId, {required this.source}); + + final int edgeId; + final bool source; +} diff --git a/app/lib/features/graph/routing/edge_label_placement.dart b/app/lib/features/graph/routing/edge_label_placement.dart new file mode 100644 index 00000000..75264135 --- /dev/null +++ b/app/lib/features/graph/routing/edge_label_placement.dart @@ -0,0 +1,175 @@ +import 'dart:math' as math; + +import '../layout/layout_models.dart'; +import 'route_geometry.dart'; +import 'route_models.dart'; + +/// Places one measured edge label without overlapping a node or another label. +/// +/// Candidates are tried in a deterministic order: the midpoint of each +/// horizontal run (above, then below), then each vertical run (right, then +/// left), sliding along the run before giving up. A run too narrow for the +/// box pushes the label to a free shelf below the drawing, which expands the +/// routing bounds instead of covering a node. +EdgeLabelBox placeEdgeLabel({ + required EdgeRoute route, + required LabelExtent extent, + required List nodes, + required List placed, + required RoutingConfig config, + required double floorY, +}) { + final width = extent.width; + final height = extent.height; + for (final candidate in _candidates(route, width, height, config.labelGap)) { + final box = EdgeLabelBox( + edgeId: route.id, + x: candidate.x, + y: candidate.y, + width: width, + height: height, + ); + if (_fits(box, nodes, placed, config)) return box; + } + + // The fallback shelf is below every route and every existing label, so it + // cannot cover a node. Growing it down expands the returned bounds. + var top = math.max( + floorY, + placed.fold(0, (bottom, box) => math.max(bottom, box.bottom)), + ); + top += config.labelGap; + final centre = _routeCentreX(route); + final step = math.max(height + config.labelGap, 1.0); + for (var attempt = 0; attempt < 100000; attempt += 1) { + final x = math.max(0.0, centre - width / 2); + final box = EdgeLabelBox( + edgeId: route.id, + x: x, + y: top, + width: width, + height: height, + ); + if (_fits(box, nodes, placed, config)) return box; + top += step; + } + // A zero-sized label cannot collide; this is unreachable for real extents. + return EdgeLabelBox( + edgeId: route.id, + x: math.max(0.0, centre - width / 2), + y: top, + width: width, + height: height, + ); +} + +bool _fits( + EdgeLabelBox box, + List nodes, + List placed, + RoutingConfig config, +) { + if (box.x < 0 || box.y < 0) return false; + for (final node in nodes) { + if (boxIntersectsNode( + x: box.x, + y: box.y, + width: box.width, + height: box.height, + node: node, + gap: config.labelGap, + )) { + return false; + } + } + for (final other in placed) { + if (boxesOverlap( + ax: box.x, + ay: box.y, + aw: box.width, + ah: box.height, + bx: other.x, + by: other.y, + bw: other.width, + bh: other.height, + gap: config.labelGap, + )) { + return false; + } + } + return true; +} + +List<_LabelCandidate> _candidates( + EdgeRoute route, + double width, + double height, + double gap, +) { + const fractions = [0.5, 0.35, 0.65, 0.2, 0.8, 0.08, 0.92]; + final horizontals = <_Run>[]; + final verticals = <_Run>[]; + for (var index = 1; index < route.points.length; index += 1) { + final a = route.points[index - 1]; + final b = route.points[index]; + if (a.y == b.y) { + horizontals.add(_Run(a, b, (b.x - a.x).abs(), index)); + } else if (a.x == b.x) { + verticals.add(_Run(a, b, (b.y - a.y).abs(), index)); + } + } + horizontals.sort((a, b) { + final length = b.length.compareTo(a.length); + return length != 0 ? length : a.order.compareTo(b.order); + }); + verticals.sort((a, b) { + final length = b.length.compareTo(a.length); + return length != 0 ? length : a.order.compareTo(b.order); + }); + + final candidates = <_LabelCandidate>[]; + for (final run in horizontals) { + for (final fraction in fractions) { + final x = run.a.x + (run.b.x - run.a.x) * fraction; + final left = x - width / 2; + candidates.add(_LabelCandidate(left, run.a.y - gap - height)); + candidates.add(_LabelCandidate(left, run.a.y + gap)); + } + } + for (final run in verticals) { + for (final fraction in fractions) { + final y = run.a.y + (run.b.y - run.a.y) * fraction; + final top = y - height / 2; + candidates.add(_LabelCandidate(run.a.x + gap, top)); + candidates.add(_LabelCandidate(run.a.x - gap - width, top)); + } + } + return candidates; +} + +double _routeCentreX(EdgeRoute route) { + if (route.points.isEmpty) return 0; + var lo = route.points.first.x; + var hi = lo; + for (final point in route.points) { + lo = math.min(lo, point.x); + hi = math.max(hi, point.x); + } + return (lo + hi) / 2; +} + +class _Run { + const _Run(this.a, this.b, this.length, this.order); + + final RoutePoint a; + final RoutePoint b; + final double length; + final int order; +} + +class _LabelCandidate { + const _LabelCandidate(this.x, this.y); + + final double x; + final double y; +} diff --git a/app/lib/features/graph/routing/edge_route_planner.dart b/app/lib/features/graph/routing/edge_route_planner.dart new file mode 100644 index 00000000..8b3d6ff4 --- /dev/null +++ b/app/lib/features/graph/routing/edge_route_planner.dart @@ -0,0 +1,265 @@ +import 'dart:math' as math; + +import '../domain/graph_definition.dart'; +import '../layout/layout_models.dart'; +import 'corridor_plan.dart'; +import 'route_geometry.dart'; +import 'route_models.dart'; + +/// One routed edge before labels and bounds are assembled. +/// +/// Internal to the routing library: callers receive the immutable public +/// [EdgeRoute] instead. +class PlannedEdgeRoute { + PlannedEdgeRoute({ + required this.edge, + required this.kind, + required this.straight, + required this.sourcePort, + required this.targetPort, + required List points, + }) : points = List.unmodifiable(points); + + final GraphEdge edge; + final RouteKind kind; + final bool straight; + final RoutePort sourcePort; + final RoutePort targetPort; + final List points; + + EdgeRoute toRoute() => EdgeRoute( + id: edge.id, + source: edge.source, + outcome: edge.outcome, + target: edge.target, + label: edge.label, + fallback: edge.fallback, + kind: kind, + straight: straight, + sourcePort: sourcePort, + targetPort: targetPort, + points: points, + ); +} + +/// Plans orthogonal polylines for every edge whose endpoints have placed boxes. +/// +/// [edges] must already be filtered to known endpoints and sorted by id. The +/// plan is deterministic: forward one-rank routes take a straight horizontal +/// run when the measured boxes and labels leave room, and every other route +/// gets a unique lane below the node grid plus vertical corridors inside the +/// column gaps. Corridors and lanes never enter a node column. +/// +/// All horizontal stubs share one [AxisTrackAllocator], so two different edges +/// cannot occupy the same run in a column gap even when they touch different +/// nodes on the same row. +List planEdgeRoutes({ + required GraphLayout layout, + required List edges, + required double maxLabelHeight, + required RoutingConfig config, +}) { + if (edges.isEmpty) return const []; + final nodes = { + for (final node in layout.nodes) node.key: node, + }; + final kinds = {}; + for (final edge in edges) { + final source = nodes[edge.source]!; + final target = nodes[edge.target]!; + kinds[edge.id] = _kindFor(edge, source, target, layout); + } + + final trackSpacing = math.max( + config.portSpacing, + maxLabelHeight + config.labelGap, + ); + final runs = AxisTrackAllocator(trackSpacing); + final straightY = {}; + for (final edge in edges) { + if (kinds[edge.id] != RouteKind.forward) continue; + final source = nodes[edge.source]!; + final target = nodes[edge.target]!; + if (target.rank != source.rank + 1) continue; + if (target.x <= source.right) continue; + final sourceInset = portInset(source, config.portSpacing); + final targetInset = portInset(target, config.portSpacing); + final lo = math.max(source.y + sourceInset, target.y + targetInset); + final hi = math.min( + source.bottom - sourceInset, + target.bottom - targetInset, + ); + if (hi <= lo) continue; + final y = runs.allocate( + desired: (lo + hi) / 2, + min: lo, + max: hi, + spanLo: source.right, + spanHi: target.x, + ); + if (y != null) straightY[edge.id] = y; + } + + final laneStep = math.max( + config.laneSpacing, + maxLabelHeight + config.labelGap, + ); + final contentBottom = layout.nodes.fold( + 0, + (bottom, node) => math.max(bottom, node.bottom), + ); + final wrapPlans = <_WrapPlan>[]; + final corridorRequests = []; + var laneIndex = 0; + for (final edge in edges) { + if (straightY.containsKey(edge.id)) continue; + final source = nodes[edge.source]!; + final target = nodes[edge.target]!; + final kind = kinds[edge.id]!; + final laneY = + contentBottom + config.nodeClearance + laneStep * (laneIndex + 1); + laneIndex += 1; + final sourceGap = (source.rank + 1).clamp(0, layout.rankCount); + final targetGap = kind == RouteKind.forward + ? target.rank.clamp(0, layout.rankCount) + : (target.rank + 1).clamp(0, layout.rankCount); + corridorRequests.add( + CorridorRequest( + edgeId: edge.id, + sourceGap: sourceGap, + targetGap: targetGap, + ), + ); + wrapPlans.add(_WrapPlan(edge: edge, kind: kind, laneY: laneY)); + } + + final corridors = planCorridors( + layout: layout, + requests: corridorRequests, + config: config, + ); + final sourceTrackX = corridors.sourceX; + final targetTrackX = corridors.targetX; + + final sourcePorts = {}; + final targetPorts = {}; + for (final edge in edges) { + final y = straightY[edge.id]; + if (y == null) continue; + final source = nodes[edge.source]!; + final target = nodes[edge.target]!; + sourcePorts[edge.id] = RoutePort( + side: RoutePortSide.right, + point: RoutePoint(source.right, y), + ); + targetPorts[edge.id] = RoutePort( + side: RoutePortSide.left, + point: RoutePoint(target.x, y), + ); + } + for (final plan in wrapPlans) { + final edge = plan.edge; + final source = nodes[edge.source]!; + final target = nodes[edge.target]!; + final sourceTrack = sourceTrackX[edge.id]!; + final targetTrack = targetTrackX[edge.id]!; + final sourceInset = portInset(source, config.portSpacing); + final targetInset = portInset(target, config.portSpacing); + final sourceY = runs.allocate( + desired: source.y + source.height / 2, + min: source.y + sourceInset, + max: source.bottom - sourceInset, + spanLo: source.right, + spanHi: sourceTrack, + ); + final targetSide = plan.kind == RouteKind.forward + ? RoutePortSide.left + : RoutePortSide.right; + final targetBorder = targetSide == RoutePortSide.left + ? target.x + : target.right; + final targetY = runs.allocate( + desired: target.y + target.height / 2, + min: target.y + targetInset, + max: target.bottom - targetInset, + spanLo: math.min(targetBorder, targetTrack), + spanHi: math.max(targetBorder, targetTrack), + ); + sourcePorts[edge.id] = RoutePort( + side: RoutePortSide.right, + point: RoutePoint(source.right, sourceY ?? source.y + source.height / 2), + ); + targetPorts[edge.id] = RoutePort( + side: targetSide, + point: RoutePoint(targetBorder, targetY ?? target.y + target.height / 2), + ); + } + + final planned = {}; + for (final edge in edges) { + final value = straightY[edge.id]; + if (value != null) { + planned[edge.id] = PlannedEdgeRoute( + edge: edge, + kind: kinds[edge.id]!, + straight: true, + sourcePort: sourcePorts[edge.id]!, + targetPort: targetPorts[edge.id]!, + points: _collapse([ + sourcePorts[edge.id]!.point, + targetPorts[edge.id]!.point, + ]), + ); + } + } + for (final plan in wrapPlans) { + final sourceTrack = sourceTrackX[plan.edge.id]!; + final targetTrack = targetTrackX[plan.edge.id]!; + planned[plan.edge.id] = PlannedEdgeRoute( + edge: plan.edge, + kind: plan.kind, + straight: false, + sourcePort: sourcePorts[plan.edge.id]!, + targetPort: targetPorts[plan.edge.id]!, + points: _collapse([ + sourcePorts[plan.edge.id]!.point, + RoutePoint(sourceTrack, sourcePorts[plan.edge.id]!.point.y), + RoutePoint(sourceTrack, plan.laneY), + RoutePoint(targetTrack, plan.laneY), + RoutePoint(targetTrack, targetPorts[plan.edge.id]!.point.y), + targetPorts[plan.edge.id]!.point, + ]), + ); + } + return [for (final edge in edges) planned[edge.id]!]; +} + +RouteKind _kindFor( + GraphEdge edge, + GraphNodeBox source, + GraphNodeBox target, + GraphLayout layout, +) { + if (edge.source == edge.target) return RouteKind.selfLoop; + final sourceRank = layout.ranks[edge.source] ?? source.rank; + final targetRank = layout.ranks[edge.target] ?? target.rank; + if (targetRank > sourceRank) return RouteKind.forward; + if (targetRank < sourceRank) return RouteKind.back; + return RouteKind.sameRank; +} + +List _collapse(List points) { + final result = []; + for (final point in points) { + if (result.isEmpty || result.last != point) result.add(point); + } + return result; +} + +class _WrapPlan { + _WrapPlan({required this.edge, required this.kind, required this.laneY}); + + final GraphEdge edge; + final RouteKind kind; + final double laneY; +} diff --git a/app/lib/features/graph/routing/graph_edge_routing.dart b/app/lib/features/graph/routing/graph_edge_routing.dart new file mode 100644 index 00000000..33ad9a9a --- /dev/null +++ b/app/lib/features/graph/routing/graph_edge_routing.dart @@ -0,0 +1,135 @@ +import 'dart:math' as math; + +import '../domain/graph_definition.dart'; +import '../layout/layout_models.dart'; +import 'edge_label_placement.dart'; +import 'edge_route_planner.dart'; +import 'route_models.dart'; + +/// Routes every definition edge that has a placed source and target. +/// +/// The node boxes and ranks come from the landed [GraphLayout]; this function +/// never moves them, invents a node or assumes a node size. Callers supply one +/// measured [LabelExtent] for every routed edge, plus the clearances and lane +/// spacing in [RoutingConfig]. +/// +/// Edges with an unknown, empty or missing endpoint are returned in +/// [GraphRouting.skipped] with their definition identity intact. A routed edge +/// keeps its id, source, outcome, target, label and fallback flag. Results are +/// ordered by definition edge id and are stable for repeated input. +GraphRouting routeGraphEdges({ + required GraphLayout layout, + required List edges, + required Map labelExtents, + required RoutingConfig config, +}) { + final ordered = [...edges]..sort((a, b) => a.id.compareTo(b.id)); + final seenIds = {}; + for (final edge in ordered) { + if (!seenIds.add(edge.id)) { + throw ArgumentError.value(edge.id, 'edges', 'duplicate edge id'); + } + } + + final nodes = { + for (final node in layout.nodes) node.key: node, + }; + final routed = []; + final skipped = []; + for (final edge in ordered) { + if (!nodes.containsKey(edge.source)) { + skipped.add( + RouteDiagnostic( + id: edge.id, + source: edge.source, + outcome: edge.outcome, + target: edge.target, + reason: RouteSkipReason.unknownSource, + message: 'source "${edge.source}" has no placed node', + ), + ); + continue; + } + if (!edge.knownTarget || !nodes.containsKey(edge.target)) { + skipped.add( + RouteDiagnostic( + id: edge.id, + source: edge.source, + outcome: edge.outcome, + target: edge.target, + reason: RouteSkipReason.unknownTarget, + message: edge.target.isEmpty + ? 'edge target is empty' + : 'target "${edge.target}" has no placed node', + ), + ); + continue; + } + routed.add(edge); + } + + final missing = [ + for (final edge in routed) + if (!labelExtents.containsKey(edge.id)) edge.id, + ]; + if (missing.isNotEmpty) { + throw ArgumentError.value( + missing, + 'labelExtents', + 'missing measured label extents for routed edges', + ); + } + + var maxLabelHeight = 0.0; + for (final edge in routed) { + maxLabelHeight = math.max(maxLabelHeight, labelExtents[edge.id]!.height); + } + final planned = planEdgeRoutes( + layout: layout, + edges: routed, + maxLabelHeight: maxLabelHeight, + config: config, + ); + final routes = [for (final plan in planned) plan.toRoute()]; + var floorY = layout.height; + for (final route in routes) { + for (final point in route.points) { + floorY = math.max(floorY, point.y); + } + } + + final labels = []; + for (var index = 0; index < routes.length; index += 1) { + labels.add( + placeEdgeLabel( + route: routes[index], + extent: labelExtents[routes[index].id]!, + nodes: layout.nodes, + placed: labels, + config: config, + floorY: floorY, + ), + ); + } + + var width = layout.width; + var height = layout.height; + for (final route in routes) { + for (final point in route.points) { + width = math.max(width, point.x); + height = math.max(height, point.y); + } + } + for (final label in labels) { + width = math.max(width, label.right); + height = math.max(height, label.bottom); + } + + return GraphRouting( + routes: routes, + labels: labels, + skipped: skipped, + width: width + config.boundsPadding, + height: height + config.boundsPadding, + ); +} diff --git a/app/lib/features/graph/routing/route_geometry.dart b/app/lib/features/graph/routing/route_geometry.dart new file mode 100644 index 00000000..aa89c4df --- /dev/null +++ b/app/lib/features/graph/routing/route_geometry.dart @@ -0,0 +1,175 @@ +import 'dart:math' as math; + +import '../layout/layout_models.dart'; + +/// Geometry helpers for deterministic orthogonal routing. +/// +/// Everything here is plain numbers: no Flutter types, no drawing and no +/// assumed metrics. The helpers are internal to the routing library. + +/// Reserves horizontal or vertical tracks without collinear overlap. +/// +/// A track is a position on [axis] plus the interval it spans on the other +/// axis. Two tracks only conflict when both their positions and their spans +/// overlap, so a long cross lane and a short stub may share a coordinate when +/// their runs do not meet. +class AxisTrackAllocator { + AxisTrackAllocator(this.step); + + final double step; + final List<_Track> _placed = <_Track>[]; + + /// The nearest free position to [desired], or null when none is found. + double? allocate({ + required double desired, + required double min, + required double max, + required double spanLo, + required double spanHi, + }) { + if (max < min) return null; + final start = desired.clamp(min, max); + var spacing = step; + while (spacing > 0.0001) { + for (var attempt = 0; attempt <= 512; attempt += 1) { + final candidates = attempt == 0 + ? [start] + : [start + attempt * spacing, start - attempt * spacing]; + for (final candidate in candidates) { + if (candidate < min || candidate > max) continue; + if (_isFree(candidate, spanLo, spanHi, spacing)) { + _placed.add(_Track(candidate, spanLo, spanHi)); + return candidate; + } + } + } + spacing /= 2; + } + return null; + } + + bool _isFree(double position, double spanLo, double spanHi, double spacing) { + for (final track in _placed) { + if ((track.position - position).abs() >= spacing) continue; + final overlaps = track.lo <= spanHi && spanLo <= track.hi; + if (overlaps) return false; + } + return true; + } +} + +class _Track { + const _Track(this.position, this.lo, this.hi); + + final double position; + final double lo; + final double hi; +} + +/// The x band available for vertical corridors in each column gap. +/// +/// Gap `g` sits before rank `g`; gap `rankCount` is the free space right of the +/// last column. Left/right bounds come from the placed boxes themselves, so a +/// corridor never crosses a column, including heterogeneous node widths. +class ColumnGaps { + ColumnGaps({ + required List nodes, + required this.rankCount, + required this.layoutWidth, + }) : _left = List.filled(rankCount + 1, 0), + _right = List.filled(rankCount + 1, layoutWidth) { + final rankRight = List.filled(rankCount, 0); + final rankLeft = List.filled(rankCount, layoutWidth); + for (final node in nodes) { + if (node.rank < 0 || node.rank >= rankCount) continue; + rankRight[node.rank] = math.max(rankRight[node.rank], node.right); + rankLeft[node.rank] = math.min(rankLeft[node.rank], node.x); + } + var left = 0.0; + for (var rank = 0; rank < rankCount; rank += 1) { + _left[rank] = left; + left = math.max(left, rankRight[rank]); + } + _left[rankCount] = left; + var right = layoutWidth; + _right[rankCount] = right; + for (var rank = rankCount - 1; rank >= 0; rank -= 1) { + right = math.min(right, rankLeft[rank]); + _right[rank] = right; + } + } + + final int rankCount; + final double layoutWidth; + final List _left; + final List _right; + + /// The usable band in gap [index], inset by at most [clearance]. + /// + /// The rightmost gap is open-ended because a loop may expand the canvas; + /// every other gap is bounded by the neighbouring columns. + GapBand band(int index, double clearance) { + final gap = index.clamp(0, rankCount); + final left = _left[gap]; + final right = _right[gap]; + if (gap == rankCount) { + return GapBand(lo: left + clearance, hi: double.infinity, open: true); + } + if (gap == 0) { + return GapBand( + lo: double.negativeInfinity, + hi: right - clearance, + open: true, + ); + } + final width = math.max(0.0, right - left); + final inset = math.min(clearance, width / 4); + return GapBand(lo: left + inset, hi: right - inset, open: false); + } +} + +/// One usable corridor band. +class GapBand { + const GapBand({required this.lo, required this.hi, required this.open}); + + final double lo; + final double hi; + final bool open; +} + +/// The inset a port keeps from a node corner. +double portInset(GraphNodeBox node, double portSpacing) => + math.min(portSpacing / 2, node.height / 2); + +/// True when an axis-aligned box overlaps [node], optionally inflated by [gap]. +bool boxIntersectsNode({ + required double x, + required double y, + required double width, + required double height, + required GraphNodeBox node, + double gap = 0, +}) { + return x < node.right + gap && + x + width > node.x - gap && + y < node.bottom + gap && + y + height > node.y - gap; +} + +/// True when two label-sized boxes overlap, optionally inflated by [gap]. +bool boxesOverlap({ + required double ax, + required double ay, + required double aw, + required double ah, + required double bx, + required double by, + required double bw, + required double bh, + double gap = 0, +}) { + return ax < bx + bw + gap && + ax + aw + gap > bx && + ay < by + bh + gap && + ay + ah + gap > by; +} diff --git a/app/lib/features/graph/routing/route_models.dart b/app/lib/features/graph/routing/route_models.dart new file mode 100644 index 00000000..7ce2dc24 --- /dev/null +++ b/app/lib/features/graph/routing/route_models.dart @@ -0,0 +1,261 @@ +/// Pure orthogonal geometry for a workflow graph's edges and labels. +/// +/// The caller owns every measurement: node boxes come from the landed +/// `GraphLayout`, label extents are measured after text layout, and clearances +/// or spacings come from [RoutingConfig]. This library never assumes a font, +/// widget style, device class or CSS value, and it has no Flutter imports. +/// +/// The same result can be built into a painter, native widgets or a test +/// fixture; no drawing decision lives here. +library; + +export 'routing_inputs.dart'; + +/// One point on an orthogonal route, in graph space. +class RoutePoint { + const RoutePoint(this.x, this.y); + + final double x; + final double y; + + @override + bool operator ==(Object other) => + other is RoutePoint && other.x == x && other.y == y; + + @override + int get hashCode => Object.hash(x, y); + + @override + String toString() => 'RoutePoint($x, $y)'; +} + +/// The border an edge leaves or enters through. +enum RoutePortSide { top, right, bottom, left } + +/// A route endpoint on a node's border. +/// +/// [side] is the edge's outward direction: a right port leaves to the right +/// (or enters from the right), a left port leaves to the left, and so on. +class RoutePort { + const RoutePort({required this.side, required this.point}); + + final RoutePortSide side; + final RoutePoint point; + + @override + bool operator ==(Object other) => + other is RoutePort && other.side == side && other.point == point; + + @override + int get hashCode => Object.hash(side, point); + + @override + String toString() => 'RoutePort($side, ${point.x}, ${point.y})'; +} + +/// How an edge relates to the layer it comes from. +enum RouteKind { + /// The target is in a later rank. + forward, + + /// Both endpoints share a rank (a cycle or strongly connected component). + sameRank, + + /// The target is in an earlier rank. Ranks from `assignGraphRanks` only + /// produce this for a caller-supplied layout; it is still routed honestly. + back, + + /// The source and target are the same node. + selfLoop, +} + +/// Why an edge has no route. +enum RouteSkipReason { + /// The source key has no placed node. + unknownSource, + + /// The target key has no placed node, including an empty/unknown target. + unknownTarget, +} + +/// One edge's deterministic orthogonal route. +/// +/// [id], [source], [outcome], [target], [label] and [fallback] are copied from +/// the definition edge unchanged. [points] starts at [sourcePort] and ends at +/// [targetPort]; every consecutive pair shares one coordinate. +class EdgeRoute { + EdgeRoute({ + required this.id, + required this.source, + required this.outcome, + required this.target, + required this.label, + required this.fallback, + required this.kind, + required this.straight, + required this.sourcePort, + required this.targetPort, + required List points, + }) : points = List.unmodifiable(points); + + final int id; + final String source; + final String outcome; + final String target; + final String label; + final bool fallback; + final RouteKind kind; + + /// True when the route is one straight horizontal segment. + final bool straight; + final RoutePort sourcePort; + final RoutePort targetPort; + final List points; + + @override + bool operator ==(Object other) => + other is EdgeRoute && + other.id == id && + other.source == source && + other.outcome == outcome && + other.target == target && + other.label == label && + other.fallback == fallback && + other.kind == kind && + other.straight == straight && + other.sourcePort == sourcePort && + other.targetPort == targetPort && + _samePoints(other.points, points); + + @override + int get hashCode => Object.hash( + id, + source, + outcome, + target, + label, + fallback, + kind, + straight, + sourcePort, + targetPort, + Object.hashAll(points), + ); +} + +/// One measured label box placed clear of node interiors. +class EdgeLabelBox { + const EdgeLabelBox({ + required this.edgeId, + required this.x, + required this.y, + required this.width, + required this.height, + }); + + final int edgeId; + final double x; + final double y; + final double width; + final double height; + + double get right => x + width; + double get bottom => y + height; + + @override + bool operator ==(Object other) => + other is EdgeLabelBox && + other.edgeId == edgeId && + other.x == x && + other.y == y && + other.width == width && + other.height == height; + + @override + int get hashCode => Object.hash(edgeId, x, y, width, height); +} + +/// An edge the router deliberately did not draw. +/// +/// The definition identity is preserved so a caller can present a diagnostic +/// instead of inventing a node, route or visit. +class RouteDiagnostic { + const RouteDiagnostic({ + required this.id, + required this.source, + required this.outcome, + required this.target, + required this.reason, + required this.message, + }); + + final int id; + final String source; + final String outcome; + final String target; + final RouteSkipReason reason; + final String message; + + @override + bool operator ==(Object other) => + other is RouteDiagnostic && + other.id == id && + other.source == source && + other.outcome == outcome && + other.target == target && + other.reason == reason && + other.message == message; + + @override + int get hashCode => Object.hash(id, source, outcome, target, reason, message); +} + +/// The complete immutable routing result. +/// +/// [width] and [height] include every route point and label box as well as the +/// landed layout bounds, so a loop that leaves the node grid expands the +/// returned box instead of being clipped. [routes] and [skipped] are ordered by +/// definition edge id; [labels] follows the same order. +class GraphRouting { + GraphRouting({ + required List routes, + required List labels, + required List skipped, + required this.width, + required this.height, + }) : routes = List.unmodifiable(routes), + labels = List.unmodifiable(labels), + skipped = List.unmodifiable(skipped); + + final List routes; + final List labels; + final List skipped; + final double width; + final double height; + + bool get isEmpty => routes.isEmpty; + + /// The route for [id], or null when that edge was skipped. + EdgeRoute? routeFor(int id) { + for (final route in routes) { + if (route.id == id) return route; + } + return null; + } + + /// The label box for [id], or null when the edge was skipped. + EdgeLabelBox? labelFor(int id) { + for (final label in labels) { + if (label.edgeId == id) return label; + } + return null; + } +} + +bool _samePoints(List a, List b) { + if (a.length != b.length) return false; + for (var index = 0; index < a.length; index += 1) { + if (a[index] != b[index]) return false; + } + return true; +} diff --git a/app/lib/features/graph/routing/routing_inputs.dart b/app/lib/features/graph/routing/routing_inputs.dart new file mode 100644 index 00000000..4fafe115 --- /dev/null +++ b/app/lib/features/graph/routing/routing_inputs.dart @@ -0,0 +1,64 @@ +/// Caller-supplied measurements and clearances for graph-edge routing. +/// +/// No font, widget style, device class or CSS value is assumed: every size is +/// measured or chosen by the caller. +library; + +void _requireFiniteNonNegative(String name, double value) { + if (!value.isFinite || value < 0) { + throw ArgumentError.value(value, name, 'must be finite and non-negative'); + } +} + +void _requireFinitePositive(String name, double value) { + if (!value.isFinite || value <= 0) { + throw ArgumentError.value(value, name, 'must be finite and positive'); + } +} + +/// A caller-measured edge label extent, in logical pixels. +class LabelExtent { + LabelExtent({required this.width, required this.height}) { + _requireFiniteNonNegative('width', width); + _requireFiniteNonNegative('height', height); + } + + final double width; + final double height; +} + +/// Clearances and spacings a caller reserves for edge geometry. +/// +/// [nodeClearance] is the distance a lane or corridor keeps from every node +/// edge. [laneSpacing] separates the horizontal tracks used by wrapping +/// routes, [corridorSpacing] separates vertical tracks inside one column gap, +/// and [portSpacing] separates ports on a node side. [labelGap] keeps a label +/// box off its wire; [boundsPadding] is added to the returned bounds. +/// +/// The router may widen a lane step beyond [laneSpacing] when the measured +/// label heights need the room. Inside a narrow column gap it compresses +/// corridor or port spacing rather than routing a track into a node column. +class RoutingConfig { + RoutingConfig({ + required this.nodeClearance, + required this.laneSpacing, + required this.corridorSpacing, + required this.portSpacing, + required this.labelGap, + this.boundsPadding = 0, + }) { + _requireFiniteNonNegative('nodeClearance', nodeClearance); + _requireFinitePositive('laneSpacing', laneSpacing); + _requireFinitePositive('corridorSpacing', corridorSpacing); + _requireFinitePositive('portSpacing', portSpacing); + _requireFiniteNonNegative('labelGap', labelGap); + _requireFiniteNonNegative('boundsPadding', boundsPadding); + } + + final double nodeClearance; + final double laneSpacing; + final double corridorSpacing; + final double portSpacing; + final double labelGap; + final double boundsPadding; +} diff --git a/app/notes/P2c.md b/app/notes/P2c.md new file mode 100644 index 00000000..f8837940 --- /dev/null +++ b/app/notes/P2c.md @@ -0,0 +1,116 @@ +# P2c — deterministic orthogonal edge and label routing + +## What changed + +New app-only, pure-Dart files. No existing file, server, web client, legacy +client, shell, `main.dart`, pubspec, domain, layout, other feature or platform +source was edited. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/graph/routing/route_models.dart` | 261 | public route, port, label, diagnostic and bounds types | +| `lib/features/graph/routing/routing_inputs.dart` | 64 | measured label extents and caller clearances | +| `lib/features/graph/routing/route_geometry.dart` | 175 | axis track allocator and column-gap bands | +| `lib/features/graph/routing/corridor_plan.dart` | 105 | vertical corridor allocation per column gap | +| `lib/features/graph/routing/edge_route_planner.dart` | 265 | forward/back/same-rank/self-loop polyline planning | +| `lib/features/graph/routing/edge_label_placement.dart` | 175 | measured label boxes clear of nodes and other labels | +| `lib/features/graph/routing/graph_edge_routing.dart` | 135 | validation, skipped diagnostics, labels, total bounds | +| `test/features/graph/routing/routing_fixtures.dart` | 143 | chain/diamond/parallel/cycle/self-loop/disconnected fixtures | +| `test/features/graph/routing/routing_assertions.dart` | 215 | orthogonality, borders, node interiors, corridors, labels, bounds | +| `test/features/graph/routing/graph_edge_routing_test.dart` | 191 | chain, diamond, parallel, cycle, loop, disconnected, expanded text, unknown targets | +| `test/features/graph/routing/graph_routing_geometry_test.dart` | 161 | wide labels, tight gaps, 3-stage SCC, backward layout, loop + forwards | +| `test/features/graph/routing/graph_routing_validation_test.dart` | 222 | empty input, missing measurements, duplicate ids, invalid config, determinism/immutability | + +No painting, widgets, styling, shell wiring or font/CSS/device constants were +added. + +## Public API + +```dart +GraphRouting routeGraphEdges({ + required GraphLayout layout, + required List edges, + required Map labelExtents, + required RoutingConfig config, +}); +``` + +`RoutingConfig` takes `nodeClearance`, `laneSpacing`, `corridorSpacing`, +`portSpacing`, `labelGap` and optional `boundsPadding`. `LabelExtent` is the +caller's measured label width/height. The node boxes and ranks are the landed +`GraphLayout` values; the router never moves or resizes a node. + +`GraphRouting` exposes unmodifiable `routes`, `labels`, `skipped`, `width` and +`height`, plus `routeFor(id)` / `labelFor(id)`. Each `EdgeRoute` keeps the +definition `id`, `source`, `outcome`, `target`, `label` and `fallback` flag, and +returns `sourcePort`, `targetPort`, a `RouteKind` and an orthogonal `points` +list. Each `EdgeLabelBox` carries the measured box for its edge id. + +## Deterministic guarantees (and what is not claimed) + +- **Identity:** routed edges copy the definition identity unchanged; skipped + edges keep it in `RouteDiagnostic` with `unknownSource`/`unknownTarget`. No + node, route or visit is invented for an empty, missing or unknown target. +- **Order and stability:** routes, labels and diagnostics are ordered by edge id + regardless of input order. Equal input produces equal, immutable results. +- **Orthogonality and ports:** every consecutive point pair shares one + coordinate. Endpoints are exactly on the source/target border with the + recorded side: forward routes leave right and enter left; same-rank, backward + and self-loop routes leave/enter the right side. +- **Node avoidance:** a forward one-rank route is a straight horizontal run only + when the boxes share a port band and leave room for label-aware track spacing. + Every other route drops into a unique horizontal lane below the node grid, + travels vertically only inside column gaps (or the free space right of the + last column), and returns to a port through its own stub. Vertical corridors + and lanes never enter a node column, and every horizontal stub stays on a row + that is clear of unrelated node boxes. +- **Distinguishable runs:** vertical tracks are spread across each gap, one + slot per corridor request; horizontal stubs and straight routes share one + interval-aware allocator; every wrapping route owns its own lane. Two edges + cannot share a collinear run in the tested fixtures. +- **Labels:** each routed edge needs a measured `LabelExtent`; a missing one is + an `ArgumentError`. The box is placed at a deterministic route run, clear of + node interiors and earlier labels. If a run is too narrow (for example a wide + label between close columns), the label moves to a free shelf below the + drawing and the returned bounds grow instead of covering a node. +- **Bounds:** `width`/`height` include the landed node layout, all route points + and all label boxes, plus `boundsPadding`. A self loop or an edge into the + right-free gap expands the box; nothing is clipped. +- **Not claimed:** perfect general crossing minimization or minimal bend + counts. Corridors and lanes are deterministic and locally separated, not a + globally optimal routing. + +## Checks actually run + +``` +flutter pub get +dart format lib/features/graph/routing test/features/graph/routing # 0 changed +flutter test test/features/graph/routing # 20 passed +flutter analyze # No issues found! +flutter test # 193 passed +``` + +Focused coverage includes chain, diamond fan-out/fan-in, three outcomes to one +target, a two-stage and a three-stage SCC, a self loop alone and beside forward +routes, disconnected stages, heterogeneous widths, 2.6x expanded text, tight +gaps, wide labels, a caller-supplied backward rank, missing/empty/unknown +targets, immutability, stable ordering and finite bounds. + +## Honest limits + +- **No rendering.** This is a nonvisual geometry slice: no painter, widgets, + native controls, screenshots or browser behavior. Rendered parity belongs to + the next renderer task. +- **Layout is an input.** The router does not widen columns for labels or move + nodes. Very wide labels may sit on the free shelf below the drawing; callers + that want labels beside an edge should reserve enough column gap when laying + out nodes. A zero-width column gap leaves no space for distinct vertical + corridors, so callers should supply a positive gap (the landed layout keeps + whatever gap it is given). +- **No general crossing optimum.** Only deterministic corridor/lane separation + is guaranteed, as described above. +- **No server or device.** Tests use local fixtures only; no run, pipeline, + schedule, service, emulator, ADB, Android/iOS build or live chat was touched. +- **Mobile unverified.** Only web-targeted Flutter test/analyze ran. +- **Uncommitted candidate.** Per this stage's instruction the slice is left in + the worktree; no commit, push or deployment was made. diff --git a/app/test/features/graph/routing/graph_edge_routing_test.dart b/app/test/features/graph/routing/graph_edge_routing_test.dart new file mode 100644 index 00000000..59ee4922 --- /dev/null +++ b/app/test/features/graph/routing/graph_edge_routing_test.dart @@ -0,0 +1,191 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/routing/route_models.dart'; + +import '../layout/layout_fixtures.dart' as layout; +import 'routing_assertions.dart'; +import 'routing_fixtures.dart'; + +void main() { + test('chain routes keep identities and use straight forward runs', () { + final graph = chainGraphFixture(); + final layoutBox = layoutFor(graph); + final edges = graphEdges(graph); + final labels = labelsFor(edges); + final routing = routeFor(graph, labels: labels); + + expect(routing.skipped, isEmpty); + expect( + routing.routes.map((route) => route.id), + edges.map((edge) => edge.id), + ); + for (var index = 0; index < edges.length; index += 1) { + final edge = edges[index]; + final route = routing.routes[index]; + expect(route.source, edge.source); + expect(route.outcome, edge.outcome); + expect(route.target, edge.target); + expect(route.label, edge.label); + expect(route.fallback, edge.fallback); + expect(route.kind, RouteKind.forward); + expect(route.straight, isTrue); + expect(route.points.length, 2); + expect(route.sourcePort.side, RoutePortSide.right); + expect(route.targetPort.side, RoutePortSide.left); + } + expectValidRouting(routing, layoutBox, extents: labels); + }); + + test('diamond fan-out and fan-in avoid every node interior', () { + final graph = diamondGraphFixture(); + final layoutBox = layoutFor(graph); + final labels = labelsFor(graphEdges(graph)); + final routing = routeFor(graph, labels: labels); + + expect(routing.skipped, isEmpty); + expect(routing.routes.length, graphEdges(graph).length); + final fromA = routing.routes.where((route) => route.source == 'a'); + expect(fromA.length, 3); + expect( + fromA.where((route) => route.straight).length, + greaterThanOrEqualTo(1), + ); + final longForward = fromA.singleWhere( + (route) => route.target == failureEnd, + ); + expect(longForward.kind, RouteKind.forward); + expect(longForward.straight, isFalse); + expect(longForward.points.length, greaterThan(4)); + expectValidRouting(routing, layoutBox, extents: labels); + }); + + test('parallel outcomes to one target get separate corridors and labels', () { + final graph = parallelOutcomesGraph(); + final layoutBox = layoutFor(graph); + final labels = labelsFor(graphEdges(graph)); + final routing = routeFor(graph, labels: labels); + + final parallel = routing.routes + .where((route) => route.source == 'a' && route.target == 'b') + .toList(); + expect(parallel.length, 3); + final ports = { + for (final route in parallel) + '${route.sourcePort.point.y}/${route.targetPort.point.y}', + }; + expect(ports.length, 3, reason: 'each outcome has its own port pair'); + final labelBoxes = [ + for (final route in parallel) routing.labelFor(route.id)!, + ]; + expect(labelBoxes.map((box) => box.y).toSet().length, greaterThan(1)); + expectValidRouting(routing, layoutBox, extents: labels); + }); + + test('a same-rank cycle uses distinct lanes around both members', () { + final graph = cycleGraphFixture(); + final layoutBox = layoutFor(graph); + final labels = labelsFor(graphEdges(graph)); + final routing = routeFor(graph, labels: labels); + + final sameRank = routing.routes + .where((route) => route.kind == RouteKind.sameRank) + .toList(); + expect(sameRank.length, 2); + expect(sameRank.map((route) => route.target).toSet(), {'a', 'b'}); + for (final route in sameRank) { + expect(route.straight, isFalse); + expect(route.sourcePort.side, RoutePortSide.right); + expect(route.targetPort.side, RoutePortSide.right); + expect( + route.points.map((point) => point.y).toSet().length, + greaterThan(2), + ); + } + expectValidRouting(routing, layoutBox, extents: labels); + }); + + test('a self loop expands bounds and keeps both ports on its border', () { + final graph = selfLoopOnlyGraph(); + final layoutBox = layoutFor(graph); + final labels = labelsFor(graphEdges(graph)); + final routing = routeFor(graph, labels: labels); + + final route = routing.routes.single; + expect(route.kind, RouteKind.selfLoop); + expect(route.straight, isFalse); + expect(route.points.length, greaterThanOrEqualTo(4)); + expect(route.sourcePort.side, RoutePortSide.right); + expect(route.targetPort.side, RoutePortSide.right); + expect(route.sourcePort.point.y, isNot(route.targetPort.point.y)); + expect(routing.width, greaterThan(layoutBox.width)); + expect(routing.height, greaterThan(layoutBox.height)); + expectValidRouting(routing, layoutBox, extents: labels); + }); + + test('disconnected stages route only their declared edges', () { + final graph = disconnectedGraphFixture(); + final layoutBox = layoutFor(graph); + final labels = labelsFor(graphEdges(graph)); + final routing = routeFor(graph, labels: labels); + + expect(routing.skipped, isEmpty); + expect(routing.routes.length, 2); + expect(routing.routes.map((route) => route.source).toSet(), { + 'a', + 'b', + }); + expect(layoutBox.nodeFor('c'), isNotNull); + expect(routing.routes.any((route) => route.source == 'c'), isFalse); + expectValidRouting(routing, layoutBox, extents: labels); + }); + + test('heterogeneous and expanded text sizes stay valid and grow bounds', () { + final graph = diamondGraphFixture(); + final baseLayout = layoutFor(graph, extents: layout.heterogeneousExtents()); + final expandedExtents = layout.scaledExtents( + layout.heterogeneousExtents(), + 2.6, + ); + final expandedLayout = layoutFor(graph, extents: expandedExtents); + final edges = graphEdges(graph); + final labels = fixedLabels(edges); + + final base = routeFor( + graph, + extents: layout.heterogeneousExtents(), + labels: labels, + ); + final expanded = routeFor(graph, extents: expandedExtents, labels: labels); + + expectValidRouting(base, baseLayout, extents: labels); + expectValidRouting(expanded, expandedLayout, extents: labels); + expect(expanded.width, greaterThan(base.width)); + expect(expanded.height, greaterThan(base.height)); + }); + + test('unknown and missing targets are skipped with their identity', () { + final graph = incompleteGraphFixture(); + final layoutBox = layoutFor(graph); + final edges = graphEdges(graph); + final labels = labelsFor(edges); + final routing = routeFor(graph, labels: labels); + + expect(routing.skipped.length, 2); + final skipped = routing.skipped.toList(); + expect(skipped.map((item) => item.reason), [ + RouteSkipReason.unknownTarget, + RouteSkipReason.unknownTarget, + ]); + expect(skipped.map((item) => item.id), [1, 2]); + expect(skipped[0].source, 'a'); + expect(skipped[0].outcome, 'blocked'); + expect(skipped[0].target, ''); + expect(skipped[1].target, 'ghost'); + expect(routing.routes.map((route) => route.id), [3, 4]); + expect(routing.routeFor(1), isNull); + expect(routing.routeFor(2), isNull); + expect(layoutBox.nodeFor('ghost'), isNull); + expectValidRouting(routing, layoutBox, extents: labels); + }); +} diff --git a/app/test/features/graph/routing/graph_routing_geometry_test.dart b/app/test/features/graph/routing/graph_routing_geometry_test.dart new file mode 100644 index 00000000..2fce067a --- /dev/null +++ b/app/test/features/graph/routing/graph_routing_geometry_test.dart @@ -0,0 +1,161 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/layout/layout_models.dart'; +import 'package:pipelines_app/features/graph/routing/graph_edge_routing.dart'; +import 'package:pipelines_app/features/graph/routing/route_models.dart'; + +import 'routing_assertions.dart'; +import 'routing_fixtures.dart'; +import '../layout/layout_fixtures.dart' as layout; + +void main() { + test( + 'wide measured labels move outside the drawing instead of covering it', + () { + final graph = chainGraphFixture(); + final layoutBox = layoutFor(graph); + final edges = graphEdges(graph); + final labels = fixedLabels(edges, width: 400, height: 40); + final routing = routeFor(graph, labels: labels); + + expect(routing.labels.length, edges.length); + for (final label in routing.labels) { + expect(label.y, greaterThanOrEqualTo(layoutBox.height)); + expect(label.right, lessThanOrEqualTo(routing.width)); + expect(label.bottom, lessThanOrEqualTo(routing.height)); + } + expect(routing.height, greaterThan(layoutBox.height)); + expectValidRouting(routing, layoutBox, extents: labels); + }, + ); + + test('tight gaps and expanded extents keep the same guarantees', () { + for (final gap in [8, 24, 80]) { + for (final scale in [1, 2.6]) { + final extents = layout.scaledExtents( + layout.heterogeneousExtents(), + scale, + ); + final layoutBox = layoutFor( + diamondGraphFixture(), + extents: extents, + config: routingLayoutConfig(columnGap: gap, rowGap: 16), + ); + final edges = graphEdges(diamondGraphFixture()); + final labels = labelsFor(edges); + final routing = routeFor( + diamondGraphFixture(), + extents: extents, + labels: labels, + layoutConfig: routingLayoutConfig(columnGap: gap, rowGap: 16), + ); + expectValidRouting(routing, layoutBox, extents: labels); + } + } + }); + + test('a three-stage cycle keeps every same-rank corridor distinct', () { + final graph = cycleThreeGraph(); + final layoutBox = layoutFor( + graph, + config: routingLayoutConfig(columnGap: 8), + ); + final edges = graphEdges(graph); + final labels = labelsFor(edges); + final routing = routeFor( + graph, + labels: labels, + layoutConfig: routingLayoutConfig(columnGap: 8), + ); + + expect(routing.routes.length, 3); + expect( + routing.routes.every((route) => route.kind == RouteKind.sameRank), + isTrue, + ); + expectValidRouting(routing, layoutBox, extents: labels); + }); + + test('a caller-supplied backward rank routes around the target column', () { + final layoutBox = GraphLayout( + nodes: [ + const GraphNodeBox( + key: 'a', + terminal: false, + stageIndex: 0, + rank: 1, + x: 208, + y: 8, + width: 120, + height: 60, + ), + const GraphNodeBox( + key: 'b', + terminal: false, + stageIndex: 1, + rank: 0, + x: 8, + y: 8, + width: 120, + height: 60, + ), + ], + ranks: {'a': 1, 'b': 0}, + rankCount: 2, + width: 336, + height: 76, + ); + final edge = GraphEdge( + id: 1, + source: 'a', + outcome: 'success', + target: 'b', + label: 'success', + fallback: false, + knownTarget: true, + ); + final labels = {1: LabelExtent(width: 52, height: 18)}; + final routing = routeGraphEdges( + layout: layoutBox, + edges: [edge], + labelExtents: labels, + config: routingConfig(), + ); + + final route = routing.routes.single; + expect(route.kind, RouteKind.back); + expect(route.sourcePort.side, RoutePortSide.right); + expect(route.targetPort.side, RoutePortSide.right); + expect(route.straight, isFalse); + expect(route.points.length, greaterThan(4)); + expect(routing.width, greaterThan(layoutBox.width)); + expectValidRouting(routing, layoutBox, extents: labels); + }); + + test('a self loop and forward routes share one valid layout', () { + final graph = selfLoopGraphFixture(); + final layoutBox = layoutFor(graph); + final labels = labelsFor(graphEdges(graph)); + final routing = routeFor(graph, labels: labels); + + expect(routing.routes.length, 4); + expect(routing.routes.map((route) => route.kind).toSet(), { + RouteKind.forward, + RouteKind.selfLoop, + }); + final loop = routing.routes.singleWhere( + (route) => route.kind == RouteKind.selfLoop, + ); + expect(loop.source, 'a'); + expect(loop.target, 'a'); + expect(loop.sourcePort.point.y, isNot(loop.targetPort.point.y)); + expect( + routing.routes + .where((route) => route.target == successEnd) + .every((route) => route.targetPort.side == RoutePortSide.left), + isTrue, + ); + expectValidRouting(routing, layoutBox, extents: labels); + }); +} diff --git a/app/test/features/graph/routing/graph_routing_validation_test.dart b/app/test/features/graph/routing/graph_routing_validation_test.dart new file mode 100644 index 00000000..7d548748 --- /dev/null +++ b/app/test/features/graph/routing/graph_routing_validation_test.dart @@ -0,0 +1,222 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/routing/graph_edge_routing.dart'; +import 'package:pipelines_app/features/graph/routing/route_models.dart'; + +import 'routing_fixtures.dart'; + +GraphEdge _edge({ + int id = 1, + String source = 'a', + String target = 'b', + String outcome = 'success', + bool knownTarget = true, +}) { + return GraphEdge( + id: id, + source: source, + outcome: outcome, + target: target, + label: outcome, + fallback: false, + knownTarget: knownTarget, + ); +} + +void main() { + test('an empty graph has empty routes and the layout bounds', () { + final layoutBox = layoutFor({'stages': []}); + final routing = routeGraphEdges( + layout: layoutBox, + edges: const [], + labelExtents: const {}, + config: routingConfig(), + ); + + expect(routing.isEmpty, isTrue); + expect(routing.routes, isEmpty); + expect(routing.labels, isEmpty); + expect(routing.skipped, isEmpty); + expect(routing.width, layoutBox.width + routingConfig().boundsPadding); + expect(routing.height, layoutBox.height + routingConfig().boundsPadding); + }); + + test('unknown endpoints become diagnostics, never invented nodes', () { + final layoutBox = layoutFor(chainGraphFixture()); + final edges = [ + _edge(id: 1, source: 'missing', target: 's0'), + _edge(id: 2, source: 's0', target: 'ghost'), + _edge(id: 3, source: 's0', target: '', knownTarget: false), + ]; + final routing = routeGraphEdges( + layout: layoutBox, + edges: edges, + labelExtents: const {}, + config: routingConfig(), + ); + + expect(routing.routes, isEmpty); + expect(routing.skipped.map((item) => item.reason), [ + RouteSkipReason.unknownSource, + RouteSkipReason.unknownTarget, + RouteSkipReason.unknownTarget, + ]); + expect(routing.skipped.map((item) => item.id), [1, 2, 3]); + expect(layoutBox.nodeFor('missing'), isNull); + expect(layoutBox.nodeFor('ghost'), isNull); + }); + + test('routed edges require measured label extents', () { + final graph = diamondGraphFixture(); + final layoutBox = layoutFor(graph); + final edges = graphEdges(graph); + final labels = labelsFor(edges)..remove(edges.first.id); + + expect( + () => routeGraphEdges( + layout: layoutBox, + edges: edges, + labelExtents: labels, + config: routingConfig(), + ), + throwsArgumentError, + ); + }); + + test('extra label extents are ignored and duplicate ids are rejected', () { + final graph = diamondGraphFixture(); + final layoutBox = layoutFor(graph); + final edges = graphEdges(graph); + final labels = labelsFor(edges)..[999] = LabelExtent(width: 10, height: 10); + final routing = routeGraphEdges( + layout: layoutBox, + edges: edges, + labelExtents: labels, + config: routingConfig(), + ); + expect(routing.routes.length, edges.length); + expect(routing.labelFor(999), isNull); + + expect( + () => routeGraphEdges( + layout: layoutBox, + edges: [edges.first, edges.first], + labelExtents: labelsFor(edges), + config: routingConfig(), + ), + throwsArgumentError, + ); + }); + + test('invalid configuration and label extents are rejected', () { + expect( + () => RoutingConfig( + nodeClearance: -1, + laneSpacing: 10, + corridorSpacing: 10, + portSpacing: 8, + labelGap: 2, + ), + throwsArgumentError, + ); + expect( + () => RoutingConfig( + nodeClearance: 2, + laneSpacing: 0, + corridorSpacing: 10, + portSpacing: 8, + labelGap: 2, + ), + throwsArgumentError, + ); + expect( + () => RoutingConfig( + nodeClearance: 2, + laneSpacing: 10, + corridorSpacing: double.nan, + portSpacing: 8, + labelGap: 2, + ), + throwsArgumentError, + ); + expect( + () => LabelExtent(width: double.infinity, height: 10), + throwsArgumentError, + ); + expect(() => LabelExtent(width: 10, height: -1), throwsArgumentError); + }); + + test('the same input produces equal immutable results', () { + final graph = diamondGraphFixture(); + final layoutBox = layoutFor(graph); + final edges = graphEdges(graph); + final labels = labelsFor(edges); + final config = routingConfig(); + + final first = routeGraphEdges( + layout: layoutBox, + edges: edges, + labelExtents: labels, + config: config, + ); + final second = routeGraphEdges( + layout: layoutBox, + edges: edges, + labelExtents: labels, + config: config, + ); + + expect(first.routes, second.routes); + expect(first.labels, second.labels); + expect(first.skipped, second.skipped); + expect(first.width, second.width); + expect(first.height, second.height); + expect(() => first.routes.add(first.routes.first), throwsUnsupportedError); + expect( + () => first.routes.first.points.add(const RoutePoint(0, 0)), + throwsUnsupportedError, + ); + expect(() => first.labels.add(first.labels.first), throwsUnsupportedError); + expect( + () => first.skipped.add( + const RouteDiagnostic( + id: 1, + source: 'a', + outcome: 'success', + target: 'b', + reason: RouteSkipReason.unknownTarget, + message: '', + ), + ), + throwsUnsupportedError, + ); + }); + + test('edges are routed in definition id order regardless of input order', () { + final graph = diamondGraphFixture(); + final layoutBox = layoutFor(graph); + final edges = graphEdges(graph); + final labels = labelsFor(edges); + final forward = routeGraphEdges( + layout: layoutBox, + edges: edges, + labelExtents: labels, + config: routingConfig(), + ); + final reversed = routeGraphEdges( + layout: layoutBox, + edges: edges.reversed.toList(), + labelExtents: labels, + config: routingConfig(), + ); + + expect(reversed.routes, forward.routes); + expect(reversed.labels, forward.labels); + expect(reversed.width, forward.width); + expect(reversed.height, forward.height); + expect( + forward.routes.map((route) => route.id), + edges.map((edge) => edge.id), + ); + }); +} diff --git a/app/test/features/graph/routing/routing_assertions.dart b/app/test/features/graph/routing/routing_assertions.dart new file mode 100644 index 00000000..c524fa30 --- /dev/null +++ b/app/test/features/graph/routing/routing_assertions.dart @@ -0,0 +1,215 @@ +import 'dart:math' as math; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/layout/layout_models.dart'; +import 'package:pipelines_app/features/graph/routing/route_models.dart'; + +const double _epsilon = 1e-9; + +/// Checks the routing guarantees every fixture must satisfy. +void expectValidRouting( + GraphRouting routing, + GraphLayout layout, { + Map? extents, +}) { + expect(routing.width.isFinite, isTrue); + expect(routing.height.isFinite, isTrue); + expect(routing.width, greaterThan(0)); + expect(routing.height, greaterThan(0)); + + for (final route in routing.routes) { + _expectRoute(route, layout, routing.width, routing.height); + _expectNoNodeInterior(route, layout); + } + expectDistinctCorridors(routing.routes); + + final byId = { + for (final label in routing.labels) label.edgeId: label, + }; + expect(byId.length, routing.labels.length, reason: 'one label per edge'); + for (final route in routing.routes) { + final label = byId[route.id]; + expect(label, isNotNull, reason: 'edge ${route.id} has a label'); + final extent = extents?[route.id]; + if (extent != null) { + expect(label!.width, extent.width); + expect(label.height, extent.height); + } + expect(label!.x, greaterThanOrEqualTo(-_epsilon)); + expect(label.y, greaterThanOrEqualTo(-_epsilon)); + expect(label.right, lessThanOrEqualTo(routing.width + _epsilon)); + expect(label.bottom, lessThanOrEqualTo(routing.height + _epsilon)); + for (final node in layout.nodes) { + expect( + _overlaps( + label.x, + label.y, + label.width, + label.height, + node.x, + node.y, + node.width, + node.height, + ), + isFalse, + reason: 'label for edge ${route.id} overlaps node ${node.key}', + ); + } + } + for (var first = 0; first < routing.labels.length; first += 1) { + for (var second = first + 1; second < routing.labels.length; second += 1) { + final a = routing.labels[first]; + final b = routing.labels[second]; + expect( + _overlaps(a.x, a.y, a.width, a.height, b.x, b.y, b.width, b.height), + isFalse, + reason: 'labels for edges ${a.edgeId} and ${b.edgeId} overlap', + ); + } + } + + for (final skipped in routing.skipped) { + expect(routing.routeFor(skipped.id), isNull); + expect(routing.labelFor(skipped.id), isNull); + } +} + +void expectDistinctCorridors(List routes) { + for (var first = 0; first < routes.length; first += 1) { + for (var second = first + 1; second < routes.length; second += 1) { + final a = routes[first]; + final b = routes[second]; + for (var ai = 1; ai < a.points.length; ai += 1) { + final a0 = a.points[ai - 1]; + final a1 = a.points[ai]; + for (var bi = 1; bi < b.points.length; bi += 1) { + final b0 = b.points[bi - 1]; + final b1 = b.points[bi]; + if (a0.x == a1.x && b0.x == b1.x && a0.x == b0.x) { + final aLo = math.min(a0.y, a1.y); + final aHi = math.max(a0.y, a1.y); + final bLo = math.min(b0.y, b1.y); + final bHi = math.max(b0.y, b1.y); + expect( + aLo < bHi - _epsilon && bLo < aHi - _epsilon, + isFalse, + reason: 'edges ${a.id} and ${b.id} share a vertical corridor', + ); + } + if (a0.y == a1.y && b0.y == b1.y && a0.y == b0.y) { + final aLo = math.min(a0.x, a1.x); + final aHi = math.max(a0.x, a1.x); + final bLo = math.min(b0.x, b1.x); + final bHi = math.max(b0.x, b1.x); + expect( + aLo < bHi - _epsilon && bLo < aHi - _epsilon, + isFalse, + reason: 'edges ${a.id} and ${b.id} share a horizontal run', + ); + } + } + } + } + } +} + +void _expectRoute( + EdgeRoute route, + GraphLayout layout, + double width, + double height, +) { + expect(route.points.length, greaterThanOrEqualTo(2)); + expect(route.points.first, route.sourcePort.point); + expect(route.points.last, route.targetPort.point); + for (var index = 0; index < route.points.length; index += 1) { + final point = route.points[index]; + expect(point.x.isFinite, isTrue); + expect(point.y.isFinite, isTrue); + expect(point.x, greaterThanOrEqualTo(-_epsilon)); + expect(point.y, greaterThanOrEqualTo(-_epsilon)); + expect(point.x, lessThanOrEqualTo(width + _epsilon)); + expect(point.y, lessThanOrEqualTo(height + _epsilon)); + if (index > 0) { + final previous = route.points[index - 1]; + expect( + previous.x == point.x || previous.y == point.y, + isTrue, + reason: 'edge ${route.id} segment ${index - 1} is not orthogonal', + ); + expect(previous, isNot(point), reason: 'zero-length segment'); + } + } + _expectPort(route.sourcePort, layout.nodeFor(route.source)!); + _expectPort(route.targetPort, layout.nodeFor(route.target)!); +} + +void _expectPort(RoutePort port, GraphNodeBox box) { + switch (port.side) { + case RoutePortSide.right: + expect(port.point.x, closeTo(box.right, _epsilon)); + expect(port.point.y, greaterThanOrEqualTo(box.y - _epsilon)); + expect(port.point.y, lessThanOrEqualTo(box.bottom + _epsilon)); + case RoutePortSide.left: + expect(port.point.x, closeTo(box.x, _epsilon)); + expect(port.point.y, greaterThanOrEqualTo(box.y - _epsilon)); + expect(port.point.y, lessThanOrEqualTo(box.bottom + _epsilon)); + case RoutePortSide.top: + expect(port.point.y, closeTo(box.y, _epsilon)); + expect(port.point.x, greaterThanOrEqualTo(box.x - _epsilon)); + expect(port.point.x, lessThanOrEqualTo(box.right + _epsilon)); + case RoutePortSide.bottom: + expect(port.point.y, closeTo(box.bottom, _epsilon)); + expect(port.point.x, greaterThanOrEqualTo(box.x - _epsilon)); + expect(port.point.x, lessThanOrEqualTo(box.right + _epsilon)); + } +} + +void _expectNoNodeInterior(EdgeRoute route, GraphLayout layout) { + for (var index = 1; index < route.points.length; index += 1) { + final a = route.points[index - 1]; + final b = route.points[index]; + for (final node in layout.nodes) { + if (a.y == b.y) { + final left = math.min(a.x, b.x); + final right = math.max(a.x, b.x); + final crosses = + a.y > node.y + _epsilon && + a.y < node.bottom - _epsilon && + right > node.x + _epsilon && + left < node.right - _epsilon; + expect( + crosses, + isFalse, + reason: 'edge ${route.id} crosses node ${node.key} horizontally', + ); + } else { + final top = math.min(a.y, b.y); + final bottom = math.max(a.y, b.y); + final crosses = + a.x > node.x + _epsilon && + a.x < node.right - _epsilon && + bottom > node.y + _epsilon && + top < node.bottom - _epsilon; + expect( + crosses, + isFalse, + reason: 'edge ${route.id} crosses node ${node.key} vertically', + ); + } + } + } +} + +bool _overlaps( + double ax, + double ay, + double aw, + double ah, + double bx, + double by, + double bw, + double bh, +) { + return ax < bx + bw && ax + aw > bx && ay < by + bh && ay + ah > by; +} diff --git a/app/test/features/graph/routing/routing_fixtures.dart b/app/test/features/graph/routing/routing_fixtures.dart new file mode 100644 index 00000000..7a155b03 --- /dev/null +++ b/app/test/features/graph/routing/routing_fixtures.dart @@ -0,0 +1,143 @@ +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/layout/graph_node_layout.dart'; +import 'package:pipelines_app/features/graph/layout/layout_models.dart'; +import 'package:pipelines_app/features/graph/routing/graph_edge_routing.dart'; +import 'package:pipelines_app/features/graph/routing/route_models.dart'; + +import '../layout/layout_fixtures.dart' as layout; +import '../domain/graph_fixtures.dart' as domain; + +/// Definitions, measured extents and configs shared by the routing tests. + +GraphLayoutConfig routingLayoutConfig({ + double columnGap = 80, + double rowGap = 16, + double padding = 8, +}) { + return GraphLayoutConfig( + columnGap: columnGap, + rowGap: rowGap, + padding: padding, + ); +} + +RoutingConfig routingConfig({ + double nodeClearance = 8, + double laneSpacing = 28, + double corridorSpacing = 20, + double portSpacing = 12, + double labelGap = 4, + double boundsPadding = 4, +}) { + return RoutingConfig( + nodeClearance: nodeClearance, + laneSpacing: laneSpacing, + corridorSpacing: corridorSpacing, + portSpacing: portSpacing, + labelGap: labelGap, + boundsPadding: boundsPadding, + ); +} + +GraphLayout layoutFor( + Map graph, { + Map? extents, + GraphLayoutConfig? config, +}) { + final nodes = graphNodes(graph); + return layoutGraphNodes( + nodes: nodes, + edges: graphEdges(graph), + extents: extents ?? layout.uniformExtents(nodes), + config: config ?? routingLayoutConfig(), + ); +} + +/// Measured label boxes sized from their text, as a renderer would supply them. +Map labelsFor( + Iterable edges, { + double charWidth = 7, + double padding = 12, + double height = 18, +}) { + return { + for (final edge in edges) + edge.id: LabelExtent( + width: edge.label.length * charWidth + padding, + height: height, + ), + }; +} + +/// One box per edge at an explicit size, used for wide-label checks. +Map fixedLabels( + Iterable edges, { + double width = 52, + double height = 18, +}) { + return { + for (final edge in edges) + edge.id: LabelExtent(width: width, height: height), + }; +} + +GraphRouting routeFor( + Map graph, { + Map? extents, + Map? labels, + GraphLayoutConfig? layoutConfig, + RoutingConfig? config, +}) { + final layout = layoutFor(graph, extents: extents, config: layoutConfig); + final edges = graphEdges(graph); + return routeGraphEdges( + layout: layout, + edges: edges, + labelExtents: labels ?? labelsFor(edges), + config: config ?? routingConfig(), + ); +} + +/// Three outcomes from `a` to the same target `b`, then `b` to Success. +Map parallelOutcomesGraph() => { + 'stages': [ + domain.stage( + 'a', + edges: { + 'success': 'b', + 'approved': 'b', + 'rejected': 'b', + }, + ), + domain.stage('b', edges: {'success': '#success'}), + ], +}; + +/// A single stage that retries itself and has no terminal pair. +Map selfLoopOnlyGraph() => { + 'stages': [ + domain.stage('a', edges: {'retry': 'a'}), + ], +}; + +Map chainGraphFixture() => layout.chainGraph(4); + +Map diamondGraphFixture() => layout.diamondGraphFixture(); + +Map cycleGraphFixture() => layout.cycleGraph(); + +Map selfLoopGraphFixture() => layout.selfLoopGraphFixture(); + +Map disconnectedGraphFixture() => layout.disconnectedGraph(); + +Map incompleteGraphFixture() => + layout.incompleteGraphFixture(); + +/// Three stages in one strongly connected component with no terminals. +Map cycleThreeGraph() => { + 'stages': [ + domain.stage('a', edges: {'success': 'b'}), + domain.stage('b', edges: {'success': 'c'}), + domain.stage('c', edges: {'success': 'a'}), + ], +}; From ff0f812e002251e6432da9b0ec5ec005e84dd39c Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 16:56:11 +0100 Subject: [PATCH 60/84] feat(app): add artifact records, grouping and safe url navigation Pure Dart A1a artifact domain slice mirroring web/src/artifacts.js and artifactNavigation.js: record parsing, capture facts, stage/visit grouping, public attribution, kind vocabulary, summaries, viewer paging and safe artifact url resolution. Tests mirror the domain directory; nothing is wired into a screen or transport. --- .../artifacts/domain/artifact_capture.dart | 63 ++++ .../artifacts/domain/artifact_groups.dart | 109 +++++++ .../artifacts/domain/artifact_kind.dart | 225 +++++++++++++ .../artifacts/domain/artifact_record.dart | 85 +++++ .../artifacts/domain/artifact_selection.dart | 67 ++++ .../artifacts/domain/artifact_summary.dart | 78 +++++ .../artifacts/domain/artifact_url.dart | 78 +++++ .../artifacts/domain/gallery_navigation.dart | 76 +++++ app/notes/A1a.md | 101 ++++++ .../domain/artifact_capture_test.dart | 241 ++++++++++++++ .../artifacts/domain/artifact_fixtures.dart | 44 +++ .../domain/artifact_groups_test.dart | 308 ++++++++++++++++++ .../artifacts/domain/artifact_kind_test.dart | 110 +++++++ .../domain/artifact_selection_test.dart | 154 +++++++++ .../artifacts/domain/artifact_url_test.dart | 148 +++++++++ .../domain/gallery_navigation_test.dart | 197 +++++++++++ 16 files changed, 2084 insertions(+) create mode 100644 app/lib/features/artifacts/domain/artifact_capture.dart create mode 100644 app/lib/features/artifacts/domain/artifact_groups.dart create mode 100644 app/lib/features/artifacts/domain/artifact_kind.dart create mode 100644 app/lib/features/artifacts/domain/artifact_record.dart create mode 100644 app/lib/features/artifacts/domain/artifact_selection.dart create mode 100644 app/lib/features/artifacts/domain/artifact_summary.dart create mode 100644 app/lib/features/artifacts/domain/artifact_url.dart create mode 100644 app/lib/features/artifacts/domain/gallery_navigation.dart create mode 100644 app/notes/A1a.md create mode 100644 app/test/features/artifacts/domain/artifact_capture_test.dart create mode 100644 app/test/features/artifacts/domain/artifact_fixtures.dart create mode 100644 app/test/features/artifacts/domain/artifact_groups_test.dart create mode 100644 app/test/features/artifacts/domain/artifact_kind_test.dart create mode 100644 app/test/features/artifacts/domain/artifact_selection_test.dart create mode 100644 app/test/features/artifacts/domain/artifact_url_test.dart create mode 100644 app/test/features/artifacts/domain/gallery_navigation_test.dart diff --git a/app/lib/features/artifacts/domain/artifact_capture.dart b/app/lib/features/artifacts/domain/artifact_capture.dart new file mode 100644 index 00000000..6f081d16 --- /dev/null +++ b/app/lib/features/artifacts/domain/artifact_capture.dart @@ -0,0 +1,63 @@ +import '../../../core/api_gateway.dart'; +import 'artifact_record.dart'; + +/// Whether a step actually carried an artifact list. +/// +/// An absent (or null) field means the capture is unavailable: an older step, a +/// running visit, or a reply that did not include the field. It must never be +/// reported as an empty capture. An explicitly recorded empty list is a known, +/// empty capture. +enum ArtifactCaptureAvailability { unavailable, recorded } + +/// The recorded capture facts of one step: availability, files, and how many +/// files the bounded scan excluded or omitted. Pure: it reads the step and adds +/// no server call. +class ArtifactCapture { + const ArtifactCapture._({ + required this.availability, + required this.artifacts, + required this.skipped, + required this.truncated, + }); + + factory ArtifactCapture.fromStep(JsonMap step) { + final value = step['artifacts']; + final available = step.containsKey('artifacts') && value is List; + final artifacts = available + ? [ + for (final item in value) + if (item is Map) + ArtifactRecord.fromJson(Map.from(item)), + ] + : const []; + return ArtifactCapture._( + availability: available + ? ArtifactCaptureAvailability.recorded + : ArtifactCaptureAvailability.unavailable, + artifacts: List.unmodifiable(artifacts), + skipped: _countOf(step['artifacts_skipped']), + truncated: _countOf(step['artifacts_truncated']), + ); + } + + final ArtifactCaptureAvailability availability; + + /// Every recorded file, including utility and retired files. + final List artifacts; + + /// Files excluded from the bounded per-step scan. + final int skipped; + + /// Files omitted by the capture's total budget. + final int truncated; + + bool get isAvailable => availability == ArtifactCaptureAvailability.recorded; + + bool get isPartial => skipped > 0 || truncated > 0; + + static int _countOf(dynamic value) { + if (value is num) return value.toInt(); + if (value is String) return int.tryParse(value.trim()) ?? 0; + return 0; + } +} diff --git a/app/lib/features/artifacts/domain/artifact_groups.dart b/app/lib/features/artifacts/domain/artifact_groups.dart new file mode 100644 index 00000000..bfa0707e --- /dev/null +++ b/app/lib/features/artifacts/domain/artifact_groups.dart @@ -0,0 +1,109 @@ +import '../../../core/api_gateway.dart'; +import '../../graph/domain/stage_visits.dart'; +import 'artifact_record.dart'; +import 'artifact_selection.dart'; + +/// One gallery group: the stage-produced artifacts of a recorded stage visit. +class ArtifactGroup { + const ArtifactGroup({ + required this.stageKey, + required this.visit, + required this.artifacts, + }); + + final String stageKey; + + /// The display visit number: `control.visit` when positive, else the position + /// within the stage's ordered visits. Never a synthetic visit. + final int visit; + + final List artifacts; +} + +int _sequenceOf(JsonMap step) { + final sequence = step['sequence']; + return sequence is num ? sequence.toInt() : 0; +} + +/// Sequence order with recorded order as the tie-break, matching the web +/// client's stable sort. +List _orderedBySequence(List steps) { + final indexed = <({int position, JsonMap step})>[ + for (var index = 0; index < steps.length; index += 1) + (position: index, step: steps[index]), + ]; + indexed.sort((a, b) { + final bySequence = _sequenceOf(a.step).compareTo(_sequenceOf(b.step)); + return bySequence != 0 ? bySequence : a.position.compareTo(b.position); + }); + return [for (final entry in indexed) entry.step]; +} + +/// Groups a run's stage artifacts by stage and recorded visit. +/// +/// Stages keep first-appearance order and each stage's visits are ordered by +/// sequence. A shared `public/` file is attributed to the visit that first +/// recorded it, because the server records the whole public directory on every +/// model visit. Only visits with at least one presented stage artifact produce a +/// group, so an unavailable or empty capture never yields an empty group. An +/// artifact-less run yields an empty list rather than a fabricated stage. +List artifactGroups(List steps) { + if (steps.isEmpty) return const []; + + final attributed = >{}; + final seenPublic = {}; + for (final recordedStep in _orderedBySequence(steps)) { + final repairs = repairArtifactNames(recordedStep); + final kept = []; + for (final artifact in stageArtifactsFrom( + artifactsOf(recordedStep), + repairs: repairs, + )) { + if (artifact.isPublicName) { + if (seenPublic.contains(artifact.name)) continue; + seenPublic.add(artifact.name); + } + kept.add(artifact); + } + attributed[recordedStep] = List.unmodifiable(kept); + } + + final groups = []; + for (final entry in visitsByStage(steps).entries) { + final visits = entry.value; + for (var index = 0; index < visits.length; index += 1) { + final artifacts = attributed[visits[index]]; + if (artifacts == null || artifacts.isEmpty) continue; + groups.add( + ArtifactGroup( + stageKey: entry.key, + visit: displayVisit(visits[index], index), + artifacts: artifacts, + ), + ); + } + } + return List.unmodifiable(groups); +} + +/// One visit's stage artifacts, excluding shared public files that an earlier +/// visit already recorded. A repeated non-public name in a later visit stays +/// because it is a different recorded artifact, not the same shared file. +List visitArtifacts(JsonMap step, List runSteps) { + final all = stageArtifacts(step); + if (runSteps.isEmpty) return all; + final seen = {}; + for (final candidate in _orderedBySequence(runSteps)) { + if (identical(candidate, step) || + _sequenceOf(candidate) == _sequenceOf(step)) { + break; + } + for (final artifact in stageArtifacts(candidate)) { + if (artifact.isPublicName) seen.add(artifact.name); + } + } + return [ + for (final artifact in all) + if (!artifact.isPublicName || !seen.contains(artifact.name)) artifact, + ]; +} diff --git a/app/lib/features/artifacts/domain/artifact_kind.dart b/app/lib/features/artifacts/domain/artifact_kind.dart new file mode 100644 index 00000000..7bac7708 --- /dev/null +++ b/app/lib/features/artifacts/domain/artifact_kind.dart @@ -0,0 +1,225 @@ +/// What an artifact is from the gallery's point of view: the two media kinds it +/// previews and the file kinds it labels with a type word. Mirrors the web +/// client's `ArtifactKind` vocabulary. +enum ArtifactKind { + image, + video, + audio, + pdf, + json, + archive, + spreadsheet, + log, + code, + document, + other, +} + +const Set _archiveExtensions = { + 'zip', + 'tar', + 'gz', + 'tgz', + 'bz2', + 'xz', + 'rar', + '7z', + 'jar', + 'war', +}; + +const Set _archiveMimes = { + 'application/zip', + 'application/gzip', + 'application/x-tar', + 'application/x-7z-compressed', + 'application/x-rar-compressed', + 'application/java-archive', +}; + +const Set _spreadsheetExtensions = { + 'csv', + 'tsv', + 'xls', + 'xlsx', + 'ods', +}; + +const Set _spreadsheetMimes = { + 'text/csv', + 'text/tab-separated-values', + 'application/vnd.ms-excel', + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', +}; + +const Set _codeExtensions = { + 'kt', + 'kts', + 'java', + 'go', + 'py', + 'rb', + 'php', + 'rs', + 'c', + 'h', + 'cc', + 'cpp', + 'hpp', + 'cs', + 'js', + 'jsx', + 'ts', + 'tsx', + 'mjs', + 'cjs', + 'swift', + 'scala', + 'sh', + 'bash', + 'zsh', + 'fish', + 'ps1', + 'sql', + 'yaml', + 'yml', + 'toml', + 'ini', + 'xml', + 'gradle', + 'properties', + 'proto', +}; + +const Set _codeMimes = { + 'application/xml', + 'application/x-yaml', + 'application/javascript', + 'text/javascript', + 'text/x-python', + 'text/x-java-source', + 'text/x-kotlin', + 'application/x-sh', + 'application/x-httpd-php', + 'application/sql', +}; + +const Set _documentExtensions = { + 'txt', + 'md', + 'markdown', + 'rst', + 'doc', + 'docx', + 'odt', + 'rtf', + 'html', + 'htm', +}; + +const Set _markdownExtensions = {'md', 'markdown', 'txt'}; + +const Set _documentMimes = { + 'application/msword', + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'application/rtf', +}; + +const Map _kindLabels = { + ArtifactKind.image: 'Image', + ArtifactKind.video: 'Video', + ArtifactKind.audio: 'Audio', + ArtifactKind.pdf: 'PDF', + ArtifactKind.json: 'JSON', + ArtifactKind.archive: 'Archive', + ArtifactKind.spreadsheet: 'Spreadsheet', + ArtifactKind.log: 'Log', + ArtifactKind.code: 'Code', + ArtifactKind.document: 'Document', + ArtifactKind.other: 'File', +}; + +/// Whether a recorded content type is an image the gallery previews. +bool isImageContentType(String contentType) => contentType.startsWith('image/'); + +/// Whether a recorded content type is a video; videos get a poster tile and are +/// never decoded inline or autoplayed. +bool isVideoContentType(String contentType) => contentType.startsWith('video/'); + +/// The lowercased extension of [name], or '' when it carries none. +String _extensionOf(String name) { + final dot = name.lastIndexOf('.'); + return dot == -1 ? '' : name.substring(dot + 1).toLowerCase(); +} + +/// The gallery kind for a recorded content type and name. +/// +/// Image and video come straight from the content type; the other kinds match +/// the normalised MIME first, then the name's extension. Pure and total: an +/// unknown type is [ArtifactKind.other], never a guess that changes an action. +ArtifactKind artifactKind(String contentType, String name) { + if (isImageContentType(contentType)) return ArtifactKind.image; + if (isVideoContentType(contentType)) return ArtifactKind.video; + final mime = contentType.split(';').first.trim().toLowerCase(); + final ext = _extensionOf(name); + if (mime.startsWith('audio/')) return ArtifactKind.audio; + if (mime == 'application/pdf' || ext == 'pdf') return ArtifactKind.pdf; + if (mime.contains('json') || ext == 'json') return ArtifactKind.json; + if (_archiveMimes.contains(mime) || _archiveExtensions.contains(ext)) { + return ArtifactKind.archive; + } + if (_spreadsheetMimes.contains(mime) || + _spreadsheetExtensions.contains(ext)) { + return ArtifactKind.spreadsheet; + } + if (ext == 'log') return ArtifactKind.log; + if (mime == 'text/html') return ArtifactKind.document; + if (_codeMimes.contains(mime) || _codeExtensions.contains(ext)) { + return ArtifactKind.code; + } + if (mime.startsWith('text/') || + _documentMimes.contains(mime) || + _documentExtensions.contains(ext)) { + return ArtifactKind.document; + } + return ArtifactKind.other; +} + +/// The prose word naming [kind], so a type glyph never has to be read alone. +String artifactKindLabel(ArtifactKind kind) => _kindLabels[kind] ?? 'File'; + +/// Whether an artifact is text the viewer can render as markdown: `text/markdown` +/// or `text/plain` (parameters ignored), or an md/markdown/txt name. +bool isMarkdownArtifact(String contentType, String name) { + final mime = contentType.split(';').first.trim().toLowerCase(); + if (mime == 'text/markdown' || mime == 'text/plain') return true; + return _markdownExtensions.contains(_extensionOf(name)); +} + +/// Whether an artifact opens inside the full-screen viewer: images, videos, and +/// markdown/text documents. A `text/plain` log, source file or spreadsheet stays +/// an external file because those are evidence, not prose. +bool isViewerArtifact(String contentType, String name) { + if (isImageContentType(contentType) || isVideoContentType(contentType)) { + return true; + } + return artifactKind(contentType, name) == ArtifactKind.document && + isMarkdownArtifact(contentType, name); +} + +/// Human-readable byte size, matching the web client: whole bytes under 1 KiB, +/// otherwise one decimal with a binary unit (KiB/MiB/GiB/TiB/PiB/EiB). +String humanBytes(num size) { + final value = size.truncate(); + const unit = 1024; + if (value < unit) return '$value B'; + var div = unit; + var exp = 0; + var scaled = value ~/ unit; + while (scaled >= unit) { + div *= unit; + exp++; + scaled ~/= unit; + } + return '${(value / div).toStringAsFixed(1)} ${'KMGTPE'[exp]}iB'; +} diff --git a/app/lib/features/artifacts/domain/artifact_record.dart b/app/lib/features/artifacts/domain/artifact_record.dart new file mode 100644 index 00000000..6c6bc845 --- /dev/null +++ b/app/lib/features/artifacts/domain/artifact_record.dart @@ -0,0 +1,85 @@ +import '../../../core/api_gateway.dart'; + +/// The retired markdown session export file name. Nothing writes it any more, +/// but a run recorded before the HTML-only change still lists `session.md`: it +/// is dated evidence that is never presented beside `session.html`. +const String legacySessionMarkdownArtifact = 'session.md'; + +/// The files the turn protocol itself writes for every visit. They are audit +/// evidence, not stage output, so the artifact gallery lists stage files first +/// and keeps these for an audit/debug surface. +const List systemArtifactNames = [ + 'input.md', + 'memory.md', + 'output.md', + 'session.html', +]; + +/// One recorded artifact of a stage visit. +/// +/// The server is the authority: [name], [url], [contentType] and [sizeBytes] +/// are read verbatim and every other field is kept in [raw]. A record is never +/// inferred or completed locally; a missing url stays empty rather than being +/// fabricated from the name. Two records with the same name stay distinct +/// because only the recorded url identifies an artifact. +class ArtifactRecord { + const ArtifactRecord({ + required this.name, + required this.url, + required this.contentType, + required this.sizeBytes, + required this.raw, + }); + + factory ArtifactRecord.fromJson(JsonMap json) { + final raw = _frozenMap(json); + return ArtifactRecord( + name: _text(raw['name']), + url: _text(raw['url']), + contentType: _text(raw['content_type']), + sizeBytes: _intOf(raw['size_bytes']), + raw: raw, + ); + } + + /// The recorded file name, including any `public/` prefix. + final String name; + + /// The recorded artifact url exactly as the server sent it. + final String url; + + /// The server-sniffed content type, possibly with parameters. + final String contentType; + + /// The recorded byte size; 0 when the server recorded none. + final int sizeBytes; + + /// Every field the server sent, including fields this slice does not model. + /// Deeply unmodifiable, so a view cannot mutate the server reply. + final JsonMap raw; + + bool get hasUrl => url.trim().isNotEmpty; + bool get isLegacySessionMarkdown => name == legacySessionMarkdownArtifact; + bool get isSystem => isSystemArtifactName(name); + bool get isPublicName => name.startsWith('public/'); + + static String _text(dynamic value) => value == null ? '' : '$value'; + + static int _intOf(dynamic value) { + if (value is num) return value.toInt(); + if (value is String) return int.tryParse(value.trim()) ?? 0; + return 0; + } + + static JsonMap _frozenMap(JsonMap json) => Map.unmodifiable( + json.map((key, value) => MapEntry(key, _frozen(value))), + ); + + static dynamic _frozen(dynamic value) { + if (value is Map) return _frozenMap(Map.from(value)); + if (value is List) return List.unmodifiable(value.map(_frozen)); + return value; + } +} + +bool isSystemArtifactName(String name) => systemArtifactNames.contains(name); diff --git a/app/lib/features/artifacts/domain/artifact_selection.dart b/app/lib/features/artifacts/domain/artifact_selection.dart new file mode 100644 index 00000000..4f976473 --- /dev/null +++ b/app/lib/features/artifacts/domain/artifact_selection.dart @@ -0,0 +1,67 @@ +import '../../../core/api_gateway.dart'; +import 'artifact_record.dart'; + +/// Parses one step's recorded artifact list. An absent, null or malformed list +/// yields no records; the capture state (and its unavailable wording) is +/// reported by `artifact_capture.dart`, never treated as an empty capture here. +List artifactsOf(JsonMap step) { + final value = step['artifacts']; + if (value is! List) return const []; + return [ + for (final item in value) + if (item is Map) ArtifactRecord.fromJson(Map.from(item)), + ]; +} + +/// The html names a visit's session-export repairs produced. +Set repairArtifactNames(JsonMap step) { + final value = step['session_export_repairs']; + if (value is! List) return const {}; + return { + for (final entry in value) + if (entry is Map && + entry['html'] is String && + '${entry['html']}'.trim().isNotEmpty) + '${entry['html']}', + }; +} + +/// The artifacts of one visit as presented: the recorded files with the retired +/// markdown session export filtered out. Duplicate names are kept because an +/// artifact's identity is its recorded url, not its name. +List presentedArtifacts(Iterable artifacts) { + return [ + for (final artifact in artifacts) + if (!artifact.isLegacySessionMarkdown) artifact, + ]; +} + +/// A visit's stage-produced artifacts: everything except the turn-owned files +/// and repaired session exports. Order is preserved. +List stageArtifactsFrom( + Iterable artifacts, { + Set repairs = const {}, +}) { + return [ + for (final artifact in presentedArtifacts(artifacts)) + if (!artifact.isSystem && !repairs.contains(artifact.name)) artifact, + ]; +} + +/// A visit's system files and repaired exports, in recorded order. +List systemArtifactsFrom( + Iterable artifacts, { + Set repairs = const {}, +}) { + return [ + for (final artifact in presentedArtifacts(artifacts)) + if (artifact.isSystem || repairs.contains(artifact.name)) artifact, + ]; +} + +/// Convenience for callers holding a raw step rather than parsed records. +List stageArtifacts(JsonMap step) => + stageArtifactsFrom(artifactsOf(step), repairs: repairArtifactNames(step)); + +List systemArtifacts(JsonMap step) => + systemArtifactsFrom(artifactsOf(step), repairs: repairArtifactNames(step)); diff --git a/app/lib/features/artifacts/domain/artifact_summary.dart b/app/lib/features/artifacts/domain/artifact_summary.dart new file mode 100644 index 00000000..44161a86 --- /dev/null +++ b/app/lib/features/artifacts/domain/artifact_summary.dart @@ -0,0 +1,78 @@ +import '../../../core/api_gateway.dart'; +import 'artifact_capture.dart'; +import 'artifact_groups.dart'; +import 'artifact_selection.dart'; + +/// The "capture pending" wording shared by a running visit's summary and the +/// run-level empty state, so the two never spell it differently. +const String artifactCapturePending = 'capture pending'; + +/// The explicit message shown where the run's gallery would be when there are +/// no recorded artifacts. A running run says capture pending; a finished run +/// with available captures says plainly that nothing was recorded. +String artifactsEmptyMessage(bool executing) => executing + ? 'Artifacts · $artifactCapturePending' + : 'No artifacts recorded for this run.'; + +/// The run summary's Artifacts section header. +/// +/// The recorded count is exactly the number of tiles [artifactGroups] yields; +/// the title takes its singular form for one. A run whose capture is unavailable +/// says so instead of claiming that nothing was recorded. Partial capture is +/// flagged when any visit excluded or omitted files. +String artifactsHeader(List steps, {required bool executing}) { + final recorded = artifactGroups( + steps, + ).fold(0, (sum, group) => sum + group.artifacts.length); + if (recorded == 0) { + if (executing) return artifactsEmptyMessage(true); + final unavailable = steps.any( + (step) => !ArtifactCapture.fromStep(step).isAvailable, + ); + return unavailable + ? 'Artifacts · capture unavailable' + : artifactsEmptyMessage(false); + } + final partial = steps.any((step) => ArtifactCapture.fromStep(step).isPartial); + var label = + '${recorded == 1 ? 'Artifact' : 'Artifacts'} · $recorded recorded'; + if (partial) label += ' · partial capture'; + return label; +} + +/// The per-visit artifacts label. +/// +/// A running visit says capture pending. A finished visit whose capture field was +/// absent says capture unavailable rather than "not recorded"; only an explicitly +/// empty capture says "not recorded for this visit". Recorded counts exclude the +/// turn-owned files and the retired session markdown, so the words match tiles. +String artifactsSummary(JsonMap step, {int? count}) { + final capture = ArtifactCapture.fromStep(step); + final recorded = count ?? stageArtifacts(step).length; + if (recorded == 0) { + if (step['status'] == 'running') { + return 'Artifacts · $artifactCapturePending'; + } + if (!capture.isAvailable) return 'Artifacts · capture unavailable'; + return 'Artifacts · not recorded for this visit'; + } + var label = 'Artifacts · $recorded recorded'; + if (capture.isPartial) label += ' · partial capture'; + return label; +} + +/// The partial-capture notes, one line per non-zero count and nothing when the +/// capture was complete or had no presented files. An unavailable capture yields +/// no notes because there is no evidence to quantify. +List artifactCaptureNotes(JsonMap step) { + final notes = []; + if (presentedArtifacts(artifactsOf(step)).isEmpty) return notes; + final capture = ArtifactCapture.fromStep(step); + if (capture.skipped > 0) { + notes.add('${capture.skipped} files excluded from artifact capture.'); + } + if (capture.truncated > 0) { + notes.add('${capture.truncated} files omitted by artifact capture limits.'); + } + return notes; +} diff --git a/app/lib/features/artifacts/domain/artifact_url.dart b/app/lib/features/artifacts/domain/artifact_url.dart new file mode 100644 index 00000000..ea16d505 --- /dev/null +++ b/app/lib/features/artifacts/domain/artifact_url.dart @@ -0,0 +1,78 @@ +import '../../../core/transport/server_url.dart'; + +/// A validated artifact url plus whether it points outside the configured +/// server origin. +class ResolvedArtifactUrl { + const ResolvedArtifactUrl({required this.uri, required this.external}); + + final Uri uri; + + /// True when the url's origin differs from the configured server origin (or + /// the configured origin is unusable). A future authenticated fetch must send + /// no cookies, authorization header or other server credentials for an + /// external url. + final bool external; + + String get url => uri.toString(); +} + +const List _unsafePrefixes = ['//', r'\\', r'\/', '/\\']; + +/// Resolves a recorded artifact url for display and opening. +/// +/// A server-relative path (`/artifacts/...`, or a path without the leading +/// slash) resolves against the configured websocket endpoint's http(s) origin, +/// dropping the endpoint path and query. An absolute http(s) url is preserved, +/// including its encoded path and query. Output is always http(s): protocol- +/// relative (`//host`), hostless, credentialed, malformed and non-http(s) urls +/// are rejected with null. A blank or invalid configured endpoint resolves no +/// relative path; it never invents a host. +ResolvedArtifactUrl? resolveArtifactUrl( + String configuredEndpoint, + String artifactUrl, +) { + final raw = artifactUrl.trim(); + if (raw.isEmpty) return null; + for (final prefix in _unsafePrefixes) { + if (raw.startsWith(prefix)) return null; + } + final parsed = Uri.tryParse(raw); + if (parsed == null) return null; + + final configured = _httpOrigin(configuredEndpoint); + if (parsed.hasScheme) { + final scheme = parsed.scheme.toLowerCase(); + if (scheme != 'http' && scheme != 'https') return null; + if (!parsed.hasAuthority || parsed.host.isEmpty) return null; + if (parsed.userInfo.isNotEmpty) return null; + return ResolvedArtifactUrl( + uri: parsed, + external: configured == null || parsed.origin != configured.origin, + ); + } + + if (configured == null) return null; + final relative = raw.startsWith('/') ? raw : '/$raw'; + final resolved = Uri.tryParse('${configured.origin}$relative'); + if (resolved == null) return null; + final scheme = resolved.scheme.toLowerCase(); + if (scheme != 'http' && scheme != 'https') return null; + if (!resolved.hasAuthority || resolved.host.isEmpty) return null; + if (resolved.userInfo.isNotEmpty) return null; + return ResolvedArtifactUrl(uri: resolved, external: false); +} + +/// The http(s) origin of a configured websocket endpoint, or null when the +/// endpoint is blank, malformed, or not a ws/wss url. +Uri? _httpOrigin(String configuredEndpoint) { + try { + final endpoint = ServerUrl.validate(configuredEndpoint); + final http = Uri.parse(endpoint.httpUrl); + final scheme = http.scheme.toLowerCase(); + if (scheme != 'http' && scheme != 'https') return null; + if (http.host.isEmpty) return null; + return Uri.parse(http.origin); + } on FormatException { + return null; + } +} diff --git a/app/lib/features/artifacts/domain/gallery_navigation.dart b/app/lib/features/artifacts/domain/gallery_navigation.dart new file mode 100644 index 00000000..ca115a73 --- /dev/null +++ b/app/lib/features/artifacts/domain/gallery_navigation.dart @@ -0,0 +1,76 @@ +import 'artifact_groups.dart'; +import 'artifact_kind.dart'; +import 'artifact_record.dart'; + +/// One artifact in the viewer's filtered page list, with the stage visit it +/// belongs to. [identity] is the recorded url when there is one; otherwise it is +/// a visit-scoped key so two url-less records never collapse into one page. +class PagedArtifact { + const PagedArtifact({ + required this.stageKey, + required this.visit, + required this.artifact, + required this.pageIndex, + }); + + final String stageKey; + final int visit; + final ArtifactRecord artifact; + + /// Position in the filtered page list. + final int pageIndex; + + String get identity => artifact.hasUrl + ? artifact.url + : '$stageKey\u0000$visit\u0000$pageIndex\u0000${artifact.name}'; +} + +/// The artifacts the viewer can page through, in gallery order: group by group, +/// each group's images, videos and markdown/text documents in recorded order. +/// Other artifacts open externally and are not part of this list. Pure: it only +/// filters and orders records the gallery already holds. +List pagedArtifacts(List groups) { + final pages = []; + for (final group in groups) { + for (final artifact in group.artifacts) { + if (!isViewerArtifact(artifact.contentType, artifact.name)) continue; + pages.add( + PagedArtifact( + stageKey: group.stageKey, + visit: group.visit, + artifact: artifact, + pageIndex: pages.length, + ), + ); + } + } + return List.unmodifiable(pages); +} + +/// Each page's recorded url mapped to its page index, so a tile and the viewer +/// derive from the same ordered list. The first occurrence of a url wins. A +/// record with no recorded url has no fetchable identity and is omitted. +Map viewerIndexByUrl(List groups) { + final indices = {}; + for (final page in pagedArtifacts(groups)) { + if (!page.artifact.hasUrl) continue; + indices.putIfAbsent(page.artifact.url, () => page.pageIndex); + } + return indices; +} + +/// Paging from [current] by [delta] within `count` pages, clamped at both ends +/// so a page never wraps and an empty list is index 0. +int pagedIndex(int current, int delta, int count) { + if (count <= 0) return 0; + final wanted = current + delta; + if (wanted < 0) return 0; + if (wanted >= count) return count - 1; + return wanted; +} + +/// The viewer's position label, e.g. `2 of 5 · image/png`. +String artifactViewerPositionLabel(int index, int count, String contentType) { + final type = contentType.split(';').first.trim(); + return '${index + 1} of $count · ${type.isEmpty ? 'artifact' : type}'; +} diff --git a/app/notes/A1a.md b/app/notes/A1a.md new file mode 100644 index 00000000..c25715f9 --- /dev/null +++ b/app/notes/A1a.md @@ -0,0 +1,101 @@ +# A1a — artifact records, capture facts, grouping, kinds and safe urls + +## What changed + +New nonvisual `artifacts` domain slice. Every file is new; no existing file was +edited. Nothing under `lib/main.dart`, `lib/shell/`, another feature, `pubspec.*`, +`web/`, the Go server or `android/` was touched. No dependency was added and no +network/transport code was written. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/artifacts/domain/artifact_record.dart` | 85 | One recorded artifact: name, url, content type, size and deeply read-only `raw`; retired `session.md` and system names | +| `lib/features/artifacts/domain/artifact_capture.dart` | 63 | Per-step capture availability (`unavailable`/`recorded`), recorded files, skipped and truncated counts | +| `lib/features/artifacts/domain/artifact_selection.dart` | 67 | Record parsing, retired/system/repair filtering (`presented`, `stage`, `system`) | +| `lib/features/artifacts/domain/artifact_groups.dart` | 109 | Group stage artifacts by stage and recorded visit; shared `public/` attribution; per-visit list | +| `lib/features/artifacts/domain/artifact_kind.dart` | 225 | MIME/extension kind vocabulary, labels, markdown/viewer predicates, `humanBytes` | +| `lib/features/artifacts/domain/artifact_summary.dart` | 78 | Run/visit summary and empty wording, partial-capture flag and notes | +| `lib/features/artifacts/domain/gallery_navigation.dart` | 76 | Filtered viewer page order, stable identities, previous/next clamp, position label | +| `lib/features/artifacts/domain/artifact_url.dart` | 78 | Safe http(s) resolution against the configured endpoint and cross-origin marking | +| `test/features/artifacts/domain/artifact_fixtures.dart` | 44 | Local step/artifact fixtures; no fake gateway or socket | +| `test/features/artifacts/domain/artifact_capture_test.dart` | 241 | Unavailable/null/empty/partial capture facts and exact wording | +| `test/features/artifacts/domain/artifact_groups_test.dart` | 308 | Visits, identity, retired/utility files, public attribution, empty states | +| `test/features/artifacts/domain/artifact_selection_test.dart` | 154 | Field preservation, deep immutability, filtering, duplicates | +| `test/features/artifacts/domain/artifact_kind_test.dart` | 110 | Known/unknown MIME and extension classification, markdown/viewer gates, bytes | +| `test/features/artifacts/domain/gallery_navigation_test.dart` | 197 | Filtered order, duplicate urls/names, url-less identities, paging clamp, label | +| `test/features/artifacts/domain/artifact_url_test.dart` | 148 | Relative/absolute urls, wss/https, IPv6, encoded path/query, schemes, credentials, cross-origin | + +## Behaviour (from `web/src/artifacts.js` and `artifactNavigation.js`) + +- **Record facts are verbatim.** `ArtifactRecord.fromJson` reads `name`, `url`, + `content_type`, `size_bytes` and keeps every other server field in a deep + unmodifiable `raw`. A missing url stays `''`; nothing is derived from the name. + Two records with the same name stay distinct because identity is the recorded + url (or a visit-scoped fallback in the viewer). +- **Capture availability is a recorded fact.** An absent, null or non-list + `artifacts` field is `unavailable`; an explicit empty list is a recorded empty + capture. `artifacts_skipped`/`artifacts_truncated` are preserved as counts and + mark a partial capture. Unavailable capture never degrades to "no artifacts" + or "not recorded": the run header says `Artifacts · capture unavailable` + instead of `No artifacts recorded for this run.`, which is the task's explicit + requirement and the one deliberate wording extension beyond the web client. +- **Grouping and identity.** `artifactGroups` keeps first-appearance stage order, + orders each stage's visits by sequence (recorded order on ties), and uses + `displayVisit` from the existing graph domain (`control.visit` when positive, + else position + 1). A step with no presented stage artifact yields no group, so + unavailable/empty captures and utility-only visits never fabricate a visit. + Shared `public/` files are attributed to the first recorded visit; repeated + non-public names in later visits remain separate artifacts. +- **Retired and utility files.** `session.md` is hidden everywhere; `session.html`, + `input.md`, `memory.md`, `output.md` remain system evidence and are excluded + from stage output. Repaired session exports named by `session_export_repairs` + are system evidence too. +- **Kinds.** Image/video come from the content type; audio, PDF, JSON, archive, + spreadsheet, log, code, document then match normalised MIME or extension; + unknown values are `other`/`File`. `isMarkdownArtifact`/`isViewerArtifact` keep + logs, source, CSV and HTML out of the in-app viewer while images, videos and + md/markdown/txt pages enter it. +- **Navigation.** `pagedArtifacts` filters group by group in recorded order; + `viewerIndexByUrl` maps the first occurrence of each url; url-less pages use a + visit-scoped identity; `pagedIndex` clamps with no wrap; the position label + trims content-type parameters and falls back to `artifact`. +- **Safe urls.** Server-relative paths resolve against the configured endpoint's + http(s) origin (endpoint path/query dropped, `wss` → `https`, IPv6 brackets and + percent-encoding kept). Absolute http(s) urls are preserved. Output is always + http(s): blank, protocol-relative, backslash-relative, hostless, credentialed, + malformed and non-http(s) urls return null. A url whose origin differs from the + configured origin is marked `external`, so a future authenticated fetch can + refuse to send cookies or headers; a same-origin url stays internal. + +## Review and quality fixes in this visit + +- `flutter analyze` reported four infos in this slice; all fixed: block braces in + `artifact_summary.dart` and null-aware map entries (`'key': ?value`) in the + test fixtures. Analyze is now clean for the whole app. +- `dart format` found one unformatted test file; all 15 files are now formatted. +- Semantics were re-read against `web/src/artifacts.js` (`presentedArtifacts`, + `stageArtifacts`, `systemArtifacts`, `artifactKind`, `pagedArtifacts`, + `viewerIndexByUrl`, `pagedIndex`, `displayVisit`) and `artifactNavigation.js`. + No other concrete deviation was found, so no behaviour was rewritten. + +## Checks actually run + +``` +flutter test test/features/artifacts/domain # 60 passed +flutter test test/features/graph/domain # 41 passed (stage_visits reuse) +flutter analyze # No issues found! (0.9s) +dart format lib/features/artifacts test/features/artifacts # clean, 15 files +grep trailing whitespace # none +``` + +## Honest limits + +- No gallery screen, viewer, sharing, fetching or transport helper exists in this + slice, so there is no rendered change and no browser capture. The gallery and + viewer are separate future slices. +- No live server, socket, artifact download or real run data was used; tests are + local fixtures and pure functions only. +- Mobile is unverified: no Android/iOS build, emulator, ADB or device was used. +- **Not committed.** The stage instruction forbids commit/push/deploy, so the + candidate is uncommitted in the working tree. The Land stage commits the + reviewed candidate. diff --git a/app/test/features/artifacts/domain/artifact_capture_test.dart b/app/test/features/artifacts/domain/artifact_capture_test.dart new file mode 100644 index 00000000..adf2f01a --- /dev/null +++ b/app/test/features/artifacts/domain/artifact_capture_test.dart @@ -0,0 +1,241 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_capture.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_summary.dart'; + +import 'artifact_fixtures.dart'; + +void main() { + group('capture facts', () { + test('an absent or null artifact field is an unavailable capture', () { + final absent = ArtifactCapture.fromStep(step(includeArtifacts: false)); + final explicitNull = ArtifactCapture.fromStep(step(artifacts: null)); + + expect(absent.availability, ArtifactCaptureAvailability.unavailable); + expect(absent.isAvailable, isFalse); + expect(absent.artifacts, isEmpty); + expect(explicitNull.isAvailable, isFalse); + }); + + test('a malformed artifact field is unavailable, not empty', () { + final capture = ArtifactCapture.fromStep({ + 'artifacts': 'not a list', + }); + expect(capture.isAvailable, isFalse); + expect(capture.artifacts, isEmpty); + }); + + test('an explicitly recorded empty list is an available empty capture', () { + final capture = ArtifactCapture.fromStep(step(artifacts: const [])); + expect(capture.availability, ArtifactCaptureAvailability.recorded); + expect(capture.isAvailable, isTrue); + expect(capture.artifacts, isEmpty); + expect(capture.isPartial, isFalse); + }); + + test('records the skipped and truncated counts as capture facts', () { + final capture = ArtifactCapture.fromStep( + step( + artifacts: >[artifact('shot.png')], + skipped: 4, + truncated: 7, + ), + ); + expect(capture.artifacts.length, 1); + expect(capture.skipped, 4); + expect(capture.truncated, 7); + expect(capture.isPartial, isTrue); + expect( + ArtifactCapture.fromStep(step(artifacts: const [])).isPartial, + isFalse, + ); + }); + }); + + group('run and visit wording', () { + test('a running or unavailable capture never claims no artifacts', () { + expect( + artifactsSummary(step(status: 'running', artifacts: null)), + 'Artifacts · capture pending', + ); + expect( + artifactsSummary(step(status: 'running', artifacts: const [])), + 'Artifacts · capture pending', + ); + expect( + artifactsSummary(step(status: 'completed', artifacts: null)), + 'Artifacts · capture unavailable', + ); + expect( + artifactsSummary(step(status: 'completed', includeArtifacts: false)), + 'Artifacts · capture unavailable', + ); + }); + + test( + 'a finished available empty capture says not recorded for this visit', + () { + expect( + artifactsSummary(step(status: 'completed', artifacts: const [])), + 'Artifacts · not recorded for this visit', + ); + }, + ); + + test('counts presented stage artifacts and flags partial capture', () { + final full = step( + artifacts: >[ + artifact('a.png'), + artifact('b.png'), + artifact('input.md'), + artifact('session.md'), + ], + truncated: 1, + ); + expect( + artifactsSummary(full), + 'Artifacts · 2 recorded · partial capture', + ); + expect( + artifactsSummary( + step(artifacts: >[artifact('a.png')]), + ), + 'Artifacts · 1 recorded', + ); + }); + + test( + 'capture notes use the exact web wording and stay silent otherwise', + () { + final partial = step( + artifacts: >[artifact('a.png')], + skipped: 4, + truncated: 7, + ); + expect(artifactCaptureNotes(partial), [ + '4 files excluded from artifact capture.', + '7 files omitted by artifact capture limits.', + ]); + expect( + artifactCaptureNotes( + step( + artifacts: >[artifact('a.png')], + skipped: 2, + ), + ), + ['2 files excluded from artifact capture.'], + ); + expect( + artifactCaptureNotes( + step(artifacts: >[artifact('a.png')]), + ), + isEmpty, + ); + expect( + artifactCaptureNotes(step(artifacts: const [], skipped: 4)), + isEmpty, + ); + expect( + artifactCaptureNotes(step(includeArtifacts: false, skipped: 4)), + isEmpty, + ); + }, + ); + + test('the run empty message keeps the web running wording', () { + expect(artifactsEmptyMessage(true), 'Artifacts · capture pending'); + expect( + artifactsEmptyMessage(false), + 'No artifacts recorded for this run.', + ); + expect( + artifactsHeader(const [], executing: true), + 'Artifacts · capture pending', + ); + }); + + test( + 'an unavailable run capture is not reported as no recorded artifacts', + () { + final steps = >[ + step(stage: 'planner', sequence: 1, artifacts: null), + step(stage: 'build', sequence: 2, artifacts: const []), + ]; + expect( + artifactsHeader(steps, executing: false), + 'Artifacts · capture unavailable', + ); + }, + ); + + test('a fully available empty run says no artifacts were recorded', () { + final steps = >[ + step(stage: 'planner', sequence: 1, artifacts: const []), + step(stage: 'build', sequence: 2, artifacts: const []), + ]; + expect( + artifactsHeader(steps, executing: false), + 'No artifacts recorded for this run.', + ); + }); + + test( + 'the run header counts exactly the gallery tiles, singular for one', + () { + final one = >[ + step(artifacts: >[artifact('one.png')]), + ]; + expect(artifactsHeader(one, executing: false), 'Artifact · 1 recorded'); + + final four = >[ + step( + stage: 'planner', + sequence: 1, + artifacts: >[ + artifact('a.png'), + artifact('session.md'), + ], + ), + step( + stage: 'build', + sequence: 2, + artifacts: >[ + artifact('b.png'), + artifact('c.png'), + artifact('d.png'), + ], + ), + ]; + expect( + artifactsHeader(four, executing: false), + 'Artifacts · 4 recorded', + ); + expect(four, isNotEmpty); + }, + ); + + test('partial capture is flagged on the run header', () { + final steps = >[ + step(artifacts: >[artifact('a.png')], skipped: 2), + ]; + expect( + artifactsHeader(steps, executing: false), + 'Artifact · 1 recorded · partial capture', + ); + }); + + test('a visit that recorded only the retired session.md has no tile', () { + final steps = >[ + step(artifacts: >[artifact('session.md')]), + ]; + expect( + artifactsHeader(steps, executing: false), + 'No artifacts recorded for this run.', + ); + expect( + artifactsSummary(steps.first), + 'Artifacts · not recorded for this visit', + ); + expect(artifactCaptureNotes(steps.first), isEmpty); + }); + }); +} diff --git a/app/test/features/artifacts/domain/artifact_fixtures.dart b/app/test/features/artifacts/domain/artifact_fixtures.dart new file mode 100644 index 00000000..04c26bd5 --- /dev/null +++ b/app/test/features/artifacts/domain/artifact_fixtures.dart @@ -0,0 +1,44 @@ +import 'package:pipelines_app/core/api_gateway.dart'; + +/// A minimal recorded [stage artifact], named so tests read like the web +/// client's fixtures. Every field the server records is present. +JsonMap artifact( + String name, { + String? url, + String contentType = '', + int sizeBytes = 0, + Map extra = const {}, +}) { + return { + 'name': name, + 'url': url ?? '/artifacts/1/1/$name', + 'content_type': contentType, + 'size_bytes': sizeBytes, + ...extra, + }; +} + +/// A minimal recorded step. [includeArtifacts] false omits the field entirely +/// (an unavailable capture); a null [artifacts] records an explicit null. +JsonMap step({ + String stage = 'review', + int sequence = 1, + String status = 'completed', + int visit = 1, + List? artifacts, + bool includeArtifacts = true, + int? skipped, + int? truncated, + List? repairs, +}) { + return { + 'stage': stage, + 'sequence': sequence, + 'status': status, + 'control': {'visit': visit}, + if (includeArtifacts) 'artifacts': artifacts, + 'artifacts_skipped': ?skipped, + 'artifacts_truncated': ?truncated, + 'session_export_repairs': ?repairs, + }; +} diff --git a/app/test/features/artifacts/domain/artifact_groups_test.dart b/app/test/features/artifacts/domain/artifact_groups_test.dart new file mode 100644 index 00000000..cf7173f6 --- /dev/null +++ b/app/test/features/artifacts/domain/artifact_groups_test.dart @@ -0,0 +1,308 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_groups.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_selection.dart'; + +import 'artifact_fixtures.dart'; + +void main() { + group('grouping', () { + test('groups interleaved steps by stage then recorded visit', () { + final steps = >[ + step( + stage: 'planner', + sequence: 1, + visit: 1, + artifacts: >[artifact('a.png')], + ), + step( + stage: 'build', + sequence: 2, + visit: 1, + artifacts: >[artifact('b.png')], + ), + step( + stage: 'planner', + sequence: 3, + visit: 2, + artifacts: >[artifact('c.png')], + ), + ]; + + final groups = artifactGroups(steps); + expect( + groups.map((group) => '${group.stageKey}/${group.visit}'), + ['planner/1', 'planner/2', 'build/1'], + ); + expect(groups.first.artifacts.map((record) => record.name), [ + 'a.png', + ]); + }); + + test('repeated stage visits stay separate and ordered by sequence', () { + final steps = >[ + step( + stage: 'review', + sequence: 7, + visit: 2, + artifacts: >[artifact('second.md')], + ), + step( + stage: 'review', + sequence: 3, + visit: 1, + artifacts: >[artifact('first.md')], + ), + ]; + + final groups = artifactGroups(steps); + expect(groups.map((group) => group.visit), [1, 2]); + expect(groups.map((group) => group.artifacts.single.name), [ + 'first.md', + 'second.md', + ]); + }); + + test( + 'a display visit is control.visit when positive, else position + 1', + () { + final steps = >[ + step( + stage: 's', + sequence: 1, + visit: 0, + artifacts: >[artifact('a')], + ), + step( + stage: 's', + sequence: 2, + visit: 0, + artifacts: >[artifact('b')], + ), + ]; + expect(artifactGroups(steps).map((group) => group.visit), [1, 2]); + }, + ); + + test('equal sequences keep recorded order', () { + final steps = >[ + step( + stage: 's', + sequence: 1, + visit: 1, + artifacts: >[artifact('first')], + ), + step( + stage: 's', + sequence: 1, + visit: 2, + artifacts: >[artifact('second')], + ), + ]; + expect( + artifactGroups(steps).map((group) => group.artifacts.single.name), + ['first', 'second'], + ); + }); + + test('an absent stage visit is not fabricated', () { + final steps = >[ + step( + stage: 'a', + sequence: 1, + artifacts: >[artifact('a.png')], + ), + ]; + final groups = artifactGroups(steps); + expect(groups.single.stageKey, 'a'); + expect(groups.any((group) => group.stageKey == 'b'), isFalse); + }); + }); + + group('identity', () { + test('the same file name in different visits remains two groups', () { + final steps = >[ + step( + stage: 'implementer', + sequence: 1, + visit: 1, + artifacts: >[ + artifact('report.md', url: '/artifacts/1/1/report.md'), + ], + ), + step( + stage: 'implementer', + sequence: 2, + visit: 2, + artifacts: >[ + artifact('report.md', url: '/artifacts/1/2/report.md'), + ], + ), + ]; + final groups = artifactGroups(steps); + expect(groups.length, 2); + expect(groups.map((group) => group.artifacts.single.url), [ + '/artifacts/1/1/report.md', + '/artifacts/1/2/report.md', + ]); + }); + + test('duplicate names in one visit are kept with their recorded urls', () { + final steps = >[ + step( + stage: 's', + sequence: 1, + artifacts: >[ + artifact('shot.png', url: '/artifacts/1/1/shot-a.png'), + artifact('shot.png', url: '/artifacts/1/1/shot-b.png'), + ], + ), + ]; + final artifacts = artifactGroups(steps).single.artifacts; + expect(artifacts.length, 2); + expect(artifacts.map((record) => record.url), [ + '/artifacts/1/1/shot-a.png', + '/artifacts/1/1/shot-b.png', + ]); + }); + + test('the retired session.md is hidden but session.html is retained', () { + final steps = >[ + step( + stage: 's', + sequence: 1, + artifacts: >[ + artifact('session.md'), + artifact('session.html'), + artifact('report.md'), + ], + ), + ]; + // session.html is retained as system evidence, but neither it nor the + // retired session.md is stage output, so the gallery shows only the report. + expect( + artifactGroups(steps).single.artifacts.map((record) => record.name), + ['report.md'], + ); + expect( + systemArtifacts(steps.single).map((record) => record.name), + ['session.html'], + ); + }); + }); + + group('shared public files', () { + test('a public file is attributed to the visit that first recorded it', () { + final steps = >[ + step( + stage: 'a', + sequence: 1, + artifacts: >[ + artifact('input.md'), + artifact('public/a.txt'), + ], + ), + step( + stage: 'b', + sequence: 2, + artifacts: >[ + artifact('output.md'), + artifact('public/a.txt'), + artifact('public/b.txt'), + ], + ), + ]; + final groups = artifactGroups(steps); + expect( + groups.map( + (group) => group.artifacts.map((record) => record.name).toList(), + ), + >[ + ['public/a.txt'], + ['public/b.txt'], + ], + ); + expect( + visitArtifacts(steps[1], steps).map((record) => record.name), + ['public/b.txt'], + ); + }); + + test( + 'visitArtifacts keeps a repeated non-public name in a later visit', + () { + final steps = >[ + step( + stage: 'a', + sequence: 1, + artifacts: >[ + artifact('report.md', url: '/artifacts/1/1/report.md'), + ], + ), + step( + stage: 'a', + sequence: 2, + artifacts: >[ + artifact('report.md', url: '/artifacts/1/2/report.md'), + ], + ), + ]; + expect( + visitArtifacts(steps[1], steps).map((record) => record.url), + ['/artifacts/1/2/report.md'], + ); + }, + ); + + test('a public file repeated inside one visit is recorded once', () { + final steps = >[ + step( + stage: 'a', + sequence: 1, + artifacts: >[ + artifact('public/a.txt'), + artifact('public/a.txt'), + ], + ), + ]; + expect(artifactGroups(steps).single.artifacts.length, 1); + }); + }); + + group('unavailable and empty captures', () { + test('unavailable, null and empty visits yield no group', () { + final steps = >[ + step(stage: 'a', sequence: 1, includeArtifacts: false), + step(stage: 'a', sequence: 2, artifacts: null), + step(stage: 'a', sequence: 3, artifacts: const []), + step( + stage: 'b', + sequence: 4, + artifacts: >[artifact('only.png')], + ), + ]; + final groups = artifactGroups(steps); + expect(groups.length, 1); + expect(groups.single.stageKey, 'b'); + expect(groups.single.visit, 1); + }); + + test('a visit with only utility or retired files yields no group', () { + final steps = >[ + step( + stage: 'a', + sequence: 1, + artifacts: >[ + artifact('input.md'), + artifact('session.md'), + artifact('session.html'), + ], + ), + ]; + expect(artifactGroups(steps), isEmpty); + }); + + test('an empty run yields no groups', () { + expect(artifactGroups(const []), isEmpty); + }); + }); +} diff --git a/app/test/features/artifacts/domain/artifact_kind_test.dart b/app/test/features/artifacts/domain/artifact_kind_test.dart new file mode 100644 index 00000000..a95ccfab --- /dev/null +++ b/app/test/features/artifacts/domain/artifact_kind_test.dart @@ -0,0 +1,110 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_kind.dart'; + +void main() { + test('classifies images and videos from their recorded content type', () { + expect(artifactKind('image/png', 'shot.png'), ArtifactKind.image); + expect( + artifactKind('image/svg+xml; charset=utf-8', 'plot'), + ArtifactKind.image, + ); + expect(artifactKind('video/mp4', 'clip.mp4'), ArtifactKind.video); + }); + + test('matches the web client file-kind vocabulary by MIME and name', () { + const cases = <(String, String, ArtifactKind)>[ + ('audio/mpeg', 'sound.mp3', ArtifactKind.audio), + ('application/pdf', 'report', ArtifactKind.pdf), + ('application/octet-stream', 'data.pdf', ArtifactKind.pdf), + ('application/json', 'payload', ArtifactKind.json), + ('text/plain', 'config.json', ArtifactKind.json), + ('application/zip', 'bundle', ArtifactKind.archive), + ('text/plain', 'backup.tar.gz', ArtifactKind.archive), + ('text/csv', 'rows', ArtifactKind.spreadsheet), + ('application/octet-stream', 'sheet.xlsx', ArtifactKind.spreadsheet), + ('text/plain', 'run.log', ArtifactKind.log), + ('application/xml', 'layout', ArtifactKind.code), + ('text/plain', 'main.go', ArtifactKind.code), + ('text/html; charset=utf-8', 'session.html', ArtifactKind.document), + ('text/plain', 'notes.txt', ArtifactKind.document), + ('application/octet-stream', 'blob.bin', ArtifactKind.other), + ('', '', ArtifactKind.other), + ('application/x-unknown-thing', 'report.unknownext', ArtifactKind.other), + ]; + for (final (contentType, name, kind) in cases) { + expect( + artifactKind(contentType, name), + kind, + reason: '$contentType $name', + ); + } + }); + + test('names every kind in prose, with File as the unknown fallback', () { + expect(artifactKindLabel(ArtifactKind.image), 'Image'); + expect(artifactKindLabel(ArtifactKind.video), 'Video'); + expect(artifactKindLabel(ArtifactKind.audio), 'Audio'); + expect(artifactKindLabel(ArtifactKind.pdf), 'PDF'); + expect(artifactKindLabel(ArtifactKind.json), 'JSON'); + expect(artifactKindLabel(ArtifactKind.archive), 'Archive'); + expect(artifactKindLabel(ArtifactKind.spreadsheet), 'Spreadsheet'); + expect(artifactKindLabel(ArtifactKind.log), 'Log'); + expect(artifactKindLabel(ArtifactKind.code), 'Code'); + expect(artifactKindLabel(ArtifactKind.document), 'Document'); + expect(artifactKindLabel(ArtifactKind.other), 'File'); + }); + + test('formats recorded bytes like the web client', () { + expect(humanBytes(0), '0 B'); + expect(humanBytes(999), '999 B'); + expect(humanBytes(1024), '1.0 KiB'); + expect(humanBytes(1536), '1.5 KiB'); + expect(humanBytes(2 * 1024 * 1024), '2.0 MiB'); + expect(humanBytes(3 * 1024 * 1024 * 1024), '3.0 GiB'); + }); + + test('markdown and viewer artifacts use the shared classification', () { + const markdown = <(String, String)>[ + ('text/markdown', 'plan'), + ('text/markdown; charset=utf-8', 'plan'), + ('text/plain', 'notes'), + ('application/octet-stream', 'input.md'), + ('', 'memory.markdown'), + ('', 'output.txt'), + ]; + for (final (contentType, name) in markdown) { + expect(isMarkdownArtifact(contentType, name), isTrue, reason: name); + } + for (final (contentType, name) in <(String, String)>[ + ('text/html', 'session.html'), + ('text/csv', 'rows.csv'), + ('application/json', 'payload.json'), + ('text/x-python', 'main.py'), + ('application/xml', 'shot.png.xml'), + ('', ''), + ]) { + expect(isMarkdownArtifact(contentType, name), isFalse, reason: name); + } + + for (final (contentType, name) in <(String, String)>[ + ('image/png', 'shot.png'), + ('video/mp4', 'clip.mp4'), + ('text/markdown', 'input.md'), + ('text/plain', 'memory.txt'), + ('', 'output.md'), + ]) { + expect(isViewerArtifact(contentType, name), isTrue, reason: name); + } + for (final (contentType, name) in <(String, String)>[ + ('text/html', 'session.html'), + ('text/csv', 'rows.csv'), + ('application/json', 'payload.json'), + ('text/x-python', 'main.py'), + ('text/plain', 'run.log'), + ('application/octet-stream', 'blob.bin'), + ('', ''), + ]) { + expect(isViewerArtifact(contentType, name), isFalse, reason: name); + } + }); +} diff --git a/app/test/features/artifacts/domain/artifact_selection_test.dart b/app/test/features/artifacts/domain/artifact_selection_test.dart new file mode 100644 index 00000000..d65bdcb7 --- /dev/null +++ b/app/test/features/artifacts/domain/artifact_selection_test.dart @@ -0,0 +1,154 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_selection.dart'; + +import 'artifact_fixtures.dart'; + +void main() { + group('record preservation', () { + test('keeps size, content type, url and unknown fields verbatim', () { + final recorded = ArtifactRecord.fromJson( + artifact( + 'shot.png', + url: '/artifacts/7/3/shot.png', + contentType: 'image/png', + sizeBytes: 1536, + extra: { + 'sha256': 'abc', + 'capture': {'source': 'stage'}, + }, + ), + ); + + expect(recorded.name, 'shot.png'); + expect(recorded.url, '/artifacts/7/3/shot.png'); + expect(recorded.contentType, 'image/png'); + expect(recorded.sizeBytes, 1536); + expect(recorded.raw['sha256'], 'abc'); + expect((recorded.raw['capture'] as Map)['source'], 'stage'); + }); + + test('never invents a missing name, url, type or size', () { + final recorded = ArtifactRecord.fromJson(const {}); + expect(recorded.name, ''); + expect(recorded.url, ''); + expect(recorded.contentType, ''); + expect(recorded.sizeBytes, 0); + expect(recorded.hasUrl, isFalse); + }); + + test('the raw record is read-only, including nested values', () { + final recorded = ArtifactRecord.fromJson( + artifact( + 'a.txt', + extra: { + 'nested': {'x': 1}, + }, + ), + ); + expect( + () => recorded.raw['nested'] = {}, + throwsUnsupportedError, + ); + expect( + () => (recorded.raw['nested'] as Map)['x'] = 2, + throwsUnsupportedError, + ); + }); + }); + + group('retired and utility files', () { + test( + 'hides session.md from presented artifacts but keeps session.html', + () { + final records = [ + ArtifactRecord.fromJson(artifact('shot.png')), + ArtifactRecord.fromJson(artifact(legacySessionMarkdownArtifact)), + ArtifactRecord.fromJson(artifact('session.html')), + ]; + + expect( + presentedArtifacts(records).map((record) => record.name), + ['shot.png', 'session.html'], + ); + }, + ); + + test('utility files are system evidence, not stage output', () { + expect(systemArtifactNames, [ + 'input.md', + 'memory.md', + 'output.md', + 'session.html', + ]); + for (final name in systemArtifactNames) { + expect(isSystemArtifactName(name), isTrue, reason: name); + } + expect(isSystemArtifactName('public/input.md'), isFalse); + expect(isSystemArtifactName('session.md'), isFalse); + expect(isSystemArtifactName('shot.png'), isFalse); + }); + + test('stage artifacts exclude utility files and repair exports', () { + final recorded = step( + artifacts: [ + artifact('input.md'), + artifact('memory.md'), + artifact('output.md'), + artifact('session.html'), + artifact('repaired.html'), + artifact('public/input.md'), + artifact('shot.png'), + ].cast>(), + repairs: >[ + {'html': 'repaired.html'}, + ], + ); + + expect(stageArtifacts(recorded).map((record) => record.name), [ + 'public/input.md', + 'shot.png', + ]); + expect(systemArtifacts(recorded).map((record) => record.name), [ + 'input.md', + 'memory.md', + 'output.md', + 'session.html', + 'repaired.html', + ]); + }); + + test('a missing or malformed artifact list records no artifacts', () { + expect(artifactsOf(step(includeArtifacts: false)), isEmpty); + expect(artifactsOf(step(artifacts: null)), isEmpty); + expect(artifactsOf(step(artifacts: const [])), isEmpty); + expect( + artifactsOf({'artifacts': 'not a list'}), + isEmpty, + ); + }); + + test('duplicate names are records, not identities to dedupe', () { + final records = [ + ArtifactRecord.fromJson( + artifact('shot.png', url: '/artifacts/1/1/a.png'), + ), + ArtifactRecord.fromJson( + artifact('shot.png', url: '/artifacts/1/1/b.png'), + ), + ]; + expect( + stageArtifacts( + step( + artifacts: >[ + artifact('shot.png', url: '/artifacts/1/1/a.png'), + artifact('shot.png', url: '/artifacts/1/1/b.png'), + ], + ), + ).map((record) => record.url), + ['/artifacts/1/1/a.png', '/artifacts/1/1/b.png'], + ); + expect(records.length, 2); + }); + }); +} diff --git a/app/test/features/artifacts/domain/artifact_url_test.dart b/app/test/features/artifacts/domain/artifact_url_test.dart new file mode 100644 index 00000000..e7d9a961 --- /dev/null +++ b/app/test/features/artifacts/domain/artifact_url_test.dart @@ -0,0 +1,148 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_url.dart'; + +void main() { + group('server-relative paths', () { + test( + 'resolve against the configured endpoint origin, dropping its path', + () { + final resolved = resolveArtifactUrl( + 'ws://example.test:8081/connect?token=x', + '/artifacts/a%20b?download=1', + ); + expect(resolved, isNotNull); + expect( + resolved!.uri.toString(), + 'http://example.test:8081/artifacts/a%20b?download=1', + ); + expect(resolved.external, isFalse); + }, + ); + + test('map wss to https and omit the default port', () { + final resolved = resolveArtifactUrl( + 'wss://example.test/connect', + 'artifacts/shot.png', + ); + expect( + resolved!.uri.toString(), + 'https://example.test/artifacts/shot.png', + ); + expect(resolved.external, isFalse); + }); + + test('keep IPv6 brackets and encoded paths intact', () { + final resolved = resolveArtifactUrl( + 'ws://[::1]:8081/connect', + '/artifacts/a%2Fb?next=%2Fnext', + ); + expect( + resolved!.uri.toString(), + 'http://[::1]:8081/artifacts/a%2Fb?next=%2Fnext', + ); + expect(resolved.uri.host, '::1'); + }); + + test('a blank endpoint leaves a relative artifact unresolved', () { + expect(resolveArtifactUrl('', '/artifacts/a'), isNull); + expect(resolveArtifactUrl('not a url', '/artifacts/a'), isNull); + expect( + resolveArtifactUrl('https://example.test', '/artifacts/a'), + isNull, + ); + }); + }); + + group('absolute http(s) artifacts', () { + test('a same-origin absolute url stays internal', () { + final resolved = resolveArtifactUrl( + 'ws://example.test:8081/connect', + 'http://example.test:8081/artifacts/a%20b?download=1', + ); + expect( + resolved!.uri.toString(), + 'http://example.test:8081/artifacts/a%20b?download=1', + ); + expect(resolved.external, isFalse); + }); + + test('cross-host, cross-port and cross-scheme urls are external', () { + const configured = 'wss://example.test/connect'; + for (final url in [ + 'https://cdn.test/artifacts/a', + 'https://example.test:8443/artifacts/a', + 'http://example.test/artifacts/a', + ]) { + final resolved = resolveArtifactUrl(configured, url); + expect(resolved, isNotNull, reason: url); + expect(resolved!.external, isTrue, reason: url); + } + }); + + test('an absolute url without a usable configured origin is external', () { + final resolved = resolveArtifactUrl('', 'https://cdn.test/a%2Fb?q=1'); + expect(resolved!.uri.toString(), 'https://cdn.test/a%2Fb?q=1'); + expect(resolved.external, isTrue); + }); + }); + + group('unsafe urls', () { + test('rejects blank, protocol-relative and hostless urls', () { + for (final url in [ + '', + ' ', + '//evil.test/artifacts/a', + 'http:///artifacts/a', + 'http://', + 'https://?x=1', + ]) { + expect( + resolveArtifactUrl('ws://example.test:8081', url), + isNull, + reason: url, + ); + } + }); + + test('rejects credentials in any absolute url', () { + for (final url in [ + 'http://user:pass@example.test/artifacts/a', + 'https://user@example.test/artifacts/a', + 'http://example.test:8081@evil.test/artifacts/a', + ]) { + expect( + resolveArtifactUrl('ws://example.test:8081', url), + isNull, + reason: url, + ); + } + }); + + test('rejects unsafe and non-http schemes', () { + for (final url in [ + 'javascript:alert(1)', + 'data:text/html,hello', + 'file:///etc/passwd', + 'ftp://example.test/a', + 'intent://example.test/a#Intent;end', + 'mailto:ops@example.test', + ]) { + expect( + resolveArtifactUrl('ws://example.test:8081', url), + isNull, + reason: url, + ); + } + }); + + test('never produces a non-http(s) output', () { + final resolved = resolveArtifactUrl( + 'ws://example.test:8081/connect', + '/artifacts/a', + ); + expect(resolved!.uri.scheme, 'http'); + expect(resolved.uri.hasAuthority, isTrue); + expect(resolved.uri.userInfo, isEmpty); + }); + }); +} diff --git a/app/test/features/artifacts/domain/gallery_navigation_test.dart b/app/test/features/artifacts/domain/gallery_navigation_test.dart new file mode 100644 index 00000000..af8b72ed --- /dev/null +++ b/app/test/features/artifacts/domain/gallery_navigation_test.dart @@ -0,0 +1,197 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_groups.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart'; +import 'package:pipelines_app/features/artifacts/domain/gallery_navigation.dart'; + +import 'artifact_fixtures.dart'; + +ArtifactRecord record(String name, {String contentType = '', String? url}) => + ArtifactRecord.fromJson(artifact(name, contentType: contentType, url: url)); + +void main() { + group('filtered gallery order', () { + test('pages viewer artifacts group by group, in recorded order', () { + final groups = [ + ArtifactGroup( + stageKey: 'reviewer', + visit: 1, + artifacts: [ + record('session.html', contentType: 'text/html'), + record('input.md', contentType: 'text/markdown'), + ], + ), + ArtifactGroup( + stageKey: 'implementer', + visit: 2, + artifacts: [ + record('run.log', contentType: 'text/plain'), + record('shot.png', contentType: 'image/png'), + record('main.py', contentType: 'text/x-python'), + record('clip.mp4', contentType: 'video/mp4'), + record('memory.txt', contentType: 'text/plain'), + record('rows.csv', contentType: 'text/csv'), + record('output.md', contentType: 'application/octet-stream'), + ], + ), + ]; + + expect(pagedArtifacts(groups).map((page) => page.artifact.name), [ + 'input.md', + 'shot.png', + 'clip.mp4', + 'memory.txt', + 'output.md', + ]); + expect(pagedArtifacts(const []), isEmpty); + }); + + test('a page keeps the stage visit it belongs to', () { + final groups = artifactGroups(>[ + step( + stage: 'a', + sequence: 1, + visit: 3, + artifacts: >[ + artifact('a.png', contentType: 'image/png'), + ], + ), + step( + stage: 'b', + sequence: 2, + visit: 5, + artifacts: >[ + artifact('b.png', contentType: 'image/png'), + ], + ), + ]); + final pages = pagedArtifacts(groups); + expect(pages.map((page) => '${page.stageKey}/${page.visit}'), [ + 'a/3', + 'b/5', + ]); + expect(pages.map((page) => page.pageIndex), [0, 1]); + }); + }); + + group('identity', () { + test('duplicate names with different urls get distinct viewer indices', () { + final groups = artifactGroups(>[ + step( + stage: 'a', + sequence: 1, + visit: 1, + artifacts: >[ + artifact( + 'shot.png', + url: '/artifacts/1/1/shot.png', + contentType: 'image/png', + ), + ], + ), + step( + stage: 'a', + sequence: 2, + visit: 2, + artifacts: >[ + artifact( + 'shot.png', + url: '/artifacts/1/2/shot.png', + contentType: 'image/png', + ), + ], + ), + ]); + final index = viewerIndexByUrl(groups); + expect(index, { + '/artifacts/1/1/shot.png': 0, + '/artifacts/1/2/shot.png': 1, + }); + expect(pagedArtifacts(groups).map((page) => page.identity), [ + '/artifacts/1/1/shot.png', + '/artifacts/1/2/shot.png', + ]); + }); + + test('a repeated url maps to its first occurrence only', () { + final groups = artifactGroups(>[ + step( + stage: 'a', + sequence: 1, + artifacts: >[ + artifact( + 'a.png', + url: '/artifacts/1/1/a.png', + contentType: 'image/png', + ), + artifact( + 'a.png', + url: '/artifacts/1/1/a.png', + contentType: 'image/png', + ), + ], + ), + ]); + final index = viewerIndexByUrl(groups); + expect(index, {'/artifacts/1/1/a.png': 0}); + expect(pagedArtifacts(groups).length, 2); + }); + + test('artifacts without a url keep distinct fallback identities', () { + final groups = artifactGroups(>[ + step( + stage: 'a', + sequence: 1, + visit: 2, + artifacts: >[ + artifact('shot.png', url: '', contentType: 'image/png'), + artifact('shot.png', url: '', contentType: 'image/png'), + ], + ), + ]); + final pages = pagedArtifacts(groups); + expect(pages.map((page) => page.identity).toSet().length, 2); + expect(viewerIndexByUrl(groups), isEmpty); + }); + + test('non-viewer artifacts never get a viewer identity', () { + final groups = artifactGroups(>[ + step( + stage: 'a', + sequence: 1, + artifacts: >[ + artifact('session.html', contentType: 'text/html'), + artifact('main.py', contentType: 'text/x-python'), + artifact('run.log', contentType: 'text/plain'), + ], + ), + ]); + expect(pagedArtifacts(groups), isEmpty); + expect(viewerIndexByUrl(groups), isEmpty); + }); + }); + + group('paging', () { + test('previous and next clamp at both ends without wrapping', () { + expect(pagedIndex(0, -1, 3), 0); + expect(pagedIndex(1, -1, 3), 0); + expect(pagedIndex(1, 1, 3), 2); + expect(pagedIndex(2, 1, 3), 2); + expect(pagedIndex(0, 0, 0), 0); + expect(pagedIndex(0, 0, 1), 0); + expect(pagedIndex(9, -3, 0), 0); + }); + + test('the position label trims the content type and falls back', () { + expect( + artifactViewerPositionLabel(0, 3, 'image/png'), + '1 of 3 · image/png', + ); + expect( + artifactViewerPositionLabel(1, 3, 'image/png; charset=binary'), + '2 of 3 · image/png', + ); + expect(artifactViewerPositionLabel(4, 5, ''), '5 of 5 · artifact'); + expect(artifactViewerPositionLabel(0, 1, ' '), '1 of 1 · artifact'); + }); + }); +} From 49783b04ab04841fd891ef206729e03aa7bf48e5 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 16:57:11 +0100 Subject: [PATCH 61/84] docs(app): record A1a candidate commit and main merge --- app/notes/A1a.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/notes/A1a.md b/app/notes/A1a.md index c25715f9..2d5802e1 100644 --- a/app/notes/A1a.md +++ b/app/notes/A1a.md @@ -96,6 +96,6 @@ grep trailing whitespace # none - No live server, socket, artifact download or real run data was used; tests are local fixtures and pure functions only. - Mobile is unverified: no Android/iOS build, emulator, ADB or device was used. -- **Not committed.** The stage instruction forbids commit/push/deploy, so the - candidate is uncommitted in the working tree. The Land stage commits the - reviewed candidate. +- **Committed by the Land stage** as `ff0f812` on `flutter/a1-data` and merged + with `main` in `a303368`; the checks above were re-run on the merged candidate. + This stage did not merge into `main`, push or deploy. From ceffd5d0d1e150548abd4f8c01cb1da5f3adfee5 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 16:59:07 +0100 Subject: [PATCH 62/84] fix(stage): retain inline audit payloads once without losing native evidence --- .../session-export-inline-attachments.md | 26 +++++++ internal/stage/session_export.go | 21 +++++- internal/stage/session_export_inline_test.go | 68 +++++++++++++++++++ 3 files changed, 113 insertions(+), 2 deletions(-) create mode 100644 docs/notes/session-export-inline-attachments.md create mode 100644 internal/stage/session_export_inline_test.go diff --git a/docs/notes/session-export-inline-attachments.md b/docs/notes/session-export-inline-attachments.md new file mode 100644 index 00000000..4c03d10e --- /dev/null +++ b/docs/notes/session-export-inline-attachments.md @@ -0,0 +1,26 @@ +# Complete visual audit exports without duplicate inline payloads + +Run34 visit3 retained a complete, untruncated native session (71 messages, +4,196,297 decoded native bytes), but the HTML audit exceeded the8MiB render cap. +The readable tool projection printed47 inline `data:` attachment URIs as text, +duplicating3,752,634 bytes already stored in complete native message records. + +The renderer now summarizes an inline attachment in the readable projection +ONLY when its exact URI bytes also occur in that message's retained native +record. The complete native JSON remains unchanged and HTML-escaped. If the +native record is absent or does not contain the payload, the original full +projection is kept; there is no evidence loss or fabricated completeness. + +No source/render/artifact bound is raised. All remain at their existing limits, +and genuinely oversized exports still report partial/truncated. No HTML is +executed from the attachment; MIME labels and native data stay escaped. + +Read-only scratch export of the exact original visual-review session now +produces4,676,544 bytes,71 messages, `truncated:false`. Production originals and +checkpoints were not overwritten by this proof. + +Regressions cover a4MiB inline payload retained exactly once, fallback when no +native copy exists, and escaped/unescaped hostile native JSON/MIME values. The +full Go suite passes with the unrelated notification-test URL env isolated. +Installation remains deferred until a quiescent service window; no active run +may be interrupted just to activate this correction. diff --git a/internal/stage/session_export.go b/internal/stage/session_export.go index 2c752c5c..f7562b2d 100644 --- a/internal/stage/session_export.go +++ b/internal/stage/session_export.go @@ -262,7 +262,11 @@ func renderHTMLMessage(out *bytes.Buffer, index int, message opencode.ExportedMe fmt.Fprintf(out, "

id: %s | model: %s | agent: %s | created_at: %d

\n", html.EscapeString(message.ID), html.EscapeString(message.Model), html.EscapeString(message.Agent), message.CreatedAt) for _, part := range message.Parts { - renderHTMLPart(out, part) + if part.Type == protocol.ChatPartTool { + renderHTMLToolWithNativeRecord(out, part, message.Raw) + } else { + renderHTMLPart(out, part) + } } // The readable projection is not the complete native record: tools can // carry inline images and provider-specific metadata absent from ChatPart. @@ -297,6 +301,10 @@ func renderHTMLPart(out *bytes.Buffer, part opencode.ExportedPart) { // renderHTMLTool renders a tool call with its name, status, input, result and // error, escaping every value. func renderHTMLTool(out *bytes.Buffer, part opencode.ExportedPart) { + renderHTMLToolWithNativeRecord(out, part, nil) +} + +func renderHTMLToolWithNativeRecord(out *bytes.Buffer, part opencode.ExportedPart, native []byte) { name := part.Name if name == "" { name = part.ID @@ -316,7 +324,16 @@ func renderHTMLTool(out *bytes.Buffer, part opencode.ExportedPart) { if content.Text != "" { fmt.Fprintf(out, "
%s
\n", html.EscapeString(content.Text)) } else if content.URI != "" { - fmt.Fprintf(out, "

%s (%s)

\n", html.EscapeString(content.URI), html.EscapeString(content.Mime)) + // Inline screenshot/file data is already retained verbatim in the + // complete native record. Printing megabytes of base64 again as a + // paragraph adds no readable evidence and can truncate the whole + // audit. Summarize only when that exact payload is demonstrably in + // this message's native bytes; otherwise preserve the old full output. + if len(content.URI) >= 5 && strings.EqualFold(content.URI[:5], "data:") && bytes.Contains(native, []byte(content.URI)) { + fmt.Fprintf(out, "

Inline attachment (%s): complete payload retained in the native message below.

\n", html.EscapeString(content.Mime)) + } else { + fmt.Fprintf(out, "

%s (%s)

\n", html.EscapeString(content.URI), html.EscapeString(content.Mime)) + } } } if part.State.Error != nil { diff --git a/internal/stage/session_export_inline_test.go b/internal/stage/session_export_inline_test.go new file mode 100644 index 00000000..87249d51 --- /dev/null +++ b/internal/stage/session_export_inline_test.go @@ -0,0 +1,68 @@ +package stage + +import ( + "encoding/json" + "html" + "strconv" + "strings" + "testing" + + "git.a-wan.net/alan/pipelines/internal/opencode" + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +func inlineSession(uri string, native json.RawMessage) opencode.ExportedSession { + return opencode.ExportedSession{ID: "ses_inline", Backend: "v2", Messages: []opencode.ExportedMessage{{ + ID: "message_inline", Role: "assistant", Raw: native, + Parts: []opencode.ExportedPart{{Type: protocol.ChatPartTool, Name: "screenshot", State: &protocol.ChatToolState{ + Content: []protocol.ChatToolContent{{URI: uri, Mime: "image/png"}}, + }}}, + }}} +} + +func TestSessionExportRetainsLargeInlinePayloadOnceWithoutRaisingBounds(t *testing.T) { + uri := "data:image/png;base64," + strings.Repeat("A", 4<<20) + native, err := json.Marshal(map[string]any{"id": "message_inline", "image": uri, "future_field": "retained"}) + if err != nil { + t.Fatal(err) + } + doc, truncated := renderSessionHTML(inlineSession(uri, native), SessionExportRequest{}) + if truncated || len(doc) > SessionExportFileLimit { + t.Fatalf("complete native screenshot was truncated by duplicate projection: bytes=%d", len(doc)) + } + if strings.Count(doc, uri) != 1 || !strings.Contains(html.UnescapeString(doc), string(native)) { + t.Fatal("exact native payload was lost or duplicated") + } + if !strings.Contains(doc, "complete payload retained in the native message below") || strings.Contains(doc, "TRUNCATED") { + t.Fatal("inline projection did not accurately describe retained complete evidence") + } +} + +func TestSessionExportNeverSummarizesInlinePayloadAbsentFromNativeRecord(t *testing.T) { + uri := "data:image/png;base64,AAAA" + for _, native := range []json.RawMessage{nil, json.RawMessage(`{"unrelated":"record"}`)} { + doc, truncated := renderSessionHTML(inlineSession(uri, native), SessionExportRequest{}) + if truncated || !strings.Contains(doc, uri) || strings.Contains(doc, "class=\"inline-attachment\"") { + t.Fatal("inline payload without a complete native copy was omitted") + } + } +} + +func TestSessionExportInlineProjectionDoesNotCreateExecutableMarkup(t *testing.T) { + uri := `data:text/html,` + native, err := json.Marshal(map[string]string{"attachment": uri}) + if err != nil { + t.Fatal(err) + } + // Cover both escaped and unescaped native JSON encodings: only the latter + // contains the literal URI and therefore takes the new summary path. + plain := json.RawMessage(`{"attachment":` + strconv.Quote(uri) + `}`) + for _, raw := range []json.RawMessage{native, plain} { + session := inlineSession(uri, raw) + session.Messages[0].Parts[0].State.Content[0].Mime = `image/png">` + doc, _ := renderSessionHTML(session, SessionExportRequest{}) + if strings.Contains(doc, "