import 'dart:convert'; import '../../../core/api_gateway.dart'; import '../../pipelines/pipeline_format.dart' show formatDuration; import '../domain/run_models.dart'; /// One labelled value in the run detail's metrics block. typedef DetailMetric = ({String label, String value}); /// One recorded visit in the run detail's timeline. /// /// [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, String title, String subtitle, String status, String outcome, String target, String? duration, }); /// The run's primary label: the stored title, else the pipeline name, and only /// then the numeric identity. String detailTitle(JsonMap run) { final identity = runIdentity(run['title'], run['name']); return identity.label.trim().isEmpty ? 'Run ${run['id']}' : identity.label; } String detailPipeline(JsonMap run) { final name = '${run['name'] ?? ''}'.trim(); return name.isEmpty ? 'unavailable' : name; } /// The original prompt exactly as the server stored it; never trimmed or /// replaced by another field. String? detailPrompt(JsonMap run) { final input = run['input']; return input is Map && input['prompt'] is String ? input['prompt'] as String : null; } /// Nested input/output shown as formatted, selectable JSON. String detailJson(dynamic value) => const JsonEncoder.withIndent(' ').convert(value); bool detailEmpty(dynamic value) => value is! Map || value.isEmpty; /// Reported run metrics. A present zero with a reporting stage count is a real /// zero; a zero without that evidence is unavailable, never a measured zero. List detailUsageMetrics(dynamic raw) { if (raw is! Map || raw.isEmpty) return const []; final usage = Map.from(raw); final stages = _int(usage['stages']); final tokenStages = _int(usage['tokens_known_stages']) ?? 0; final costStages = _int(usage['cost_known_stages']) ?? 0; final totalTokens = _int(usage['tokens_total']); final splitKnown = usage['split_known'] == true && tokenStages > 0; final rows = [ if (stages != null) (label: 'Stages', value: '$stages'), ( label: 'Total tokens', value: tokenStages == 0 || totalTokens == null ? 'Unavailable' : '$totalTokens', ), ( label: 'Input tokens', value: splitKnown ? '${_int(usage['tokens_in']) ?? 0}' : 'Unavailable', ), ( label: 'Output tokens', value: splitKnown ? '${_int(usage['tokens_out']) ?? 0}' : 'Unavailable', ), ( label: 'Reported cost', // cost_usd is omitted by the server when zero, so a known stage count // makes an absent value a real $0.000000 rather than an unknown cost. value: costStages == 0 ? 'Unavailable' : '\$${((usage['cost_usd'] as num?) ?? 0).toStringAsFixed(6)}', ), ]; if (stages != null && tokenStages < stages) { rows.add(( label: 'Token reporting', value: '$tokenStages of $stages stages', )); } if (stages != null && costStages < stages) { rows.add((label: 'Cost reporting', value: '$costStages of $stages stages')); } return rows; } /// Every recorded visit with its server sequence, in recorded order. List detailTimeline(dynamic steps) { if (steps is! List) return const []; return [ for (final step in steps.whereType()) ( stage: '${step['stage'] ?? ''}'.trim(), sequence: step['sequence'] is num ? (step['sequence'] as num).toInt() : null, title: '${_text(step['stage'], 'Stage unavailable')} · visit ' '${step['sequence'] is num ? (step['sequence'] as num).toInt() : 'unavailable'}', subtitle: _visitSubtitle(step), status: '${step['status'] ?? ''}'.trim(), outcome: '${step['outcome'] ?? ''}'.trim(), target: '${step['target'] ?? ''}'.trim(), duration: _visitDuration(step), ), ]; } /// 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 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); } 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;