feat(app): add native authored stage definition pane

This commit is contained in:
2026-10-21 22:26:34 +01:00
parent 76fb2cdd87
commit d88213deb4
7 changed files with 1529 additions and 0 deletions
@@ -0,0 +1,212 @@
import 'graph_definition.dart';
import 'graph_protocol.dart';
/// The read-only definition of one declared stage, as field rows.
///
/// Mirrors `stageDefinitionFields`/`terminalFields` from `web/src/graph.js`:
/// the same labels, the same order, and the same rule that blank fields are
/// omitted rather than shown as an empty row. Pure data only: nothing here
/// reads run visits, so a definition can be inspected without claiming that a
/// stage executed.
class StageDefinitionField {
const StageDefinitionField(this.label, this.value, {this.block = false});
final String label;
final String value;
/// Multi-line content (prompt, output, outcomes, tools, memory, routes).
final bool block;
}
/// The one stage declaration [key] names, or null when this version does not
/// declare it.
///
/// The last declaration wins, matching the web pane's `new Map(stages)`.
Map<String, dynamic>? stageDefinitionFor(dynamic graph, String key) {
final stages = graph is Map ? graph['stages'] : null;
if (stages is! List) return null;
Map<String, dynamic>? found;
for (final stage in stages) {
if (stage is Map && _text(stage['key']) == key) {
found = Map<String, dynamic>.from(stage);
}
}
return found;
}
/// A stage's effective type: a blank/absent type reads `model`, exactly as
/// `effectiveStageType` in `web/src/templates.js`.
String effectiveStageType(dynamic type) {
final text = _text(type);
return text.trim().isEmpty ? 'model' : text;
}
/// A config key's display label (`configLabel` in `web/src/graph.js`).
String stageConfigLabel(String key) {
switch (key) {
case 'provider':
return 'Provider';
case 'model':
return 'Model';
case 'retries':
return 'Retries';
case 'timeout':
return 'Timeout';
case 'budget_usd':
return 'Budget (USD)';
case 'budget_tokens':
return 'Budget (tokens)';
case 'harness':
return 'Harness';
default:
return key;
}
}
/// The definition fields of one stage declaration, in the web pane's order.
///
/// Only non-blank fields are emitted. Unknown keys are deliberately not
/// interpreted here; the pane keeps the stage's raw JSON so they stay visible.
List<StageDefinitionField> stageDefinitionFields(dynamic stage) {
if (stage is! Map) return const <StageDefinitionField>[];
final fields = <StageDefinitionField>[
StageDefinitionField('Type', effectiveStageType(stage['type'])),
];
final prompt = _text(stage['prompt']);
if (prompt.trim().isNotEmpty) {
fields.add(StageDefinitionField('Prompt', prompt, block: true));
}
final output = _text(stage['output']);
if (output.trim().isNotEmpty) {
fields.add(StageDefinitionField('Output', output, block: true));
}
final edges = stage['edges'];
final outcomes = <String>[];
for (final outcome in stageOutcomes(stage)) {
final raw = edges is Map ? edges[outcome] : null;
final target = resolveTarget(outcome, raw == null ? '' : _text(raw)) ?? '';
final suffix = isTerminalTarget(target) ? ' (terminal)' : '';
outcomes.add('$outcome \u2192 ${nodeLabel(target)}$suffix');
}
if (outcomes.isNotEmpty) {
fields.add(
StageDefinitionField('Outcomes', outcomes.join('\n'), block: true),
);
}
final configs = stage['configs'];
if (configs is Map) {
final entries = configs.entries.toList()
..sort((a, b) => _text(a.key).compareTo(_text(b.key)));
for (final entry in entries) {
final value = _text(entry.value);
if (entry.value == null || value.trim().isEmpty) continue;
fields.add(
StageDefinitionField(stageConfigLabel(_text(entry.key)), value),
);
}
}
final blocks = stage['blocks'];
if (blocks is Map) {
final tools = blocks['tools'];
final text = _text(tools);
if (tools != null && text.trim().isNotEmpty) {
fields.add(StageDefinitionField('Tools', text, block: true));
}
}
final limits = stage['limits'];
if (limits is Map) {
final maxVisits = limits['max_visits'];
final visits = maxVisits is num
? maxVisits
: num.tryParse(_text(maxVisits));
if (visits != null && visits > 0) {
fields.add(StageDefinitionField('Max visits', _text(maxVisits)));
}
final on = _items(limits['on']);
if (on.isNotEmpty) {
fields.add(StageDefinitionField('Limit on', on.join(', ')));
}
}
final memory = stage['memory'];
if (memory is Map && memory.isNotEmpty) {
fields.add(
StageDefinitionField(
'Memory',
[
for (final entry in memory.entries)
'${_text(entry.key)}: ${_text(entry.value)}',
].join('\n'),
block: true,
),
);
}
final notify = stage['notify'];
if (notify is Map) {
final on = _items(notify['on']);
if (on.isNotEmpty) {
fields.add(StageDefinitionField('Notify on', on.join(', ')));
}
final destination = _text(notify['destination']);
if (destination.trim().isNotEmpty) {
fields.add(StageDefinitionField('Notify destination', destination));
}
final artifacts = _items(notify['artifacts']);
if (artifacts.isNotEmpty) {
fields.add(
StageDefinitionField('Notify artifacts', artifacts.join(', ')),
);
}
}
return fields;
}
/// A terminal pane's fields: the declared routes into that target.
///
/// A terminal is part of the definition, not evidence that a run reached it.
List<StageDefinitionField> terminalDefinitionFields(dynamic graph, String key) {
final lines = <String>[
for (final edge in graphEdges(graph))
if (edge.target == key)
'${edge.source} \u00b7 ${edge.label} \u2192 ${nodeLabel(key)}',
];
return lines.isEmpty
? const <StageDefinitionField>[]
: <StageDefinitionField>[
StageDefinitionField(
'Incoming routes',
lines.join('\n'),
block: true,
),
];
}
List<String> _items(dynamic value) {
if (value is! List) return const <String>[];
return <String>[for (final item in value) _text(item)];
}
/// Web `String(value)` for the values the definition fields carry. Numbers
/// that are integral render without a trailing `.0`, as JavaScript does; a
/// complex value stays visible but its exact shape is preserved by the raw
/// JSON section instead.
String _text(dynamic value) {
if (value == null) return '';
if (value is String) return value;
if (value is num) {
if (value.isFinite &&
value == value.roundToDouble() &&
value.abs() < 1e21) {
return value.toInt().toString();
}
return value.toString();
}
return value.toString();
}
@@ -0,0 +1,241 @@
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../../../ui/adaptive/host.dart';
import '../domain/graph_protocol.dart';
import '../domain/stage_definition.dart';
/// Wording for a stage that this pinned definition does not declare.
const String unknownStageDefinition =
'This stage is not declared in this pipeline version. '
'No definition has been reconstructed.';
/// The web pane's message when a node has no recorded stage or incoming routes.
const String noStageDefinitionDetails = 'No details recorded for this node.';
/// Terminals are definition targets; this pane never presents one as evidence.
const String terminalDefinitionNote =
'Success and Failure are definition targets, not recorded visits. '
'This pane shows where the definition routes.';
/// The raw section's heading: unknown stage fields stay visible and selectable.
const String rawStageDefinitionTitle = 'Raw stage definition';
/// A read-only native view of one stage's declared definition.
///
/// [graph] is the graph pinned for exactly [pipelineId]/[version] and
/// [stageKey] is a node key (a stage or `#success`/`#failure`). Nothing is
/// fetched and no run visit is read, so the pane cannot imply that the stage
/// executed. Unknown stage declarations get an explicit missing state; every
/// declared stage also keeps its exact JSON below the structured fields.
class StageDefinitionView extends StatelessWidget {
const StageDefinitionView({
super.key,
required this.graph,
required this.stageKey,
required this.pipelineId,
required this.pipelineName,
required this.version,
});
final JsonMap graph;
final String stageKey;
final int pipelineId;
final String pipelineName;
final int version;
String get _identity =>
'${pipelineName.isEmpty ? 'Pipeline' : pipelineName} \u00b7 v$version';
@override
Widget build(BuildContext context) {
final style = _StageDefinitionStyle.of(context);
final stage = stageDefinitionFor(graph, stageKey);
final terminal = isTerminalTarget(stageKey);
final fields = stage != null
? stageDefinitionFields(stage)
: terminal
? terminalDefinitionFields(graph, stageKey)
: const <StageDefinitionField>[];
return ListView(
padding: const EdgeInsets.all(16),
children: [
Text(_identity, style: style.muted),
const SizedBox(height: 16),
if (stage == null && !terminal)
Text(unknownStageDefinition, style: style.value)
else ...[
if (terminal) ...[
Text(terminalDefinitionNote, style: style.muted),
const SizedBox(height: 16),
],
for (final field in fields)
_StageDefinitionFieldView(field: field, style: style),
if (terminal && fields.isEmpty)
Text(noStageDefinitionDetails, style: style.muted),
if (stage != null) ...[
const SizedBox(height: 8),
Text(rawStageDefinitionTitle, style: style.heading),
const SizedBox(height: 8),
_SelectableDefinitionText(
value: const JsonEncoder.withIndent(' ').convert(stage),
style: style.value,
),
],
],
],
);
}
}
/// Opens the platform's native full-screen stage-definition page.
///
/// The page owns the single navigation bar and its standard back control; the
/// caller only supplies the pinned graph and identity. This is the hook the
/// pipeline graph uses when a node is selected.
Future<void> openStageDefinition(
BuildContext context, {
required JsonMap graph,
required String stageKey,
required int pipelineId,
required String pipelineName,
required int version,
}) {
final view = StageDefinitionView(
graph: graph,
stageKey: stageKey,
pipelineId: pipelineId,
pipelineName: pipelineName,
version: version,
);
final settings = RouteSettings(
name: 'stage-definition/$pipelineId/$version/$stageKey',
);
// A terminal is a definition target, not its protocol key: the web pane
// titles it with `nodeDisplayLabel` (`Failure`/`Success`).
final title = '${nodeDisplayLabel(stageKey)} definition';
final route = usesCupertinoHost(context)
? CupertinoPageRoute<void>(
settings: settings,
builder: (_) => CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(middle: Text(title)),
child: SafeArea(child: view),
),
)
: MaterialPageRoute<void>(
settings: settings,
builder: (_) => Scaffold(
appBar: AppBar(title: Text(title)),
body: SafeArea(child: view),
),
);
return Navigator.of(context).push(route);
}
/// One labelled field: a compact row for scalars, a selectable block when the
/// value is multi-line authored text.
class _StageDefinitionFieldView extends StatelessWidget {
const _StageDefinitionFieldView({required this.field, required this.style});
final StageDefinitionField field;
final _StageDefinitionStyle style;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(field.label, style: style.label),
const SizedBox(height: 4),
if (field.block)
_SelectableDefinitionText(value: field.value, style: style.value)
else
Text(field.value, style: style.value),
],
),
);
}
}
/// Authored definition text in the host's selectable body.
///
/// The semantic leaf carries the exact value: Flutter web maps a
/// [SelectableText] to an empty read-only field, so without this a screen
/// reader (and a browser check) sees only its label. The child keeps native
/// pointer selection and the host's system typography.
///
/// The strut is derived from that same host style and forced, so a glyph the
/// host font lacks (the outcomes arrow `→` is one example) cannot pull in a
/// fallback font with taller metrics and double-space only that block. It is
/// the host's own line metrics, not a font override or a fixed height.
class _SelectableDefinitionText extends StatelessWidget {
const _SelectableDefinitionText({required this.value, required this.style});
final String value;
final TextStyle style;
@override
Widget build(BuildContext context) {
return Semantics(
label: value,
child: ExcludeSemantics(
child: SelectableText(
value,
style: style,
strutStyle: StrutStyle.fromTextStyle(style, forceStrutHeight: true),
),
),
);
}
}
/// Host text roles only: no palette, font family or explicit size.
class _StageDefinitionStyle {
const _StageDefinitionStyle({
required this.label,
required this.value,
required this.muted,
required this.heading,
});
factory _StageDefinitionStyle.of(BuildContext context) {
if (usesCupertinoHost(context)) {
final theme = CupertinoTheme.of(context);
final secondary = CupertinoColors.secondaryLabel.resolveFrom(context);
return _StageDefinitionStyle(
label: theme.textTheme.tabLabelTextStyle.copyWith(color: secondary),
// SelectableText needs a style it can merge into the default text
// style; Cupertino's textStyle is a complete style with `inherit: false`
// and no baseline.
value: theme.textTheme.textStyle.copyWith(inherit: true),
muted: theme.textTheme.textStyle.copyWith(
inherit: true,
color: secondary,
),
heading: theme.textTheme.navTitleTextStyle,
);
}
final theme = Theme.of(context);
return _StageDefinitionStyle(
label: (theme.textTheme.labelMedium ?? const TextStyle()).copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
value: theme.textTheme.bodyMedium ?? const TextStyle(),
muted: (theme.textTheme.bodySmall ?? const TextStyle()).copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
heading: theme.textTheme.titleSmall ?? const TextStyle(),
);
}
final TextStyle label;
final TextStyle value;
final TextStyle muted;
final TextStyle heading;
}