Runs list carries per-run token usage; app shows tokens beside size, Most tokens sort, Summary and stage tokens

This commit is contained in:
2026-11-03 22:04:55 +00:00
parent fa6c0864db
commit aa948bdfe4
19 changed files with 620 additions and 30 deletions
@@ -1,5 +1,6 @@
import '../../pipelines/pipeline_format.dart';
import '../../../core/api_gateway.dart';
import 'run_tokens.dart';
const runStates = [
'queued',
@@ -268,6 +269,19 @@ List<JsonMap> sortRuns(List<JsonMap> runs, {String sort = 'newest_first'}) {
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
}
break;
case 'most_tokens':
// Runs with no reported tokens (older servers, no model stage) sort
// after every reported total; a partial total sorts by what was
// reported.
final ta = runTokenUsage(a)?.total, tb = runTokenUsage(b)?.total;
primary = cmp(ta == null ? 1 : 0, tb == null ? 1 : 0);
if (primary == 0 && ta != null && tb != null) {
primary = tb.compareTo(ta);
}
if (primary == 0) {
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
}
break;
case 'pipeline_name':
primary = '${a['name'] ?? ''}'.toLowerCase().compareTo(
'${b['name'] ?? ''}'.toLowerCase(),
@@ -0,0 +1,145 @@
import '../../../core/api_gateway.dart';
/// Reported token and cost usage of a run or one stage. No widgets here.
///
/// Every figure is what the server recorded from the harness: nothing is
/// estimated. A run total is partial when some stages that recorded usage
/// reported no token count, and it is then labelled as a lower bound (`≥`).
class TokenUsage {
const TokenUsage({
required this.total,
required this.partial,
this.input,
this.output,
this.cost,
this.costPartial = false,
this.stages,
this.tokenStages,
});
/// The summed reported total.
final int total;
/// Some stages that recorded usage reported no token count.
final bool partial;
/// The input/output split, only when every counted stage reported it.
final int? input;
final int? output;
/// The reported cost in USD, only when some stage reported one.
final double? cost;
/// Some stages reported no cost, so [cost] is a lower bound.
final bool costPartial;
/// Run totals only: the stages that recorded usage, and those of them that
/// reported tokens.
final int? stages;
final int? tokenStages;
}
/// The run's reported token usage from its `usage` total, or null when the
/// server sent none (an older server's list, or a run with no model usage) or
/// no stage reported a token count.
TokenUsage? runTokenUsage(JsonMap run) {
final raw = run['usage'];
if (raw is! Map) return null;
final stages = _int(raw['stages']);
final tokenStages = _int(raw['tokens_known_stages']) ?? 0;
final total = _int(raw['tokens_total']);
if (tokenStages <= 0 || total == null) return null;
final costStages = _int(raw['cost_known_stages']) ?? 0;
final split = raw['split_known'] == true;
return TokenUsage(
total: total,
partial: stages != null && tokenStages < stages,
// The server omits a zero in/out, so a known split makes absence zero.
input: split ? _int(raw['tokens_in']) ?? 0 : null,
output: split ? _int(raw['tokens_out']) ?? 0 : null,
cost: costStages > 0 ? _double(raw['cost_usd']) ?? 0 : null,
costPartial: costStages > 0 && stages != null && costStages < stages,
stages: stages,
tokenStages: tokenStages,
);
}
/// One stage's reported token usage from its step `usage`, or null when the
/// stage reported no token count.
TokenUsage? stageTokenUsage(JsonMap step) {
final raw = step['usage'];
if (raw is! Map || raw['tokens_known'] != true) return null;
final total = _int(raw['tokens_total']);
if (total == null) return null;
final split = raw['split_known'] == true;
return TokenUsage(
total: total,
partial: false,
input: split ? _int(raw['tokens_in']) ?? 0 : null,
output: split ? _int(raw['tokens_out']) ?? 0 : null,
cost: raw['cost_known'] == true ? _double(raw['cost_usd']) ?? 0 : null,
);
}
/// A compact token count: `950`, `1.2K`, `340K`, `22.4M`, `1.3B`.
///
/// Decimal multiples, one decimal below a hundred units, whole units above.
String formatTokenCount(int tokens) {
if (tokens < 1000) return '$tokens';
const units = ['K', 'M', 'B', 'T'];
var value = tokens / 1000;
var unit = 0;
while (value >= 1000 && unit < units.length - 1) {
value /= 1000;
unit++;
}
// Rounding 999.6K up would print "1000K"; promote it instead.
if (value >= 999.5 && unit < units.length - 1) {
value /= 1000;
unit++;
}
final text = value < 99.95
? value.toStringAsFixed(1).replaceFirst(RegExp(r'\.0$'), '')
: value.round().toString();
return '$text${units[unit]}';
}
/// The list row's compact label: `22.4M tokens`, or `≥22.4M tokens` when some
/// stages did not report a count.
String tokenUsageLabel(TokenUsage usage) =>
'${usage.partial ? '≥' : ''}${formatTokenCount(usage.total)} tokens';
/// The detail's token value: the compact total, the in/out split when
/// reported, and how many stages reported when the total is partial.
/// `22.4M (20M in, 2.4M out)`, `≥9 · 1 of 2 stages reported`.
String tokenUsageDetail(TokenUsage usage) {
final parts = <String>[
[
'${usage.partial ? '≥' : ''}${formatTokenCount(usage.total)}',
if (usage.input != null && usage.output != null)
'(${formatTokenCount(usage.input!)} in, '
'${formatTokenCount(usage.output!)} out)',
].join(' '),
if (usage.partial && usage.stages != null)
'${usage.tokenStages} of ${usage.stages} stages reported',
];
return parts.join(' · ');
}
/// The reported cost, or null when no stage reported one: `$1.75`, `$0.10`,
/// `$0.0042` (four places below a cent),
/// `≥$0.10` when some stages reported no cost.
String? tokenUsageCost(TokenUsage usage) {
final cost = usage.cost;
if (cost == null) return null;
final text = cost >= 0.01 || cost == 0
? cost.toStringAsFixed(2)
: cost.toStringAsFixed(4);
return '${usage.costPartial ? '≥' : ''}\$$text';
}
int? _int(dynamic value) =>
value is num && value.isFinite && value >= 0 ? value.round() : null;
double? _double(dynamic value) =>
value is num && value.isFinite && value >= 0 ? value.toDouble() : null;
@@ -3,6 +3,7 @@ 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});
@@ -23,6 +24,7 @@ typedef DetailVisit = ({
String outcome,
String target,
String? duration,
String? tokens,
});
/// The run's primary label: the stored title, else the pipeline name, and only
@@ -149,6 +151,10 @@ List<DetailVisit> detailTimeline(dynamic steps) {
outcome: '${step['outcome'] ?? ''}'.trim(),
target: '${step['target'] ?? ''}'.trim(),
duration: _visitDuration(step),
tokens: switch (stageTokenUsage(JsonMap.from(step))) {
final usage? => tokenUsageLabel(usage),
null => null,
},
);
}(),
];
@@ -1,5 +1,7 @@
import '../../../core/api_gateway.dart';
import '../../pipelines/pipeline_format.dart';
import '../domain/run_deletion.dart' show formatByteSize, runSizeBytes;
import '../domain/run_tokens.dart';
import 'run_detail_visit_facts.dart';
/// One recorded Summary row: the web run summary's key/value shape.
@@ -14,9 +16,9 @@ typedef DetailSummaryRow = ({
bool block,
});
/// The run Summary's rows, in the web summary's order: Pipeline, Stage,
/// Workspace, Content hash, Started, Finished, Duration, Retry of and the
/// Diagnostic block.
/// The run Summary's rows: Pipeline, Stage, Workspace, Content hash, Started,
/// Finished, Duration, Size on disk, Tokens, Cost, Retry of and the Diagnostic
/// block.
///
/// Only values the server actually recorded are rows: a blank field is omitted
/// rather than drawn as an empty or invented placeholder, exactly as
@@ -53,6 +55,16 @@ List<DetailSummaryRow> detailSummaryRows(JsonMap run) {
_text(run['finished_at']),
);
if (seconds != null) add('Duration', formatDuration(seconds));
// What the run occupies on disk and what it spent, as the server measured
// and the harness reported; an unmeasured size or unreported usage has no
// row.
final bytes = runSizeBytes(run);
if (bytes != null) add('Size on disk', formatByteSize(bytes));
final usage = runTokenUsage(run);
if (usage != null) {
add('Tokens', tokenUsageDetail(usage));
add('Cost', tokenUsageCost(usage));
}
final retryOf = _number(run['retry_of'])?.toInt() ?? 0;
if (retryOf > 0) add('Retry of', 'run $retryOf');
// A diagnostic is a recorded document: its own whitespace is preserved, but a
@@ -16,7 +16,7 @@ import '../../../ui/adaptive/floating_bar_layout.dart';
/// the stored original prompt with its copy control and the collapsible Input
/// and Output sections.
///
/// The web run detail has no usage block, so no metrics are drawn here. A fact
/// The run's size and reported token usage are facts like the others. A fact
/// the server did not record is omitted rather than shown as an invented or
/// `Unavailable` row; only the Input/Output empty sentences remain, and only
/// when that section recorded nothing.
@@ -135,8 +135,8 @@ class RunTimelineRow extends StatelessWidget {
@override
Widget build(BuildContext context) {
final state = _state;
// The outcome chip leads the second line, then where the visit went; the
// duration is the row's time.
// The outcome chip leads the second line, then where the visit went and
// the tokens it reported; the duration is the row's time.
return AppListRow(
cupertino: cupertino,
selected: selected,
@@ -152,7 +152,14 @@ class RunTimelineRow extends StatelessWidget {
title: Text(visit.title),
time: visit.duration,
subtitleLeading: _outcome(context),
subtitle: visit.target.isEmpty ? null : Text('→ ${visit.target}'),
subtitle: visit.target.isEmpty && visit.tokens == null
? null
: Text(
[
if (visit.target.isNotEmpty) '→ ${visit.target}',
?visit.tokens,
].join(' · '),
),
);
}
}
@@ -1,6 +1,7 @@
import '../../../core/api_gateway.dart';
import '../../graph/domain/stage_definition.dart';
import '../../pipelines/pipeline_format.dart';
import '../domain/run_tokens.dart';
import 'run_detail_content.dart';
/// The exact empty wording for a visit's recorded Input and Output. They are
@@ -80,6 +81,12 @@ List<VisitFact> detailVisitFacts(JsonMap step) {
if (duration != null) facts.add((label: 'Duration', value: duration));
final model = detailVisitProviderModel(step);
if (model != null) facts.add((label: 'Provider/model', value: model));
final usage = stageTokenUsage(step);
if (usage != null) {
facts.add((label: 'Tokens', value: tokenUsageDetail(usage)));
final cost = tokenUsageCost(usage);
if (cost != null) facts.add((label: 'Cost', value: cost));
}
final target = _text(step['target']);
if (target != null) facts.add((label: 'Target', value: target));
return facts;
@@ -9,6 +9,7 @@ import '../../../ui/status/run_status_icon.dart';
import '../../../ui/text/relative_time_label.dart';
import '../domain/run_deletion.dart';
import '../domain/run_models.dart';
import '../domain/run_tokens.dart';
import 'run_more_menu.dart';
/// One run in the list: a status avatar, title/time, and one muted fact
@@ -77,6 +78,9 @@ class RunListRow extends StatelessWidget {
final scheduled = run['scheduled'] == true;
final bytes = runSizeBytes(run);
final size = bytes == null ? null : formatByteSize(bytes);
// Reported tokens sit beside the size; an older server sends none.
final usage = runTokenUsage(run);
final tokens = usage == null ? null : tokenUsageLabel(usage);
final createdAt = DateTime.tryParse('${run['created_at'] ?? ''}');
final subtitle = [
?pipelineLabel,
@@ -84,6 +88,7 @@ class RunListRow extends StatelessWidget {
?facts.duration,
?facts.progress,
?size,
?tokens,
].join(' · ');
// A narrow pane keeps the decision facts: the pipeline, and progress
// while executing (duration only when there is no pipeline to show).
@@ -93,6 +98,7 @@ class RunListRow extends StatelessWidget {
if (run['executing'] == true && facts.progress != null) facts.progress!,
if (pipelineLabel == null && facts.duration != null) facts.duration!,
?size,
?tokens,
].join(' · ');
final state = runStateOf(run['status']);
return AppListRow(
@@ -162,14 +162,7 @@ class RunsController extends ChangeNotifier {
// A cancel/decision reply changes lifecycle fields as well as title.
// Keep sparse/unknown summary fields, without copying bulky detail-only
// payloads into the held list or inventing missing values.
const detailOnly = {
'steps',
'input',
'output',
'graph',
'usage',
'notifications',
};
const detailOnly = {'steps', 'input', 'output', 'graph', 'notifications'};
runs = [...runs]
..[index] = {
...runs[index],
@@ -7,6 +7,7 @@ const runSorts = [
('newest_first', 'Newest first'),
('oldest_first', 'Oldest first'),
('largest_first', 'Largest first'),
('most_tokens', 'Most tokens'),
('longest_duration', 'Longest duration'),
('shortest_duration', 'Shortest duration'),
('pipeline_name', 'Pipeline name'),
@@ -25,8 +26,8 @@ const runTimeRanges = [
];
/// Sorts that list runs flat instead of under day headings: an order by
/// size has no meaningful day grouping.
const flatRunSorts = {'largest_first'};
/// size or token count has no meaningful day grouping.
const flatRunSorts = {'largest_first', 'most_tokens'};
/// The pipelines the loaded runs belong to, by name then id.
List<({int id, String name})> runFilterPipelines(RunsController controller) {