diff --git a/app/lib/features/runs/actions/decision_dialog.dart b/app/lib/features/runs/actions/decision_dialog.dart index 5157097d..ddc8a56e 100644 --- a/app/lib/features/runs/actions/decision_dialog.dart +++ b/app/lib/features/runs/actions/decision_dialog.dart @@ -117,7 +117,7 @@ class _DecisionPromptState extends State<_DecisionPrompt> { RadioListTile( value: option.key, enabled: !_sending, - title: Text(option.key), + title: Text(option.displayLabel), subtitle: _target(option), ), ], @@ -156,6 +156,12 @@ class _DecisionPromptState extends State<_DecisionPrompt> { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Text(decisionMeta(widget.decision)), + if (decisionExhaustedText(widget.decision) case final text + when text.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(text, key: decisionExhaustedKey), + ), if (widget.decision.instructions.trim().isNotEmpty) Padding( padding: const EdgeInsets.only(top: 8), diff --git a/app/lib/features/runs/actions/decision_wording.dart b/app/lib/features/runs/actions/decision_wording.dart index a9904946..f74286fa 100644 --- a/app/lib/features/runs/actions/decision_wording.dart +++ b/app/lib/features/runs/actions/decision_wording.dart @@ -14,11 +14,26 @@ const decisionSendingLabel = 'Sending…'; const decisionActionKey = ValueKey('human-decision-action'); const decisionFeedbackKey = ValueKey('human-decision-feedback'); const decisionErrorKey = ValueKey('human-decision-error'); +const decisionExhaustedKey = ValueKey('human-decision-exhausted'); /// `{stage} · run {id} · {label}`, as the web decision card shows it. String decisionMeta(PendingDecision decision) => '${decision.stageKey} · run ${decision.runId} · ${decision.runLabel}'; +/// For a loop that exhausted its visits: `review used visit 3 of 3`, or the +/// part the server recorded; "" for a declared human decision. +String decisionExhaustedText(PendingDecision decision) { + final loop = decision.exhausted; + if (loop == null) return ''; + final stage = loop.stage.isEmpty ? decision.stageKey : loop.stage; + final visit = loop.visit; + final max = loop.maxVisits; + if (visit == null) return '$stage reached its visit limit'; + return max == null + ? '$stage reached its visit limit at visit $visit' + : '$stage reached its visit limit: visit $visit of $max'; +} + /// The option's target line, `→ {target}`, or "" when no target was declared. String decisionTargetText(String target) => target.trim().isEmpty ? '' : '→ $target'; diff --git a/app/lib/features/runs/actions/retry_action.dart b/app/lib/features/runs/actions/retry_action.dart index 1ba6c8c2..6b2495ff 100644 --- a/app/lib/features/runs/actions/retry_action.dart +++ b/app/lib/features/runs/actions/retry_action.dart @@ -4,6 +4,7 @@ import '../../../core/api_gateway.dart'; import '../data/runs_repository.dart'; import 'action_refusal.dart'; import 'retry_dialog.dart'; +import 'retry_extra_visits.dart'; import 'retry_eligibility.dart'; import 'retry_wording.dart'; @@ -106,12 +107,16 @@ Future openRetryRunPrompt( await showRetryRunPrompt( context: context, runId: id, + stages: retryStageKeys(run), + suggestExtraVisits: runExhaustedVisits(run), onSubmit: (intent) async { try { final updated = await repository.retryRun( id, requestKey: intent.requestKey, mode: intent.mode.wireMode, + extraVisits: intent.wireExtraVisits, + extraStage: intent.wireExtraStage, ); if (owns(id)) { onRunChanged(updated); diff --git a/app/lib/features/runs/actions/retry_dialog.dart b/app/lib/features/runs/actions/retry_dialog.dart index 7ce7409c..a8e49809 100644 --- a/app/lib/features/runs/actions/retry_dialog.dart +++ b/app/lib/features/runs/actions/retry_dialog.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'action_refusal.dart'; +import 'retry_extra_visits_field.dart'; import 'retry_intent.dart'; import 'retry_wording.dart'; @@ -19,8 +20,15 @@ Future showRetryRunPrompt({ required BuildContext context, required num runId, required RetrySubmit onSubmit, + List stages = const [], + bool suggestExtraVisits = false, }) { - final prompt = _RetryPrompt(runId: runId, onSubmit: onSubmit); + final prompt = _RetryPrompt( + runId: runId, + onSubmit: onSubmit, + stages: stages, + suggestExtraVisits: suggestExtraVisits, + ); return showDialog( context: context, barrierDismissible: false, @@ -29,17 +37,30 @@ Future showRetryRunPrompt({ } class _RetryPrompt extends StatefulWidget { - const _RetryPrompt({required this.runId, required this.onSubmit}); + const _RetryPrompt({ + required this.runId, + required this.onSubmit, + required this.stages, + required this.suggestExtraVisits, + }); final num runId; final RetrySubmit onSubmit; + /// The run's graph stage keys, offered as the extra visits' stage. + final List stages; + + /// Whether the run failed on an exhausted loop. + final bool suggestExtraVisits; + @override State<_RetryPrompt> createState() => _RetryPromptState(); } class _RetryPromptState extends State<_RetryPrompt> { RetryMode _mode = RetryMode.resume; + int? _extraVisits; + String? _extraStage; String? _requestKey; bool _sending = false; bool _checking = false; @@ -69,6 +90,8 @@ class _RetryPromptState extends State<_RetryPrompt> { final intent = RetryIntent( mode: _mode, requestKey: _requestKey ??= newRetryRequestKey(widget.runId), + extraVisits: _extraVisits, + extraStage: _extraStage, ); final refusal = await widget.onSubmit(intent); if (!mounted) return; @@ -137,6 +160,18 @@ class _RetryPromptState extends State<_RetryPrompt> { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Text(_dialogMessage), + // Extra visits extend a resumed run only; once sent, the intent (and + // its idempotency key) is fixed. + if (_mode == RetryMode.resume) + RetryExtraVisitsField( + visits: _extraVisits, + stage: _extraStage, + stages: widget.stages, + suggested: widget.suggestExtraVisits, + enabled: !_attempted, + onVisitsChanged: (value) => setState(() => _extraVisits = value), + onStageChanged: (value) => setState(() => _extraStage = value), + ), if (_error case final error?) Padding( padding: const EdgeInsets.only(top: 8), diff --git a/app/lib/features/runs/actions/retry_extra_visits.dart b/app/lib/features/runs/actions/retry_extra_visits.dart new file mode 100644 index 00000000..d527e75a --- /dev/null +++ b/app/lib/features/runs/actions/retry_extra_visits.dart @@ -0,0 +1,39 @@ +import '../../../core/api_gateway.dart'; + +/// The most extra visits one retry may grant (the server accepts 1-5). +const maxRetryExtraVisits = 5; + +/// The diagnostic phrases with which the server reports an exhausted loop. +const _exhaustedPhrases = [ + 'visit limit reached', + 'visit budget exceeded', + 'total stage budget exceeded', +]; + +/// Whether [run] failed because a loop exhausted its visits: its diagnostic +/// names a visit limit or budget, or a recorded step's control says the limit +/// was reached. Retrying it with extra visits is then worth suggesting. +bool runExhaustedVisits(JsonMap run) { + final diagnostic = '${run['diagnostic'] ?? ''}'.toLowerCase(); + if (_exhaustedPhrases.any(diagnostic.contains)) return true; + final steps = run['steps']; + if (steps is! List) return false; + return steps.whereType().any( + (step) => + step['control'] is Map && step['control']['limit_reached'] == true, + ); +} + +/// The stage keys of the run's graph, in declared order, for the extra +/// visits stage picker. +List retryStageKeys(JsonMap run) { + final graph = run['graph']; + final stages = graph is Map ? graph['stages'] : null; + if (stages is! List) return const []; + final keys = []; + for (final stage in stages.whereType()) { + final key = '${stage['key'] ?? ''}'.trim(); + if (key.isNotEmpty && !keys.contains(key)) keys.add(key); + } + return keys; +} diff --git a/app/lib/features/runs/actions/retry_extra_visits_field.dart b/app/lib/features/runs/actions/retry_extra_visits_field.dart new file mode 100644 index 00000000..876fe8d4 --- /dev/null +++ b/app/lib/features/runs/actions/retry_extra_visits_field.dart @@ -0,0 +1,95 @@ +import 'package:flutter/material.dart'; + +import 'retry_extra_visits.dart'; +import 'retry_wording.dart'; + +/// The resume prompt's optional "Grant extra visits" choice: a checkbox, the +/// number of visits (1-5) and the stage they go to (the exhausted stage by +/// default). Null [visits] means the choice is off. +class RetryExtraVisitsField extends StatelessWidget { + const RetryExtraVisitsField({ + super.key, + required this.visits, + required this.stage, + required this.stages, + required this.suggested, + required this.enabled, + required this.onVisitsChanged, + required this.onStageChanged, + }); + + final int? visits; + final String? stage; + final List stages; + + /// Whether the run failed on an exhausted loop, so the choice is suggested. + final bool suggested; + final bool enabled; + final ValueChanged onVisitsChanged; + final ValueChanged onStageChanged; + + @override + Widget build(BuildContext context) { + final count = visits; + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (suggested) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text( + retryExhaustedHint, + key: retryExhaustedHintKey, + style: Theme.of(context).textTheme.bodySmall, + ), + ), + CheckboxListTile( + key: retryExtraVisitsKey, + contentPadding: EdgeInsets.zero, + controlAffinity: ListTileControlAffinity.leading, + title: const Text(retryExtraVisitsLabel), + value: count != null, + onChanged: enabled + ? (checked) => onVisitsChanged(checked == true ? 1 : null) + : null, + ), + if (count != null) + Wrap( + spacing: 12, + runSpacing: 12, + children: [ + DropdownMenu( + key: retryExtraCountKey, + enabled: enabled, + label: const Text(retryExtraVisitsCountLabel), + initialSelection: count, + onSelected: (value) { + if (value != null) onVisitsChanged(value); + }, + dropdownMenuEntries: [ + for (var n = 1; n <= maxRetryExtraVisits; n++) + DropdownMenuEntry(value: n, label: '+$n'), + ], + ), + DropdownMenu( + key: retryExtraStageKey, + enabled: enabled, + label: const Text(retryExtraStageLabel), + initialSelection: stage, + onSelected: onStageChanged, + dropdownMenuEntries: [ + const DropdownMenuEntry( + value: null, + label: retryExhaustedStageLabel, + ), + for (final key in stages) + DropdownMenuEntry(value: key, label: key), + ], + ), + ], + ), + ], + ); + } +} diff --git a/app/lib/features/runs/actions/retry_intent.dart b/app/lib/features/runs/actions/retry_intent.dart index 4b97bb0e..122fd166 100644 --- a/app/lib/features/runs/actions/retry_intent.dart +++ b/app/lib/features/runs/actions/retry_intent.dart @@ -14,10 +14,35 @@ enum RetryMode { /// 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}); + const RetryIntent({ + required this.mode, + required this.requestKey, + this.extraVisits, + this.extraStage, + }); final RetryMode mode; final String requestKey; + + /// Extra visits (1-5) to grant on resume; null grants none. + final int? extraVisits; + + /// The stage the extra visits go to; null lets the server grant them to the + /// exhausted stage(s). + final String? extraStage; + + /// The `retry_extra_visits` value to send: only on resume, within 1-5. + int? get wireExtraVisits { + final visits = extraVisits; + if (mode != RetryMode.resume || visits == null) return null; + return visits >= 1 && visits <= 5 ? visits : null; + } + + /// The `retry_extra_stage` value to send, only alongside extra visits. + String? get wireExtraStage { + final stage = extraStage?.trim() ?? ''; + return wireExtraVisits == null || stage.isEmpty ? null : stage; + } } /// The entropy bound for a fresh key. diff --git a/app/lib/features/runs/actions/retry_wording.dart b/app/lib/features/runs/actions/retry_wording.dart index 97c6616a..873744a8 100644 --- a/app/lib/features/runs/actions/retry_wording.dart +++ b/app/lib/features/runs/actions/retry_wording.dart @@ -14,12 +14,24 @@ const restartDialogMessage = const restartConfirmLabel = 'Restart from start'; const retryKeepLabel = 'Keep'; +const retryExtraVisitsLabel = 'Grant extra visits'; +const retryExtraVisitsCountLabel = 'Extra visits'; +const retryExtraStageLabel = 'Stage'; +const retryExhaustedStageLabel = 'Exhausted stage'; +const retryExhaustedHint = + 'This run stopped because a loop used up its visits. Granting extra ' + 'visits lets it continue when resumed.'; + /// 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'); +const retryExtraVisitsKey = ValueKey('retry-run-extra-visits'); +const retryExtraCountKey = ValueKey('retry-run-extra-count'); +const retryExtraStageKey = ValueKey('retry-run-extra-stage'); +const retryExhaustedHintKey = ValueKey('retry-run-exhausted-hint'); /// The retry dialog's title: `Retry run {id}?`. String retryDialogTitle(num runId) => 'Retry run $runId?'; diff --git a/app/lib/features/runs/data/runs_repository.dart b/app/lib/features/runs/data/runs_repository.dart index 8dfe59f9..f8e9f259 100644 --- a/app/lib/features/runs/data/runs_repository.dart +++ b/app/lib/features/runs/data/runs_repository.dart @@ -112,9 +112,18 @@ class RunsRepository { num id, { required String requestKey, String? mode, + int? extraVisits, + String? extraStage, }) async { final fields = {'run_id': id, 'request_key': requestKey}; - if (mode == 'restart') fields['retry_mode'] = mode; + if (mode == 'restart') { + fields['retry_mode'] = mode; + } else if (extraVisits != null && extraVisits >= 1 && extraVisits <= 5) { + // Extra visits only extend a resumed run; a restart replays everything. + fields['retry_extra_visits'] = extraVisits; + final stage = extraStage?.trim() ?? ''; + if (stage.isNotEmpty) fields['retry_extra_stage'] = stage; + } return _required(await _gateway.call('retry_run', fields), 'run_detail'); } diff --git a/app/lib/features/runs/domain/run_decisions.dart b/app/lib/features/runs/domain/run_decisions.dart index 339508e6..1ccb4782 100644 --- a/app/lib/features/runs/domain/run_decisions.dart +++ b/app/lib/features/runs/domain/run_decisions.dart @@ -8,14 +8,58 @@ class PendingDecision { required this.stageKey, required this.instructions, required this.options, + this.exhausted, }); final num runId; final String runLabel; final String stageKey; final String instructions; final List options; + + /// The exhausted loop a server-created decision is about; null for a + /// declared human stage. + final ExhaustedLoop? exhausted; } +/// The loop whose visits ran out, from a waiting step's `exhausted` output: +/// the model stage, the visit it reached and its limit. +class ExhaustedLoop { + const ExhaustedLoop({ + required this.stage, + required this.visit, + required this.maxVisits, + required this.targets, + }); + + final String stage; + final int? visit; + final int? maxVisits; + + /// Where each option leads, by option key. + final Map targets; + + static ExhaustedLoop? parse(dynamic output) { + final value = output is Map ? output['exhausted'] : null; + if (value is! Map) return null; + final targets = value['targets']; + return ExhaustedLoop( + stage: _string(value['stage']).trim(), + visit: _int(value['visit']), + maxVisits: _int(value['max_visits']), + targets: targets is Map + ? {for (final e in targets.entries) '${e.key}': _string(e.value)} + : const {}, + ); + } +} + +/// Readable labels for the options of a server-created exhaustion decision. +const exhaustedOptionLabels = { + 'accept': 'Accept as is', + 'continue': 'One more round', + 'abort': 'Abort', +}; + JsonMap? lastWaitingStep(List steps) { for (final value in steps.reversed) { if (value is Map && value['status'] == 'waiting') { @@ -68,26 +112,37 @@ PendingDecision? pendingDecision(JsonMap? run) { } } } - if (declaration?['type'] != null && declaration!['type'] != 'human') { + final output = step?['output']; + final options = waitingOptions(output); + // A loop that exhausted its visits waits on its own (model) stage with the + // options the server recorded; any other non-human stage is not a decision. + final exhausted = ExhaustedLoop.parse(output); + final declared = exhausted == null || options.isEmpty; + if (declared && + declaration?['type'] != null && + declaration!['type'] != 'human') { return null; } - final edges = declaration?['edges']; - final options = waitingOptions(step?['output']); + final dynamic edges = exhausted != null && !declared + ? exhausted.targets + : declaration?['edges']; final keys = options.isNotEmpty ? options : humanOptions(edges); if (keys.isEmpty) return null; - final instructions = waitingPrompt(step?['output']).trim().isNotEmpty - ? waitingPrompt(step?['output']) + final instructions = waitingPrompt(output).trim().isNotEmpty + ? waitingPrompt(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, + exhausted: declared ? null : exhausted, options: keys .map( (key) => DecisionOption( key, target: _targetLabel(key, edges is Map ? edges[key] : null), + label: declared ? '' : exhaustedOptionLabels[key] ?? '', ), ) .toList(), @@ -108,3 +163,5 @@ String _targetLabel(String option, dynamic target) { bool _positive(dynamic value) => value is num && value > 0; String _string(dynamic value) => value == null ? '' : '$value'; +int? _int(dynamic value) => + value is num ? value.toInt() : int.tryParse(_string(value).trim()); diff --git a/app/lib/features/runs/domain/run_findings.dart b/app/lib/features/runs/domain/run_findings.dart new file mode 100644 index 00000000..bc2c37b8 --- /dev/null +++ b/app/lib/features/runs/domain/run_findings.dart @@ -0,0 +1,151 @@ +import '../../../core/api_gateway.dart'; + +/// A finding's severity, most severe first. Unknown wire values parse as null +/// and are kept visible under the "all" severity filter only. +enum FindingSeverity { + critical, + important, + minor, + nit; + + static FindingSeverity? parse(dynamic value) { + final text = '${value ?? ''}'.trim().toLowerCase(); + for (final severity in values) { + if (severity.name == text) return severity; + } + return null; + } +} + +/// The ledger statuses the server records for a finding. +const findingStatuses = ['open', 'fixed', 'dismissed', 'settled']; + +/// One recorded status change of a finding. +class FindingEvent { + const FindingEvent({ + required this.sequence, + required this.stage, + required this.status, + required this.reason, + }); + + final int? sequence; + final String stage; + final String status; + final String reason; +} + +/// One entry of the run's findings ledger, as the server recorded it. +class RunFinding { + const RunFinding({ + required this.id, + required this.severityText, + required this.origin, + required this.location, + required this.summary, + required this.status, + required this.reason, + required this.raisedBy, + required this.raisedSequence, + required this.updatedBy, + required this.updatedSequence, + required this.events, + }); + + final String id; + + /// The severity exactly as recorded; [severity] is its parsed form. + final String severityText; + final String origin; + final String location; + final String summary; + final String status; + final String reason; + final String raisedBy; + final int? raisedSequence; + final String updatedBy; + final int? updatedSequence; + final List events; + + FindingSeverity? get severity => FindingSeverity.parse(severityText); + bool get isOpen => status == 'open'; +} + +/// The run's findings ledger; empty when the server sent none (older servers). +List runFindings(JsonMap? run) { + final list = run?['findings']; + if (list is! List) return const []; + return [ + for (final item in list.whereType()) + if (_text(item['id']).isNotEmpty || _text(item['summary']).isNotEmpty) + RunFinding( + id: _text(item['id']), + severityText: _text(item['severity']).toLowerCase(), + origin: _text(item['origin']), + location: _text(item['location']), + summary: _text(item['summary']), + status: _text(item['status']).toLowerCase(), + reason: _text(item['reason']), + raisedBy: _text(item['raised_by']), + raisedSequence: _int(item['raised_sequence']), + updatedBy: _text(item['updated_by']), + updatedSequence: _int(item['updated_sequence']), + events: _events(item['events']), + ), + ]; +} + +/// How many findings are still open. +int openFindingCount(Iterable findings) => + findings.where((finding) => finding.isOpen).length; + +/// The status filter a fresh Findings view starts on: open items when any +/// are open, otherwise everything. +String? defaultFindingStatus(Iterable findings) => + openFindingCount(findings) > 0 ? 'open' : null; + +/// The findings matching [status] (null = all) at or above [minSeverity] +/// (null = all), in their recorded order. +List filterFindings( + Iterable findings, { + String? status, + FindingSeverity? minSeverity, +}) => [ + for (final finding in findings) + if ((status == null || finding.status == status) && + (minSeverity == null || + (finding.severity != null && + finding.severity!.index <= minSeverity.index))) + finding, +]; + +/// The run's extra visit grants as `review +1, implement +2`, or null when +/// none were granted. +String? visitGrantsSummary(JsonMap? run) { + final grants = run?['visit_grants']; + if (grants is! Map) return null; + final parts = [ + for (final entry in grants.entries) + if (_int(entry.value) case final count? when count > 0) + '${entry.key} +$count', + ]; + return parts.isEmpty ? null : parts.join(', '); +} + +List _events(dynamic value) { + if (value is! List) return const []; + return [ + for (final item in value.whereType()) + FindingEvent( + sequence: _int(item['sequence']), + stage: _text(item['stage']), + status: _text(item['status']).toLowerCase(), + reason: _text(item['reason']), + ), + ]; +} + +String _text(dynamic value) => value == null ? '' : '$value'.trim(); + +int? _int(dynamic value) => + value is num ? value.toInt() : int.tryParse(_text(value)); diff --git a/app/lib/features/runs/domain/run_models.dart b/app/lib/features/runs/domain/run_models.dart index f3502e5c..a8f43a0e 100644 --- a/app/lib/features/runs/domain/run_models.dart +++ b/app/lib/features/runs/domain/run_models.dart @@ -323,9 +323,14 @@ class RunListResult { } class DecisionOption { - const DecisionOption(this.key, {this.target = ''}); + const DecisionOption(this.key, {this.target = '', this.label = ''}); final String key; final String target; + + /// A readable label for a server-defined option; empty shows [key]. + final String label; + + String get displayLabel => label.trim().isEmpty ? key : label; } class DecisionDraft { diff --git a/app/lib/features/runs/ui/run_decision_notice.dart b/app/lib/features/runs/ui/run_decision_notice.dart index 1a2f2748..f94de5a8 100644 --- a/app/lib/features/runs/ui/run_decision_notice.dart +++ b/app/lib/features/runs/ui/run_decision_notice.dart @@ -53,6 +53,9 @@ class RunDecisionNotice extends StatelessWidget { maxLines: 1, overflow: TextOverflow.ellipsis, ), + if (decisionExhaustedText(pending) case final text + when text.isNotEmpty) + Text(text, style: metaStyle), ], ), ), diff --git a/app/lib/features/runs/ui/run_detail_summary_fields.dart b/app/lib/features/runs/ui/run_detail_summary_fields.dart index 17324533..22bb9178 100644 --- a/app/lib/features/runs/ui/run_detail_summary_fields.dart +++ b/app/lib/features/runs/ui/run_detail_summary_fields.dart @@ -1,6 +1,7 @@ import '../../../core/api_gateway.dart'; import '../../pipelines/pipeline_format.dart'; import '../domain/run_deletion.dart' show formatByteSize, runSizeBytes; +import '../domain/run_findings.dart' show visitGrantsSummary; import '../domain/run_tokens.dart'; import 'run_detail_visit_facts.dart'; @@ -70,6 +71,7 @@ List detailSummaryRows(JsonMap run, {DateTime? now}) { } final retryOf = _number(run['retry_of'])?.toInt() ?? 0; if (retryOf > 0) add('Retry of', 'run $retryOf'); + add('Extra visits', visitGrantsSummary(run)); // A diagnostic is a recorded document: its own whitespace is preserved, but a // blank one is not a row. final diagnostic = '${run['diagnostic'] ?? ''}'; diff --git a/app/lib/features/runs/ui/run_detail_tab.dart b/app/lib/features/runs/ui/run_detail_tab.dart index 2b5eb319..ddf146b4 100644 --- a/app/lib/features/runs/ui/run_detail_tab.dart +++ b/app/lib/features/runs/ui/run_detail_tab.dart @@ -5,7 +5,8 @@ import 'package:flutter/material.dart'; /// /// The stable keys match the web client's `RUN_DETAIL_TABS`; the visible labels /// are the same words. `renderedRunDetailTabs` decides which keys the strip -/// draws, so Input and Output stay addressable without being tabs. +/// draws, so Input and Output stay addressable without being tabs. Findings +/// is appended only for a run whose server recorded a findings ledger. enum RunDetailTab { summary('Summary', Icons.summarize_outlined), graph('Graph', Icons.account_tree_outlined), @@ -13,7 +14,8 @@ enum RunDetailTab { output('Output', Icons.output), timeline('Timeline', Icons.timeline), artifacts('Artifacts', Icons.inventory_2_outlined), - changes('Changes', Icons.difference_outlined); + changes('Changes', Icons.difference_outlined), + findings('Findings', Icons.fact_check_outlined); const RunDetailTab(this.label, this.icon); diff --git a/app/lib/features/runs/ui/run_detail_tab_strip.dart b/app/lib/features/runs/ui/run_detail_tab_strip.dart index a82d2623..fbf14e25 100644 --- a/app/lib/features/runs/ui/run_detail_tab_strip.dart +++ b/app/lib/features/runs/ui/run_detail_tab_strip.dart @@ -41,6 +41,25 @@ class RunArtifactsCount extends StatelessWidget { } } +/// The run's open findings as a badge on the Findings tab; nothing when none +/// are open. +class RunOpenFindingsCount extends StatelessWidget { + const RunOpenFindingsCount({super.key, required this.count, this.child}); + + final int count; + final Widget? child; + + @override + Widget build(BuildContext context) { + if (count <= 0) return child ?? const SizedBox.shrink(); + return Badge( + key: const ValueKey('run-detail-findings-count'), + label: Text('$count'), + child: child, + ); + } +} + /// The run detail's tabs on a phone: the app's floating glass tab bar, full /// width at the bottom of the page (a wide layout puts `RunDetailTopTabs` /// under the run header instead). @@ -59,6 +78,7 @@ class RunDetailTabStrip extends StatelessWidget { this.tabs = renderedRunDetailTabs, this.edge = FloatingBarEdge.bottom, this.artifactCount, + this.openFindingCount, this.disabled = const {}, this.disabledReasons = const {}, }); @@ -77,6 +97,9 @@ class RunDetailTabStrip extends StatelessWidget { /// no badge. final int? artifactCount; + /// The run's open findings, badged on the Findings tab when above zero. + final int? openFindingCount; + /// Tabs shown greyed out that take no taps. final Set disabled; @@ -99,6 +122,11 @@ class RunDetailTabStrip extends StatelessWidget { key: ValueKey('run-detail-tab-${tab.name}'), icon: tab == RunDetailTab.artifacts && count != null ? RunArtifactsCount(count: count, child: Icon(tab.icon)) + : tab == RunDetailTab.findings + ? RunOpenFindingsCount( + count: openFindingCount ?? 0, + child: Icon(tab.icon), + ) : Icon(tab.icon), label: tab.label, enabled: !disabled.contains(tab), diff --git a/app/lib/features/runs/ui/run_detail_tabs.dart b/app/lib/features/runs/ui/run_detail_tabs.dart index 117b5714..c655c0ce 100644 --- a/app/lib/features/runs/ui/run_detail_tabs.dart +++ b/app/lib/features/runs/ui/run_detail_tabs.dart @@ -27,6 +27,8 @@ import 'run_detail_top_tabs.dart'; import 'run_detail_timeline.dart'; import 'run_detail_visit.dart'; import 'run_detail_wide_chrome.dart'; +import 'run_findings_tab.dart'; +import '../domain/run_findings.dart'; import 'run_detail_visit_facts.dart'; import 'run_search_selection.dart'; @@ -398,6 +400,7 @@ class _RunDetailTabsState extends State { List _tabsFor(JsonMap run) => [ for (final tab in renderedRunDetailTabs) if (tab != RunDetailTab.changes || showRunChangesAction(run)) tab, + if (runFindings(run).isNotEmpty) RunDetailTab.findings, ]; /// Artifacts stays in place but disabled while the run recorded none. @@ -414,10 +417,13 @@ class _RunDetailTabsState extends State { final tabs = _tabsFor(widget.run); final disabled = _disabledTabs(widget.run); final artifactCount = runArtifactCount(widget.run); + final findings = runFindings(widget.run); + final openFindings = openFindingCount(findings); // A tab the run no longer offers (or cannot open) falls back to Summary. final shown = (tabs.contains(_tab) && !disabled.contains(_tab)) || - !renderedRunDetailTabs.contains(_tab) + (!renderedRunDetailTabs.contains(_tab) && + _tab != RunDetailTab.findings) ? _tab : RunDetailTab.summary; final edge = PageTabsEdge.of(context); @@ -458,6 +464,7 @@ class _RunDetailTabsState extends State { selected: shown, onSelected: select, artifactCount: artifactCount, + openFindingCount: openFindings, disabled: disabled, disabledReasons: reasons, ), @@ -471,6 +478,7 @@ class _RunDetailTabsState extends State { selected: shown, onSelected: select, artifactCount: artifactCount, + openFindingCount: openFindings, disabled: disabled, disabledReasons: reasons, ); @@ -568,6 +576,11 @@ class _RunDetailTabsState extends State { ); // Its summary heads the tab, so the tab starts below a pane's top tabs. return BelowTopBar(child: viewer); + case RunDetailTab.findings: + return RunFindingsTab( + key: ValueKey('run-detail-findings-${widget.run['id']}'), + findings: runFindings(widget.run), + ); case RunDetailTab.timeline: final visits = detailTimeline(widget.run['steps']); final index = _selectedVisit; diff --git a/app/lib/features/runs/ui/run_detail_top_tabs.dart b/app/lib/features/runs/ui/run_detail_top_tabs.dart index 90e7db85..5030388a 100644 --- a/app/lib/features/runs/ui/run_detail_top_tabs.dart +++ b/app/lib/features/runs/ui/run_detail_top_tabs.dart @@ -18,6 +18,7 @@ class RunDetailTopTabs extends StatelessWidget { required this.selected, required this.onSelected, this.artifactCount, + this.openFindingCount, this.disabled = const {}, this.disabledReasons = const {}, }); @@ -26,6 +27,7 @@ class RunDetailTopTabs extends StatelessWidget { final RunDetailTab selected; final ValueChanged onSelected; final int? artifactCount; + final int? openFindingCount; final Set disabled; /// Why a disabled tab cannot open, as its tooltip. @@ -67,6 +69,11 @@ class RunDetailTopTabs extends StatelessWidget { const SizedBox(width: 6), RunArtifactsCount(count: count), ], + if (tab == RunDetailTab.findings && + (openFindingCount ?? 0) > 0) ...[ + const SizedBox(width: 6), + RunOpenFindingsCount(count: openFindingCount!), + ], ], ), ), diff --git a/app/lib/features/runs/ui/run_findings_tab.dart b/app/lib/features/runs/ui/run_findings_tab.dart new file mode 100644 index 00000000..531158be --- /dev/null +++ b/app/lib/features/runs/ui/run_findings_tab.dart @@ -0,0 +1,172 @@ +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/floating_bar_layout.dart'; +import '../../../ui/text/monospace.dart'; +import '../domain/run_findings.dart'; + +/// The Findings tab: the run's recorded findings ledger, filtered by status +/// (open first when any are open) and by minimum severity. Each finding +/// expands to show who raised it and its recorded status changes. +class RunFindingsTab extends StatefulWidget { + const RunFindingsTab({super.key, required this.findings}); + + final List findings; + + @override + State createState() => _RunFindingsTabState(); +} + +class _RunFindingsTabState extends State { + late String? _status = defaultFindingStatus(widget.findings); + FindingSeverity? _minSeverity; + + @override + Widget build(BuildContext context) { + final shown = filterFindings( + widget.findings, + status: _status, + minSeverity: _minSeverity, + ); + return ListView( + key: const Key('run-detail-tab-body-findings'), + padding: withBarClearance(context, const EdgeInsets.all(16)), + children: [ + _filters(context), + const SizedBox(height: 8), + if (shown.isEmpty) + Padding( + padding: const EdgeInsets.symmetric(vertical: 16), + child: Text( + 'No findings match these filters.', + key: const Key('run-findings-empty'), + style: Theme.of(context).textTheme.bodyMedium, + ), + ), + for (final finding in shown) RunFindingTile(finding: finding), + ], + ); + } + + Widget _filters(BuildContext context) { + int count(String? status) => + filterFindings(widget.findings, status: status).length; + return Wrap( + spacing: 8, + runSpacing: 8, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + for (final status in [null, ...findingStatuses]) + ChoiceChip( + key: ValueKey('run-findings-status-${status ?? 'all'}'), + label: Text('${_statusLabel(status)} (${count(status)})'), + selected: _status == status, + onSelected: (_) => setState(() => _status = status), + ), + DropdownMenu( + key: const Key('run-findings-severity'), + label: const Text('Minimum severity'), + initialSelection: _minSeverity, + onSelected: (value) => setState(() => _minSeverity = value), + dropdownMenuEntries: [ + const DropdownMenuEntry(value: null, label: 'All severities'), + for (final severity in FindingSeverity.values) + DropdownMenuEntry(value: severity, label: severity.name), + ], + ), + ], + ); + } +} + +String _statusLabel(String? status) => switch (status) { + null => 'All', + final text => '${text[0].toUpperCase()}${text.substring(1)}', +}; + +/// One finding: severity, id and summary, with origin, location, status and +/// the latest reason under it; expanding shows its recorded events. +class RunFindingTile extends StatelessWidget { + const RunFindingTile({super.key, required this.finding}); + + final RunFinding finding; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final meta = [ + if (finding.severityText.isNotEmpty) finding.severityText, + if (finding.origin.isNotEmpty) finding.origin, + if (finding.status.isNotEmpty) finding.status, + ].join(' · '); + final history = [ + if (finding.raisedBy.isNotEmpty) + 'Raised by ${finding.raisedBy}${_visit(finding.raisedSequence)}', + if (finding.updatedBy.isNotEmpty) + 'Updated by ${finding.updatedBy}${_visit(finding.updatedSequence)}', + ]; + return ExpansionTile( + key: ValueKey('run-finding-${finding.id}'), + tilePadding: EdgeInsets.zero, + childrenPadding: const EdgeInsetsDirectional.only(start: 40, bottom: 8), + expandedCrossAxisAlignment: CrossAxisAlignment.start, + leading: Icon( + _severityIcon(finding.severity), + color: _severityColor(theme.colorScheme, finding.severity), + ), + title: Text( + [ + finding.id, + finding.summary, + ].where((part) => part.isNotEmpty).join(' · '), + ), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(meta), + if (finding.location.isNotEmpty) + SelectableText( + finding.location, + style: const TextStyle(fontFamily: appMonospaceFamily), + ), + if (finding.reason.isNotEmpty) Text(finding.reason), + ], + ), + children: [ + for (final line in history) + Text(line, style: theme.textTheme.bodySmall), + for (final event in finding.events) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Text( + [ + if (event.sequence != null) '#${event.sequence}', + if (event.stage.isNotEmpty) event.stage, + if (event.status.isNotEmpty) event.status, + ].join(' · ') + + (event.reason.isEmpty ? '' : ': ${event.reason}'), + style: theme.textTheme.bodySmall, + ), + ), + if (history.isEmpty && finding.events.isEmpty) + Text('No recorded history.', style: theme.textTheme.bodySmall), + ], + ); + } +} + +String _visit(int? sequence) => sequence == null ? '' : ' (visit #$sequence)'; + +IconData _severityIcon(FindingSeverity? severity) => switch (severity) { + FindingSeverity.critical => Icons.error, + FindingSeverity.important => Icons.warning_amber, + FindingSeverity.minor => Icons.info_outline, + FindingSeverity.nit || null => Icons.label_outline, +}; + +Color _severityColor(ColorScheme scheme, FindingSeverity? severity) => + switch (severity) { + FindingSeverity.critical => scheme.error, + FindingSeverity.important => scheme.tertiary, + FindingSeverity.minor => scheme.primary, + FindingSeverity.nit || null => scheme.onSurfaceVariant, + }; diff --git a/app/test/features/runs/actions/decision_exhausted_test.dart b/app/test/features/runs/actions/decision_exhausted_test.dart new file mode 100644 index 00000000..ffcf6501 --- /dev/null +++ b/app/test/features/runs/actions/decision_exhausted_test.dart @@ -0,0 +1,59 @@ +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'; + +import '../domain/run_exhausted_decision_fixture.dart'; +import 'retry_test_support.dart' show FakeRetryGateway; + +void main() { + testWidgets('an exhaustion decision shows readable options and the visit ' + 'count, and sends the option key for the exhausted stage', ( + tester, + ) async { + final gateway = FakeRetryGateway( + (type, fields) async => { + 'run_detail': {...exhaustedDecisionRun(), 'status': 'running'}, + }, + ); + final changed = []; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Center( + child: HumanDecisionAction( + run: exhaustedDecisionRun(), + gateway: gateway, + onRunChanged: changed.add, + ), + ), + ), + ), + ); + + await tester.tap(find.byKey(decisionActionKey)); + await tester.pumpAndSettle(); + expect(find.text('Accept as is'), findsOneWidget); + expect(find.text('One more round'), findsOneWidget); + expect(find.text('Abort'), findsOneWidget); + expect(find.text('→ implement'), findsOneWidget); + expect( + find.text('review reached its visit limit: visit 3 of 3'), + findsOneWidget, + ); + + await tester.tap(find.text('One more round')); + await tester.pump(); + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pumpAndSettle(); + + final decide = gateway.calls.singleWhere((c) => c.type == 'decide_run'); + expect(decide.fields, { + 'run_id': 9, + 'option': 'continue', + 'stage': 'review', + }); + expect(changed, isNotEmpty); + }); +} diff --git a/app/test/features/runs/actions/retry_extra_visits_test.dart b/app/test/features/runs/actions/retry_extra_visits_test.dart new file mode 100644 index 00000000..b77b6bb7 --- /dev/null +++ b/app/test/features/runs/actions/retry_extra_visits_test.dart @@ -0,0 +1,168 @@ +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_extra_visits.dart'; +import 'package:pipelines_app/features/runs/actions/retry_intent.dart'; +import 'package:pipelines_app/features/runs/actions/retry_wording.dart'; +import 'package:pipelines_app/features/runs/data/runs_repository.dart'; + +import 'retry_test_support.dart'; + +JsonMap exhaustedRun() => { + ...failedRun(), + 'diagnostic': 'review: visit limit reached (3 of 3)', + 'graph': { + 'stages': [ + {'key': 'implement', 'type': 'model'}, + {'key': 'review', 'type': 'model'}, + ], + }, +}; + +Future pick(WidgetTester tester, Key menu, String label) async { + await tester.tap(find.byKey(menu)); + await tester.pumpAndSettle(); + await tester.tap(find.text(label).last); + await tester.pumpAndSettle(); +} + +void main() { + test('exhausted loops are recognised from the diagnostic or a step', () { + expect(runExhaustedVisits(exhaustedRun()), isTrue); + for (final phrase in [ + 'Visit budget exceeded', + 'total stage budget exceeded', + ]) { + expect(runExhaustedVisits({'diagnostic': phrase}), isTrue); + } + expect( + runExhaustedVisits({ + 'steps': [ + { + 'stage': 'review', + 'control': {'limit_reached': true}, + }, + ], + }), + isTrue, + ); + expect(runExhaustedVisits(failedRun()), isFalse); + expect(retryStageKeys(exhaustedRun()), ['implement', 'review']); + expect(retryStageKeys(failedRun()), isEmpty); + }); + + test('extra visits are only on the wire for a resume within 1-5', () { + RetryIntent intent(RetryMode mode, int? visits, [String? stage]) => + RetryIntent( + mode: mode, + requestKey: 'k', + extraVisits: visits, + extraStage: stage, + ); + expect(intent(RetryMode.resume, 2, 'review').wireExtraVisits, 2); + expect(intent(RetryMode.resume, 2, 'review').wireExtraStage, 'review'); + expect(intent(RetryMode.resume, 2).wireExtraStage, isNull); + expect(intent(RetryMode.resume, 0).wireExtraVisits, isNull); + expect(intent(RetryMode.resume, 6).wireExtraVisits, isNull); + expect(intent(RetryMode.resume, null, 'review').wireExtraStage, isNull); + expect(intent(RetryMode.restart, 2, 'review').wireExtraVisits, isNull); + expect(intent(RetryMode.restart, 2, 'review').wireExtraStage, isNull); + }); + + test('the repository sends extra visits on resume only', () async { + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': retriedRun()}, + ); + final repo = RunsRepository(gateway); + await repo.retryRun(7, requestKey: 'a', extraVisits: 2); + expect(gateway.calls.last.fields, { + 'run_id': 7, + 'request_key': 'a', + 'retry_extra_visits': 2, + }); + await repo.retryRun(7, requestKey: 'b', extraVisits: 1, extraStage: 'x'); + expect(gateway.calls.last.fields['retry_extra_stage'], 'x'); + await repo.retryRun( + 7, + requestKey: 'c', + mode: 'restart', + extraVisits: 2, + extraStage: 'x', + ); + expect(gateway.calls.last.fields, { + 'run_id': 7, + 'request_key': 'c', + 'retry_mode': 'restart', + }); + await repo.retryRun(7, requestKey: 'd', extraVisits: 9); + expect(gateway.calls.last.fields.containsKey('retry_extra_visits'), false); + }); + + testWidgets('an exhausted run suggests extra visits; chosen ones are sent', ( + tester, + ) async { + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': retriedRun()}, + ); + await pumpRetry(tester, gateway: gateway, changed: [], run: exhaustedRun()); + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + + expect(find.byKey(retryExhaustedHintKey), findsOneWidget); + // Suggested, but off until the operator chooses it. + expect(find.byKey(retryExtraCountKey), findsNothing); + await tester.tap(find.byKey(retryExtraVisitsKey)); + await tester.pumpAndSettle(); + await pick(tester, retryExtraCountKey, '+3'); + await pick(tester, retryExtraStageKey, 'review'); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + final fields = gateway.retries.single.fields; + expect(fields['retry_extra_visits'], 3); + expect(fields['retry_extra_stage'], 'review'); + expect(fields.containsKey('retry_mode'), isFalse); + }); + + testWidgets('a plain failure offers extra visits without a hint, and the ' + 'default stage is left to the server', (tester) async { + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': retriedRun()}, + ); + await pumpRetry(tester, gateway: gateway, changed: []); + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + + expect(find.byKey(retryExhaustedHintKey), findsNothing); + await tester.tap(find.byKey(retryExtraVisitsKey)); + await tester.pumpAndSettle(); + expect(find.text(retryExhaustedStageLabel), findsWidgets); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + final fields = gateway.retries.single.fields; + expect(fields['retry_extra_visits'], 1); + expect(fields.containsKey('retry_extra_stage'), isFalse); + }); + + testWidgets('restart hides and never sends extra visits', (tester) async { + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': retriedRun()}, + ); + await pumpRetry(tester, gateway: gateway, changed: [], run: exhaustedRun()); + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryExtraVisitsKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + expect(find.byKey(retryExtraVisitsKey), findsNothing); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + final fields = gateway.retries.single.fields; + expect(fields['retry_mode'], 'restart'); + expect(fields.containsKey('retry_extra_visits'), isFalse); + expect(fields.containsKey('retry_extra_stage'), isFalse); + }); +} diff --git a/app/test/features/runs/domain/run_exhausted_decision_fixture.dart b/app/test/features/runs/domain/run_exhausted_decision_fixture.dart new file mode 100644 index 00000000..7a748a71 --- /dev/null +++ b/app/test/features/runs/domain/run_exhausted_decision_fixture.dart @@ -0,0 +1,43 @@ +import 'package:pipelines_app/core/api_gateway.dart'; + +/// A run waiting on the server-created decision of an exhausted review loop: +/// the waiting stage is the model stage, not a human stage in the graph. +JsonMap exhaustedDecisionRun({dynamic output}) => { + 'id': 9, + 'status': 'waiting', + 'current_stage': 'review', + 'name': 'Build', + 'graph': { + 'stages': [ + { + 'key': 'review', + 'type': 'model', + 'edges': {'pass': '#', 'fail': 'implement'}, + }, + {'key': 'implement', 'type': 'model'}, + ], + }, + 'steps': [ + { + 'stage': 'review', + 'sequence': 6, + 'status': 'waiting', + 'output': + output ?? + { + 'prompt': 'Review used all its visits.', + 'options': ['accept', 'continue', 'abort'], + 'exhausted': { + 'stage': 'review', + 'visit': 3, + 'max_visits': 3, + 'targets': { + 'accept': '#success', + 'continue': 'implement', + 'abort': '#failure', + }, + }, + }, + }, + ], +}; diff --git a/app/test/features/runs/domain/run_exhausted_decision_test.dart b/app/test/features/runs/domain/run_exhausted_decision_test.dart new file mode 100644 index 00000000..dae2f7bd --- /dev/null +++ b/app/test/features/runs/domain/run_exhausted_decision_test.dart @@ -0,0 +1,70 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/runs/actions/decision_wording.dart'; +import 'package:pipelines_app/features/runs/domain/run_decisions.dart'; + +import 'run_exhausted_decision_fixture.dart'; + +void main() { + test('an exhaustion decision on a model stage uses the recorded options', () { + final decision = pendingDecision(exhaustedDecisionRun())!; + expect(decision.stageKey, 'review'); + expect(decision.instructions, 'Review used all its visits.'); + expect(decision.options.map((o) => o.key), ['accept', 'continue', 'abort']); + expect(decision.options.map((o) => o.displayLabel), [ + 'Accept as is', + 'One more round', + 'Abort', + ]); + expect(decision.options.map((o) => o.target), [ + 'SUCCESS', + 'implement', + 'FAILURE', + ]); + expect(decision.exhausted?.visit, 3); + expect(decision.exhausted?.maxVisits, 3); + expect( + decisionExhaustedText(decision), + 'review reached its visit limit: visit 3 of 3', + ); + }); + + test('unknown option keys keep their recorded wording', () { + final decision = pendingDecision( + exhaustedDecisionRun( + output: { + 'options': ['accept', 'extend'], + 'exhausted': {'stage': 'review'}, + }, + ), + )!; + expect(decision.options.map((o) => o.displayLabel), [ + 'Accept as is', + 'extend', + ]); + expect(decision.options.last.target, ''); + expect(decisionExhaustedText(decision), 'review reached its visit limit'); + }); + + test('a model stage waiting without an exhaustion record is no decision', () { + expect( + pendingDecision( + exhaustedDecisionRun( + output: { + 'options': ['accept'], + }, + ), + ), + isNull, + ); + expect( + pendingDecision( + exhaustedDecisionRun( + output: { + 'exhausted': {'stage': 'review'}, + }, + ), + ), + isNull, + ); + }); +} diff --git a/app/test/features/runs/domain/run_findings_fixture.dart b/app/test/features/runs/domain/run_findings_fixture.dart new file mode 100644 index 00000000..49a43682 --- /dev/null +++ b/app/test/features/runs/domain/run_findings_fixture.dart @@ -0,0 +1,48 @@ +import 'package:pipelines_app/core/api_gateway.dart'; + +/// A run detail with a small findings ledger: one open, one fixed with its +/// event history, one dismissed, and a malformed entry. +JsonMap findingsRun() => { + 'id': 4, + 'findings': [ + { + 'id': 'F1', + 'severity': 'critical', + 'origin': 'introduced', + 'location': 'internal/cache.go:42', + 'summary': 'Cache never evicts', + 'status': 'open', + 'raised_by': 'review', + 'raised_sequence': 4, + }, + { + 'id': 'F2', + 'severity': 'minor', + 'origin': 'pre-existing', + 'location': '', + 'summary': 'Typo in log', + 'status': 'fixed', + 'reason': 'Corrected', + 'raised_by': 'review', + 'raised_sequence': 4, + 'updated_by': 'implement', + 'updated_sequence': 5, + 'events': [ + { + 'sequence': 5, + 'stage': 'implement', + 'status': 'fixed', + 'reason': 'Corrected', + }, + ], + }, + { + 'id': 'F3', + 'severity': 'nit', + 'origin': 'introduced', + 'summary': 'Naming', + 'status': 'dismissed', + }, + 'not a finding', + ], +}; diff --git a/app/test/features/runs/domain/run_findings_test.dart b/app/test/features/runs/domain/run_findings_test.dart new file mode 100644 index 00000000..7e4ad9e7 --- /dev/null +++ b/app/test/features/runs/domain/run_findings_test.dart @@ -0,0 +1,65 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/runs/domain/run_findings.dart'; + +import 'run_findings_fixture.dart'; + +void main() { + test('parses the recorded ledger and skips malformed items', () { + final findings = runFindings(findingsRun()); + expect(findings.map((f) => f.id), ['F1', 'F2', 'F3']); + final fixed = findings[1]; + expect(fixed.severity, FindingSeverity.minor); + expect(fixed.origin, 'pre-existing'); + expect(fixed.location, ''); + expect(fixed.reason, 'Corrected'); + expect(fixed.updatedBy, 'implement'); + expect(fixed.updatedSequence, 5); + expect(fixed.events.single.stage, 'implement'); + expect(fixed.events.single.sequence, 5); + expect(findings.first.events, isEmpty); + expect(findings.first.raisedSequence, 4); + }); + + test('older servers without findings show nothing', () { + expect(runFindings({'id': 1}), isEmpty); + expect(runFindings({'findings': []}), isEmpty); + expect(runFindings(null), isEmpty); + }); + + test('filters by status and minimum severity', () { + final findings = runFindings(findingsRun()); + expect(openFindingCount(findings), 1); + expect(defaultFindingStatus(findings), 'open'); + expect(defaultFindingStatus(findings.skip(1)), isNull); + ids(List list) => list.map((f) => f.id).toList(); + expect(ids(filterFindings(findings)), ['F1', 'F2', 'F3']); + expect(ids(filterFindings(findings, status: 'fixed')), ['F2']); + expect(ids(filterFindings(findings, minSeverity: FindingSeverity.minor)), [ + 'F1', + 'F2', + ]); + expect( + ids(filterFindings(findings, minSeverity: FindingSeverity.critical)), + ['F1'], + ); + expect( + filterFindings( + findings, + status: 'fixed', + minSeverity: FindingSeverity.important, + ), + isEmpty, + ); + }); + + test('visit grants summarise as stage +n', () { + expect( + visitGrantsSummary({ + 'visit_grants': {'review': 1, 'implement': 2, 'idle': 0}, + }), + 'review +1, implement +2', + ); + expect(visitGrantsSummary({'visit_grants': {}}), isNull); + expect(visitGrantsSummary({}), isNull); + }); +} diff --git a/app/test/features/runs/ui/run_detail_findings_tab_test.dart b/app/test/features/runs/ui/run_detail_findings_tab_test.dart new file mode 100644 index 00000000..c6aae9cd --- /dev/null +++ b/app/test/features/runs/ui/run_detail_findings_tab_test.dart @@ -0,0 +1,43 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_tab.dart'; + +import '../domain/run_findings_fixture.dart'; +import 'run_detail_graph_support.dart'; + +void main() { + testWidgets('a run without findings has no Findings tab', (tester) async { + await pumpRunDetail(tester, RunDetailTestPlatform.material); + expect(runDetailTab(RunDetailTab.findings), findsNothing); + }); + + for (final size in const [Size(900, 1000), Size(390, 844)]) { + testWidgets('a run with findings offers the tab with its open count at ' + '${size.width}', (tester) async { + await pumpRunDetail( + tester, + RunDetailTestPlatform.material, + size: size, + run: { + ...graphRunFixture(), + 'findings': findingsRun()['findings'], + 'visit_grants': {'review': 1}, + }, + ); + expect(runDetailTab(RunDetailTab.findings), findsOneWidget); + expect( + find.byKey(const ValueKey('run-detail-findings-count')), + findsOneWidget, + ); + expect(find.text('review +1'), findsOneWidget); + + await openRunDetailTab(tester, RunDetailTab.findings); + await tester.pumpAndSettle(); + expect( + find.byKey(const Key('run-detail-tab-body-findings')), + findsOneWidget, + ); + expect(find.byKey(const ValueKey('run-finding-F1')), findsOneWidget); + }); + } +} diff --git a/app/test/features/runs/ui/run_findings_tab_test.dart b/app/test/features/runs/ui/run_findings_tab_test.dart new file mode 100644 index 00000000..e66601d6 --- /dev/null +++ b/app/test/features/runs/ui/run_findings_tab_test.dart @@ -0,0 +1,64 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/runs/domain/run_findings.dart'; +import 'package:pipelines_app/features/runs/ui/run_findings_tab.dart'; + +import '../domain/run_findings_fixture.dart'; + +Future pumpFindings(WidgetTester tester, List findings) => + tester.pumpWidget( + MaterialApp( + home: Scaffold(body: RunFindingsTab(findings: findings)), + ), + ); + +Finder finding(String id) => find.byKey(ValueKey('run-finding-$id')); + +void main() { + testWidgets('starts on open findings and filters by status', (tester) async { + await pumpFindings(tester, runFindings(findingsRun())); + + expect(finding('F1'), findsOneWidget); + expect(finding('F2'), findsNothing); + expect(find.text('F1 · Cache never evicts'), findsOneWidget); + expect(find.text('critical · introduced · open'), findsOneWidget); + expect(find.text('internal/cache.go:42'), findsOneWidget); + expect(find.text('Open (1)'), findsOneWidget); + + await tester.tap(find.byKey(const ValueKey('run-findings-status-all'))); + await tester.pumpAndSettle(); + for (final id in ['F1', 'F2', 'F3']) { + expect(finding(id), findsOneWidget); + } + + await tester.tap(find.byKey(const ValueKey('run-findings-status-settled'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('run-findings-empty')), findsOneWidget); + }); + + testWidgets('filters by minimum severity and expands events', (tester) async { + await pumpFindings(tester, runFindings(findingsRun())); + await tester.tap(find.byKey(const ValueKey('run-findings-status-all'))); + await tester.pumpAndSettle(); + + await tester.tap(find.byKey(const Key('run-findings-severity'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('minor').last); + await tester.pumpAndSettle(); + expect(finding('F2'), findsOneWidget); + expect(finding('F3'), findsNothing); + + expect(find.text('Corrected'), findsOneWidget); + await tester.tap(finding('F2')); + await tester.pumpAndSettle(); + expect(find.text('Raised by review (visit #4)'), findsOneWidget); + expect(find.text('Updated by implement (visit #5)'), findsOneWidget); + expect(find.text('#5 · implement · fixed: Corrected'), findsOneWidget); + }); + + testWidgets('with nothing open, all findings show', (tester) async { + await pumpFindings(tester, runFindings(findingsRun()).skip(1).toList()); + expect(finding('F2'), findsOneWidget); + expect(finding('F3'), findsOneWidget); + }); +}