import 'dart:convert'; import '../../../core/api_gateway.dart'; import '../../pipelines/pipeline_format.dart' show formatDuration; import '../domain/run_models.dart'; import '../domain/run_tokens.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. /// /// [stage] and [sequence] are the visit's exact recorded identity, so the /// Graph tab can select the row of the stage it was clicked for without /// guessing from the display title. [sequence] is null only when the server /// sent no usable sequence. typedef DetailVisit = ({ String stage, int? sequence, int visit, String title, String subtitle, String status, String outcome, String target, String? duration, DateTime? runningSince, String? tokens, }); /// 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; } /// The run's context under its title in the top bar: its number, then the /// pipeline it ran and the pinned version when recorded /// (`Run 7 · Demo pipeline · v3`). String detailSubtitle(JsonMap run) { final name = '${run['name'] ?? ''}'.trim(); final version = run['version']; return [ 'Run ${run['id']}', if (name.isNotEmpty) name, if (version is num && version > 0) 'v${version.toInt()}', ].join(' · '); } 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 cost = usage['cost_usd'] is num ? usage['cost_usd'] as num : null; 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', // A cost of zero (or none) is what subscription models report even // with a "known" cost: it is not reported, never a measured zero. value: costStages == 0 || cost == null || cost <= 0 ? 'Not reported' : '\$${cost.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 []; final records = steps.whereType().toList(growable: false); final ordered = List.generate(records.length, (index) => index) ..sort((a, b) { final bySequence = (_int(records[a]['sequence']) ?? 0).compareTo( _int(records[b]['sequence']) ?? 0, ); return bySequence != 0 ? bySequence : a.compareTo(b); }); final positions = {}; final visits = {}; for (final index in ordered) { final stage = '${records[index]['stage'] ?? ''}'.trim(); final position = (positions[stage] ?? 0) + 1; positions[stage] = position; visits[index] = _displayVisit(records[index], position); } return [ for (var index = 0; index < records.length; index += 1) () { final step = records[index]; final stage = '${step['stage'] ?? ''}'.trim(); final visit = visits[index]!; return ( stage: stage, sequence: step['sequence'] is num ? (step['sequence'] as num).toInt() : null, visit: visit, title: '${_text(step['stage'], 'Stage unavailable')} · Visit $visit', subtitle: _visitSubtitle(step), status: '${step['status'] ?? ''}'.trim(), outcome: '${step['outcome'] ?? ''}'.trim(), target: '${step['target'] ?? ''}'.trim(), duration: _visitDuration(step), runningSince: _visitRunningSince(step), tokens: switch (stageTokenUsage(JsonMap.from(step))) { final usage? => stageTokenRowLabel(usage), null => null, }, ); }(), ]; } /// The latest recorded visit of [stageKey], or null when this run never /// recorded that stage. /// /// The Graph tab opens the same latest visit the web client opens. An /// unvisited node has no visit here, so no row is invented for it. DetailVisit? latestDetailVisit(dynamic steps, String stageKey) { DetailVisit? latest; for (final visit in detailTimeline(steps)) { if (visit.stage == stageKey) latest = visit; } return latest; } /// The run's own pinned definition graph, or null when the reply omitted it. /// /// The server sends the graph it pinned for the run's pipeline version; the /// detail never reconstructs one from the current source. JsonMap? detailGraph(JsonMap run) { final graph = run['graph']; return graph is Map ? JsonMap.from(graph) : null; } 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(' · '); } /// The stage's own recorded visit number, falling back to its position among /// visits to that stage rather than the run-wide step sequence. int _displayVisit(Map step, int position) { final control = step['control']; final recorded = control is Map ? control['visit'] : null; if (recorded is num && recorded > 0) return recorded.toInt(); return position; } /// The web's `stepDuration`: finished minus started, when both are recorded. String? _visitDuration(Map step) { final started = DateTime.tryParse('${step['started_at'] ?? ''}'); final finished = DateTime.tryParse('${step['finished_at'] ?? ''}'); if (started == null || finished == null) return null; final seconds = finished.difference(started).inSeconds; return seconds < 0 ? null : formatDuration(seconds); } /// When a running visit started, so its row can show the elapsed time; null /// for a visit that is not running, finished, or recorded no start. DateTime? _visitRunningSince(Map step) { if ('${step['status'] ?? ''}'.trim().toLowerCase() != 'running') return null; if ('${step['finished_at'] ?? ''}'.trim().isNotEmpty) return null; return DateTime.tryParse('${step['started_at'] ?? ''}'.trim()); } 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;