Merge main (findings ledger, loop continuation) into usage-limit branch

Keeps the findings ledger, extra visits and on_exhausted=decide alongside the
run budget, failure classes, quota parking and error-loop backoff.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 14:35:54 +00:00
66 changed files with 3565 additions and 148 deletions
@@ -117,7 +117,7 @@ class _DecisionPromptState extends State<_DecisionPrompt> {
RadioListTile<String>(
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),
@@ -14,11 +14,26 @@ const decisionSendingLabel = 'Sending…';
const decisionActionKey = ValueKey<String>('human-decision-action');
const decisionFeedbackKey = ValueKey<String>('human-decision-feedback');
const decisionErrorKey = ValueKey<String>('human-decision-error');
const decisionExhaustedKey = ValueKey<String>('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';
@@ -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<void> 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);
@@ -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<void> showRetryRunPrompt({
required BuildContext context,
required num runId,
required RetrySubmit onSubmit,
List<String> 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<void>(
context: context,
barrierDismissible: false,
@@ -29,17 +37,30 @@ Future<void> 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<String> 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),
@@ -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<Map>().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<String> retryStageKeys(JsonMap run) {
final graph = run['graph'];
final stages = graph is Map ? graph['stages'] : null;
if (stages is! List) return const [];
final keys = <String>[];
for (final stage in stages.whereType<Map>()) {
final key = '${stage['key'] ?? ''}'.trim();
if (key.isNotEmpty && !keys.contains(key)) keys.add(key);
}
return keys;
}
@@ -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<String> stages;
/// Whether the run failed on an exhausted loop, so the choice is suggested.
final bool suggested;
final bool enabled;
final ValueChanged<int?> onVisitsChanged;
final ValueChanged<String?> 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<int>(
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<String?>(
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),
],
),
],
),
],
);
}
}
@@ -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.
@@ -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<String>('retry-run-action');
const retryKeepKey = ValueKey<String>('retry-run-keep');
const retryConfirmKey = ValueKey<String>('retry-run-confirm');
const retryRestartKey = ValueKey<String>('retry-run-restart');
const retryErrorKey = ValueKey<String>('retry-run-error');
const retryExtraVisitsKey = ValueKey<String>('retry-run-extra-visits');
const retryExtraCountKey = ValueKey<String>('retry-run-extra-count');
const retryExtraStageKey = ValueKey<String>('retry-run-extra-stage');
const retryExhaustedHintKey = ValueKey<String>('retry-run-exhausted-hint');
/// The retry dialog's title: `Retry run {id}?`.
String retryDialogTitle(num runId) => 'Retry run $runId?';
@@ -118,9 +118,18 @@ class RunsRepository {
num id, {
required String requestKey,
String? mode,
int? extraVisits,
String? extraStage,
}) async {
final fields = <String, dynamic>{'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');
}
@@ -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<DecisionOption> 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<String, String> 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<dynamic> 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());
@@ -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<FindingEvent> 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<RunFinding> runFindings(JsonMap? run) {
final list = run?['findings'];
if (list is! List) return const [];
return [
for (final item in list.whereType<Map>())
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<RunFinding> 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<RunFinding> findings) =>
openFindingCount(findings) > 0 ? 'open' : null;
/// The findings matching [status] (null = all) at or above [minSeverity]
/// (null = all), in their recorded order.
List<RunFinding> filterFindings(
Iterable<RunFinding> 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<FindingEvent> _events(dynamic value) {
if (value is! List) return const [];
return [
for (final item in value.whereType<Map>())
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));
+6 -1
View File
@@ -329,9 +329,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 {
@@ -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),
],
),
),
@@ -2,6 +2,7 @@ import '../../../core/api_gateway.dart';
import '../../pipelines/pipeline_format.dart';
import '../domain/run_deletion.dart' show formatByteSize, runSizeBytes;
import '../domain/run_failure_class.dart' show runBudgetText;
import '../domain/run_findings.dart' show visitGrantsSummary;
import '../domain/run_tokens.dart';
import 'run_detail_visit_facts.dart';
@@ -72,6 +73,7 @@ List<DetailSummaryRow> detailSummaryRows(JsonMap run, {DateTime? now}) {
add('Budget', runBudgetText(run));
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'] ?? ''}';
+4 -2
View File
@@ -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);
@@ -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<RunDetailTab> 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),
+14 -1
View File
@@ -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<RunDetailTabs> {
List<RunDetailTab> _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<RunDetailTabs> {
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<RunDetailTabs> {
selected: shown,
onSelected: select,
artifactCount: artifactCount,
openFindingCount: openFindings,
disabled: disabled,
disabledReasons: reasons,
),
@@ -471,6 +478,7 @@ class _RunDetailTabsState extends State<RunDetailTabs> {
selected: shown,
onSelected: select,
artifactCount: artifactCount,
openFindingCount: openFindings,
disabled: disabled,
disabledReasons: reasons,
);
@@ -568,6 +576,11 @@ class _RunDetailTabsState extends State<RunDetailTabs> {
);
// 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;
@@ -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<RunDetailTab> onSelected;
final int? artifactCount;
final int? openFindingCount;
final Set<RunDetailTab> 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!),
],
],
),
),
@@ -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<RunFinding> findings;
@override
State<RunFindingsTab> createState() => _RunFindingsTabState();
}
class _RunFindingsTabState extends State<RunFindingsTab> {
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 <String?>[null, ...findingStatuses])
ChoiceChip(
key: ValueKey('run-findings-status-${status ?? 'all'}'),
label: Text('${_statusLabel(status)} (${count(status)})'),
selected: _status == status,
onSelected: (_) => setState(() => _status = status),
),
DropdownMenu<FindingSeverity?>(
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,
};