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); + }); +}