Merge branch 'main' into flutter/pipeline-stage-deeplink

This commit is contained in:
2026-10-22 11:42:14 +01:00
31 changed files with 2187 additions and 43 deletions
+28 -6
View File
@@ -11,13 +11,24 @@ class AppRouteParser extends RouteInformationParser<AppRoute> {
@override
Future<AppRoute> parseRouteInformation(
RouteInformation routeInformation,
) async => AppRoute.parse(routeInformation.uri.path);
) async => AppRoute.parse(routeLocation(routeInformation.uri));
@override
RouteInformation restoreRouteInformation(AppRoute configuration) =>
RouteInformation(uri: Uri(path: configuration.path));
// The route's path already carries its query (`?visit=N`, `?action=…`).
// Parsing it keeps that query a query instead of percent-encoding the
// `?` into the path, which would make a reload read one bogus key.
RouteInformation(uri: Uri.parse(configuration.path));
}
/// The app-relative location of [uri]: its path plus query, without origin.
///
/// [AppRoute.parse] understands this form, so a browser location such as
/// `/runs/7/stage/plan?visit=1` keeps the query instead of losing it to
/// `Uri.path`. A fragment is not part of an app route.
String routeLocation(Uri uri) =>
uri.hasQuery ? '${uri.path}?${uri.query}' : uri.path;
/// Owns the app's current route and builds the shell for it.
///
/// Route changes made by the operator go through [goTo]; the Router reports
@@ -217,10 +228,21 @@ class AppRouterDelegate extends RouterDelegate<AppRoute> with ChangeNotifier {
/// The location a web launch starts at, or the Pipelines list elsewhere.
///
/// Only the path is meaningful to [AppRouteParser]; the origin stays out of
/// route configuration so a serialised route is always app-relative.
/// The origin stays out of route configuration so a serialised route is always
/// app-relative, but the path and its query are both part of the route: a
/// launch at `/runs/7/stage/plan?visit=1` must open exactly that visit.
RouteInformation initialRouteInformation() {
if (!kIsWeb) return RouteInformation(uri: Uri(path: '/pipelines'));
final path = Uri.base.path;
return RouteInformation(uri: Uri(path: path.isEmpty ? '/' : path));
return routeInformationForLocation(Uri.base);
}
/// The app-relative route information for a browser [base] location.
///
/// Exposed for the boot test: [Uri.base] cannot be changed inside a widget
/// test, so the web launch seam is exercised through this function.
@visibleForTesting
RouteInformation routeInformationForLocation(Uri base) {
final path = base.path.isEmpty ? '/' : base.path;
final query = base.hasQuery ? '?${base.query}' : '';
return RouteInformation(uri: Uri.parse('$path$query'));
}
+8 -3
View File
@@ -83,10 +83,13 @@ class _PipelinesAppState extends State<PipelinesApp> {
);
// A malformed or unknown boot path renders Pipelines, so make the address
// bar agree with the rendered destination instead of showing a dead link.
final initial = AppRoute.parse(_provider.value.uri.path);
if (_provider.value.uri.path != initial.path) {
// The comparison includes the query: `?visit=N` is part of the route, while
// a dropped or unknown query is canonicalised away.
final location = routeLocation(_provider.value.uri);
final initial = AppRoute.parse(location);
if (location != initial.path) {
_provider.routerReportsNewRouteInformation(
RouteInformation(uri: Uri(path: initial.path)),
RouteInformation(uri: Uri.parse(initial.path)),
type: RouteInformationReportingType.neglect,
);
}
@@ -218,6 +221,8 @@ class _PipelinesAppState extends State<PipelinesApp> {
session: _session,
server: widget.server,
initialRunId: route.runId,
initialStageKey: route.stageKey,
initialVisit: route.visit,
listRefreshToken: _runsRefresh,
notifications: _notifications,
onRunSelected: (id) => _delegate.goTo(AppRoute.run(id)),
+11
View File
@@ -19,6 +19,8 @@ class RunsDestination extends StatelessWidget {
required this.session,
required this.server,
this.initialRunId,
this.initialStageKey,
this.initialVisit,
this.onRunSelected,
this.onBack,
this.listRefreshToken = 0,
@@ -28,6 +30,13 @@ class RunsDestination extends StatelessWidget {
final AppSession session;
final ServerEndpoint server;
final int? initialRunId;
/// The stage key and optional visit a `/runs/:id/stage/:key[?visit=N]` route
/// names. They reach the detail only through [RunsScreen]; the destination
/// does not read the route itself.
final String? initialStageKey;
final int? initialVisit;
final ValueChanged<int>? onRunSelected;
final VoidCallback? onBack;
@@ -73,6 +82,8 @@ class RunsDestination extends StatelessWidget {
Widget _runsScreen() => RunsScreen(
gateway: session.gateway,
initialRunId: initialRunId,
initialStageKey: initialStageKey,
initialVisit: initialVisit,
syncToken: session.connectionEpoch,
listRefreshToken: listRefreshToken,
notifications: notifications,
@@ -4,6 +4,8 @@ import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../domain/chat_attachment_draft.dart';
import '../domain/chat_attachment_picker.dart';
import '../ui/sessions/chat_adaptive.dart';
import 'chat_composer_controller.dart';
@@ -14,6 +16,9 @@ const String chatComposerPlaceholder = 'Message the agent… or / for commands';
const String chatSendLabel = 'Send';
const String chatStopLabel = 'Stop';
/// The attach control's accessible name, verbatim from the web composer.
const String chatAttachLabel = 'Attach file';
/// Shown while the reply says this prompt waits behind the running turn.
const String chatQueuedNotice =
'Queued — it will send when the current turn finishes.';
@@ -24,13 +29,15 @@ const String chatQueuedNotice =
/// The field owns only its [TextEditingController] and focus; the durable draft
/// text lives in the composer controller, so a live transcript rebuild never
/// replaces the operator's caret. Enter inserts a newline and Ctrl/Cmd+Enter
/// sends the plain message. Attachments and the slash palette are not part of
/// this slice.
/// sends the plain message. Picked files are memory-only chips: their names are
/// shown with the host's own remove action and the bounded draft owns every
/// refusal. Sending does not yet carry attachments, and paste is not wired.
class ChatComposerBar extends StatefulWidget {
const ChatComposerBar({
super.key,
required this.composer,
required this.running,
this.picker,
});
final ChatComposerController composer;
@@ -38,6 +45,9 @@ class ChatComposerBar extends StatefulWidget {
/// The thread controller's running bit; it alone decides Send versus Stop.
final bool running;
/// The host picker seam; production uses [hostChatAttachmentPicker].
final ChatAttachmentPicker? picker;
@override
State<ChatComposerBar> createState() => _ChatComposerBarState();
}
@@ -47,6 +57,10 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
text: widget.composer.draft,
);
final FocusNode _focus = FocusNode(debugLabel: 'chat-composer');
final ChatAttachmentDraft _attachments = ChatAttachmentDraft();
String? _attachmentError;
ChatAttachmentPicker get _picker => widget.picker ?? hostChatAttachmentPicker;
@override
void initState() {
@@ -100,6 +114,37 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
_focus.requestFocus();
}
/// Adds the operator's explicit selection through the host seam. A dismissed
/// picker changes nothing; a bounded draft refusal is shown in its own words
/// while every attachment already in the draft stays.
Future<void> _pickAttachments() async {
if (widget.composer.sending || !_picker.isSupported) return;
List<ChatPickedFile>? files;
try {
files = await _picker.pick();
} catch (error) {
if (!mounted) return;
setState(() => _attachmentError = '$error');
return;
}
if (!mounted || files == null) return;
final picked = files;
setState(() {
_attachmentError = null;
for (final file in picked) {
final refusal = _attachments.add(file.attachment);
if (refusal != null) _attachmentError = refusal.message;
}
});
}
void _removeAttachment(ChatAttachment attachment) {
setState(() {
_attachments.remove(attachment);
_attachmentError = null;
});
}
@override
void dispose() {
widget.composer.removeListener(_syncDraft);
@@ -126,6 +171,15 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (!_attachments.isEmpty) _attachmentStrip(context, cupertino),
if (_attachmentError != null)
_notice(
context,
cupertino,
key: const Key('chat-composer-attachment-error'),
text: _attachmentError!,
failed: true,
),
if (composer.queued)
_notice(
context,
@@ -144,6 +198,8 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
_attach(context, cupertino),
const SizedBox(width: 8),
Expanded(
child: Focus(
canRequestFocus: false,
@@ -164,6 +220,118 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
);
}
/// The attach control: a host button that opens the picker, disabled when the
/// host has no picker or one prompt is already awaiting its reply.
Widget _attach(BuildContext context, bool cupertino) {
final enabled = _picker.isSupported && !widget.composer.sending;
final onPressed = enabled ? () => unawaited(_pickAttachments()) : null;
if (cupertino) {
return Semantics(
label: chatAttachLabel,
button: true,
enabled: enabled,
child: ExcludeSemantics(
child: CupertinoButton(
key: const Key('chat-composer-attach'),
padding: EdgeInsets.zero,
onPressed: onPressed,
child: const Icon(CupertinoIcons.paperclip),
),
),
);
}
return IconButton(
key: const Key('chat-composer-attach'),
tooltip: chatAttachLabel,
onPressed: onPressed,
icon: const Icon(Icons.attach_file),
);
}
/// The files attached to the next message. Each chip carries only the
/// operator's recorded name and a native remove action.
Widget _attachmentStrip(BuildContext context, bool cupertino) {
final attachments = _attachments.attachments;
return Padding(
key: const Key('chat-composer-attachments'),
padding: const EdgeInsetsDirectional.only(bottom: 8),
child: Wrap(
spacing: 8,
runSpacing: 4,
children: [
for (var index = 0; index < attachments.length; index += 1)
if (cupertino)
_cupertinoChip(context, attachments[index], index)
else
_materialChip(attachments[index], index),
],
),
);
}
Widget _materialChip(ChatAttachment attachment, int index) => Chip(
key: ValueKey<String>('chat-composer-attachment-$index'),
label: Text(attachment.name),
onDeleted: () => _removeAttachment(attachment),
deleteButtonTooltipMessage: 'Remove ${attachment.name}',
);
/// Cupertino has no chip control, so the host's capsule fill and its own
/// button carry the same name and remove action.
Widget _cupertinoChip(
BuildContext context,
ChatAttachment attachment,
int index,
) {
return Semantics(
container: true,
explicitChildNodes: true,
child: DefaultTextStyle.merge(
style: CupertinoTheme.of(context).textTheme.textStyle,
child: DecoratedBox(
key: ValueKey<String>('chat-composer-attachment-$index'),
decoration: ShapeDecoration(
shape: const StadiumBorder(),
color: CupertinoColors.secondarySystemFill.resolveFrom(context),
),
child: Padding(
padding: const EdgeInsetsDirectional.fromSTEB(12, 4, 4, 4),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(
child: Text(attachment.name, overflow: TextOverflow.ellipsis),
),
const SizedBox(width: 4),
Semantics(
container: true,
button: true,
label: 'Remove ${attachment.name}',
onTap: () => _removeAttachment(attachment),
child: ExcludeSemantics(
child: CupertinoButton(
key: ValueKey<String>(
'chat-composer-attachment-remove-$index',
),
padding: EdgeInsets.zero,
onPressed: () => _removeAttachment(attachment),
child: Icon(
CupertinoIcons.xmark_circle_fill,
color: CupertinoColors.secondaryLabel.resolveFrom(
context,
),
),
),
),
),
],
),
),
),
),
);
}
Widget _field(bool cupertino) {
final composer = widget.composer;
void changed(String value) => unawaited(composer.setDraft(value));
@@ -191,6 +359,7 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
onChanged: changed,
decoration: const InputDecoration(
hintText: chatComposerPlaceholder,
hintMaxLines: 1,
border: OutlineInputBorder(),
),
);
@@ -4,6 +4,7 @@ import 'package:flutter/foundation.dart';
import '../../../core/api_gateway.dart';
import '../data/chat_repository.dart';
import '../domain/chat_sessions.dart';
import '../domain/chat_transcript.dart';
import 'chat_thread_cards.dart';
@@ -42,6 +43,7 @@ class ChatThreadController extends ChangeNotifier {
bool _hasMore = false;
String _cursor = '';
String _nativeTurnId = '';
JsonMap? _usage;
String? _error;
bool _subscribed = false;
@@ -59,6 +61,11 @@ class ChatThreadController extends ChangeNotifier {
/// The server's opaque older-page cursor. Never interpreted, only passed back.
String get cursor => _cursor;
/// The latest recorded usage snapshot, or null before the harness reports.
/// Unknown fields stay null, so a viewer can distinguish them from zero.
JsonMap? get usage => _usage;
String? get error => _error;
bool get subscribed => _subscribed;
String? get subscriptionError => _subscriptionError;
@@ -222,6 +229,16 @@ class ChatThreadController extends ChangeNotifier {
unawaited(resync());
return;
}
if (body['kind'] == 'usage') {
// Usage replaces the last snapshot and never adds a message, runs a turn
// or admits a queued prompt. An unusable snapshot keeps the previous
// recorded values instead of replacing them with fabricated zeros.
final usage = chatUsageSnapshot(body['usage']);
if (usage == null || !_reportedUsage(usage)) return;
_usage = usage;
_notify();
return;
}
if (body['kind'] == 'form') {
final form = body['form'];
if (form is! Map) return;
@@ -240,6 +257,23 @@ class ChatThreadController extends ChangeNotifier {
_notify();
}
/// Whether a normalized snapshot names a scope or carries a recorded fact.
/// A window of zero reports no usable limit, and a rate basis alone reports
/// no number at all, so neither counts as a fact on its own.
bool _reportedUsage(JsonMap usage) {
if ('${usage['scope'] ?? ''}'.isNotEmpty) return true;
if (usage['context_window'] is int &&
(usage['context_window'] as int) > 0) {
return true;
}
return const [
'total_tokens',
'context_tokens',
'cost_usd',
'output_tokens_per_second',
].any((key) => usage[key] != null);
}
/// The pushed envelope body, or null for another message type. The server
/// wraps `chat_event` in the typed envelope; domain code never sees the
/// transport fields.
@@ -101,6 +101,34 @@ class _ChatThreadViewState extends State<ChatThreadView> {
});
}
/// Reports the harness's recorded usage. The standard sheet is dismissed the
/// platform's way (drag/barrier/Back, or a popup tap) and closes explicitly.
Future<void> _openInfo() async {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
if (cupertino) {
await showCupertinoModalPopup<void>(
context: context,
builder: (sheetContext) => Align(
alignment: Alignment.bottomCenter,
child: SafeArea(
child: CupertinoPopupSurface(
child: _ChatInfoSheet(controller: _controller),
),
),
),
);
return;
}
await showModalBottomSheet<void>(
context: context,
showDragHandle: true,
isScrollControlled: true,
useSafeArea: true,
builder: (sheetContext) => _ChatInfoSheet(controller: _controller),
);
}
/// Local turns whose authoritative copy is not in the held transcript yet.
/// A live user frame or a history page that carries the same operation,
/// native id or message id hides the local copy instead of drawing it twice.
@@ -195,6 +223,13 @@ class _ChatThreadViewState extends State<ChatThreadView> {
).textTheme.navTitleTextStyle
: Theme.of(context).textTheme.titleLarge,
),
ChatBarAction(
key: const Key('chat-info'),
label: 'Chat information',
onPressed: _openInfo,
materialIcon: Icons.info_outline,
cupertinoIcon: CupertinoIcons.info,
),
],
),
),
@@ -312,6 +347,227 @@ class _ChatThreadViewState extends State<ChatThreadView> {
);
}
/// One reported usage metric: its web label, whether the harness reported it,
/// and the displayed value. Unavailable is a word, never a zero.
typedef _ChatInfoMetric = ({
String key,
String label,
bool available,
String value,
});
const _chatInfoUnavailable = 'Unavailable';
/// The four chat usage facts in the web order and wording.
///
/// Values come only from [ChatThreadController.usage]; a missing count, amount
/// or window is "Unavailable". A reported zero stays a reported zero, and the
/// context row keeps the web's partial forms when only one side was reported.
List<_ChatInfoMetric> _chatInfoMetrics(JsonMap? usage) {
final scope = '${usage?['scope'] ?? ''}';
final basis = '${usage?['rate_basis'] ?? ''}';
final rate = _chatInfoAmount(usage?['output_tokens_per_second']);
final total = _chatInfoCount(usage?['total_tokens']);
final used = _chatInfoCount(usage?['context_tokens']);
final reportedWindow = _chatInfoCount(usage?['context_window']);
// The web treats a zero context window as no reported limit.
final limit = reportedWindow != null && reportedWindow > 0
? reportedWindow
: null;
final cost = _chatInfoAmount(usage?['cost_usd']);
final context = used != null && limit != null
? '${_chatInfoInteger(used)} / ${_chatInfoInteger(limit)}'
: limit != null
? '${_chatInfoInteger(limit)} limit'
: used != null
? '${_chatInfoInteger(used)} used'
: _chatInfoUnavailable;
return [
(
key: 'rate',
label: basis == 'turn' ? 'Avg output rate' : 'Output rate',
available: rate != null,
value: rate == null ? _chatInfoUnavailable : _chatInfoRate(rate),
),
(
key: 'tokens',
label: scope == 'turn' ? 'Turn tokens' : 'Total tokens',
available: total != null,
value: total == null ? _chatInfoUnavailable : _chatInfoInteger(total),
),
(
key: 'context',
label: 'Context',
available: used != null || limit != null,
value: context,
),
(
key: 'cost',
label: 'Reported cost',
available: cost != null,
value: cost == null ? _chatInfoUnavailable : _chatInfoDollars(cost),
),
];
}
int? _chatInfoCount(Object? value) => value is int && value >= 0 ? value : null;
num? _chatInfoAmount(Object? value) =>
value is num && value.isFinite && value >= 0 ? value : null;
String _chatInfoInteger(int value) {
final digits = value.toString();
final grouped = StringBuffer();
for (var index = 0; index < digits.length; index++) {
if (index > 0 && (digits.length - index) % 3 == 0) grouped.write(',');
grouped.write(digits[index]);
}
return grouped.toString();
}
String _chatInfoRate(num value) {
final atMostOneDecimal = value.toStringAsFixed(1);
final number = atMostOneDecimal.endsWith('.0')
? atMostOneDecimal.substring(0, atMostOneDecimal.length - 2)
: atMostOneDecimal;
return value > 0 && value < 0.1 ? '<0.1 tok/s' : '$number tok/s';
}
String _chatInfoDollars(num value) {
if (value > 0 && value < 0.000001) return '<\$0.000001';
final fixed = value.toStringAsFixed(6);
final point = fixed.indexOf('.');
var decimals = fixed.substring(point + 1);
while (decimals.length > 4 && decimals.endsWith('0')) {
decimals = decimals.substring(0, decimals.length - 1);
}
final whole = int.parse(fixed.substring(0, point));
return '\$${_chatInfoInteger(whole)}.$decimals';
}
/// The "Chat information" panel. It rebuilds from the controller, so metrics
/// that arrive while it is open replace the displayed snapshot.
class _ChatInfoSheet extends StatelessWidget {
const _ChatInfoSheet({required this.controller});
final ChatThreadController controller;
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
return AnimatedBuilder(
animation: controller,
builder: (context, _) {
final titleStyle = cupertino
? CupertinoTheme.of(context).textTheme.navTitleTextStyle
: Theme.of(context).textTheme.titleLarge;
final content = Column(
key: const Key('chat-info-sheet'),
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(24, 8, 16, 4),
child: Row(
children: [
Expanded(
child: Semantics(
header: true,
child: Text('Chat information', style: titleStyle),
),
),
if (cupertino)
CupertinoButton(
key: const Key('chat-info-close'),
padding: EdgeInsets.zero,
onPressed: () => Navigator.of(context).pop(),
child: const Text('Close'),
)
else
TextButton(
key: const Key('chat-info-close'),
onPressed: () => Navigator.of(context).pop(),
child: const Text('Close'),
),
],
),
),
for (final metric in _chatInfoMetrics(controller.usage))
_ChatInfoRow(metric: metric, cupertino: cupertino),
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(24, 8, 24, 16),
child: Text(
'Last reported by the harness. '
'Unavailable values are not estimated.',
style:
(cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodySmall)
?.copyWith(
color: cupertino
? CupertinoColors.secondaryLabel.resolveFrom(
context,
)
: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
),
],
);
if (!cupertino) return SingleChildScrollView(child: content);
// A tall text scale must scroll inside the popup rather than push its
// heading off-screen. The height follows the viewport, not a fixed size.
return ConstrainedBox(
constraints: BoxConstraints(
maxHeight: MediaQuery.sizeOf(context).height * 0.8,
),
child: SingleChildScrollView(child: content),
);
},
);
}
}
class _ChatInfoRow extends StatelessWidget {
const _ChatInfoRow({required this.metric, required this.cupertino});
final _ChatInfoMetric metric;
final bool cupertino;
@override
Widget build(BuildContext context) {
final secondary = cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant;
final labelStyle =
(cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodySmall)
?.copyWith(color: secondary);
final valueStyle = cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodyLarge;
return Padding(
key: Key('chat-info-metric-${metric.key}'),
padding: const EdgeInsetsDirectional.fromSTEB(24, 6, 24, 6),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(metric.label, style: labelStyle),
Text(
metric.value,
key: Key('chat-info-value-${metric.key}'),
style: metric.available
? valueStyle
: valueStyle?.copyWith(color: secondary),
),
],
),
);
}
}
/// One recorded activity line for a turn.
///
/// The line is a summary of the recorded sequence. Its wording and state come
@@ -0,0 +1,140 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../../../core/error_reason.dart';
import '../../../ui/adaptive/host.dart';
import '../data/runs_repository.dart';
/// The browser client's export-only repair wording, kept verbatim.
const sessionExportRepairLabel = 'Retry export only';
const sessionExportRepairBusyLabel = 'Exporting…';
const sessionExportRepairHelp =
'Read the exact recorded session again. Does not rerun the stage or its '
'tools.';
/// Stable test/semantics keys shared by the action and its refusal.
const sessionExportRepairKey = ValueKey<String>('session-export-repair');
const sessionExportRepairErrorKey = ValueKey<String>(
'session-export-repair-error',
);
/// The server's refusal, verbatim. Only a blank error gets a generic sentence,
/// so a refused repair never looks like a completed one.
String describeSessionExportRepairError(Object error) => describeErrorReason(
error,
fallback: 'The server did not repair the session export.',
);
/// Reads one recorded visit's exact session again through the web client's
/// `repair_session_export` request (`run_id`, `export_sequence`).
///
/// The control is disabled while the visit is active or the request is in
/// flight, so one choice sends one request. The recorded export state is not
/// changed locally: only the server's reply, delivered through [onRepaired], is
/// shown next. A refusal stays visible beside the unchanged state and never
/// claims success.
class SessionExportRepairAction extends StatefulWidget {
const SessionExportRepairAction({
super.key,
required this.runId,
required this.sequence,
required this.gateway,
required this.running,
required this.onRepaired,
});
final num runId;
/// The visit's own recorded sequence, exactly as it is sent on the wire.
final int sequence;
final ApiGateway gateway;
/// True while the step or run is active, so reading its session is unsafe.
final bool running;
/// Receives the server's whole run detail; nothing is inferred from a reply
/// without one.
final ValueChanged<JsonMap> onRepaired;
@override
State<SessionExportRepairAction> createState() =>
_SessionExportRepairActionState();
}
class _SessionExportRepairActionState extends State<SessionExportRepairAction> {
bool _sending = false;
String? _refusal;
@override
void didUpdateWidget(covariant SessionExportRepairAction oldWidget) {
super.didUpdateWidget(oldWidget);
// A reply or refusal belongs to the visit it was sent for, never to the
// visit the pane happens to show next.
if (oldWidget.runId != widget.runId ||
oldWidget.sequence != widget.sequence) {
_sending = false;
_refusal = null;
}
}
bool _owns(num runId, int sequence) =>
mounted && widget.runId == runId && widget.sequence == sequence;
Future<void> _send() async {
if (_sending || widget.running) return;
final runId = widget.runId;
final sequence = widget.sequence;
setState(() {
_sending = true;
_refusal = null;
});
try {
final detail = await RunsRepository(
widget.gateway,
).repairSessionExport(runId, sequence);
if (!_owns(runId, sequence)) return;
widget.onRepaired(detail);
} catch (error) {
if (!_owns(runId, sequence)) return;
setState(() => _refusal = describeSessionExportRepairError(error));
} finally {
if (_owns(runId, sequence)) setState(() => _sending = false);
}
}
@override
Widget build(BuildContext context) {
final enabled = !_sending && !widget.running;
final label = _sending
? sessionExportRepairBusyLabel
: sessionExportRepairLabel;
final cupertino = usesCupertinoHost(context);
final button = cupertino
? CupertinoButton(
padding: EdgeInsets.zero,
onPressed: enabled ? _send : null,
child: Text(label),
)
: TextButton(onPressed: enabled ? _send : null, child: Text(label));
return Column(
key: sessionExportRepairKey,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (cupertino)
button
else
Tooltip(message: sessionExportRepairHelp, child: button),
if (_refusal != null)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Semantics(
liveRegion: true,
child: Text(_refusal!, key: sessionExportRepairErrorKey),
),
),
],
);
}
}
@@ -41,6 +41,26 @@ class RunsRepository {
'run_detail',
);
/// Reads the exact recorded visit again; it never reruns its stage or tools.
///
/// The body is the web client's `repair_session_export` request: the run and
/// the recorded export sequence only. The reply is the whole run detail, so
/// the caller can show exactly what the server recorded next.
Future<JsonMap> repairSessionExport(num id, int sequence) async {
if (id is! int || id < 1 || sequence < 1) {
throw const RunsRepositoryException(
'An exact run and visit are required.',
);
}
return _required(
await _gateway.call('repair_session_export', {
'run_id': id,
'export_sequence': sequence,
}),
'run_detail',
);
}
Future<JsonMap> retryRun(
num id, {
required String requestKey,
+9
View File
@@ -19,6 +19,8 @@ class RunsScreen extends StatefulWidget {
super.key,
required this.gateway,
this.initialRunId,
this.initialStageKey,
this.initialVisit,
this.syncToken = 0,
this.listRefreshToken = 0,
this.onRunSelected,
@@ -33,6 +35,11 @@ class RunsScreen extends StatefulWidget {
/// The run the current route names, or null for the list.
final int? initialRunId;
/// The recorded stage visit the route names inside [initialRunId]. The detail
/// applies it once per route target; the feature never invents a visit.
final String? initialStageKey;
final int? initialVisit;
/// Advances when the shared socket is replaced. The loaded screen refreshes
/// in place instead of being remounted, so its selection survives.
final int syncToken;
@@ -143,6 +150,8 @@ class _RunsScreenState extends State<RunsScreen> {
gateway: widget.gateway,
onBack: _back,
onRunOpened: _select,
initialStageKey: widget.initialStageKey,
initialVisit: widget.initialVisit,
),
],
);
@@ -20,7 +20,11 @@ Widget buildCupertinoRunDetail({
required String? copyStatus,
required VoidCallback onBack,
required VoidCallback onCopy,
required ApiGateway gateway,
required ValueChanged<JsonMap> onRunChanged,
required String configuredEndpoint,
String? initialStageKey,
int? initialVisit,
}) {
final theme = CupertinoTheme.of(context);
return RunDetailTabs(
@@ -29,7 +33,11 @@ Widget buildCupertinoRunDetail({
copying: copying,
copyStatus: copyStatus,
onCopy: onCopy,
gateway: gateway,
onRunChanged: onRunChanged,
configuredEndpoint: configuredEndpoint,
initialStageKey: initialStageKey,
initialVisit: initialVisit,
header: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
@@ -20,7 +20,11 @@ Widget buildMaterialRunDetail({
required String? copyStatus,
required VoidCallback onBack,
required VoidCallback onCopy,
required ApiGateway gateway,
required ValueChanged<JsonMap> onRunChanged,
required String configuredEndpoint,
String? initialStageKey,
int? initialVisit,
}) {
final theme = Theme.of(context);
return RunDetailTabs(
@@ -29,7 +33,11 @@ Widget buildMaterialRunDetail({
copying: copying,
copyStatus: copyStatus,
onCopy: onCopy,
gateway: gateway,
onRunChanged: onRunChanged,
configuredEndpoint: configuredEndpoint,
initialStageKey: initialStageKey,
initialVisit: initialVisit,
header: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
+74 -1
View File
@@ -36,7 +36,11 @@ class RunDetailTabs extends StatefulWidget {
required this.copying,
required this.copyStatus,
required this.onCopy,
required this.gateway,
required this.onRunChanged,
required this.configuredEndpoint,
this.initialStageKey,
this.initialVisit,
});
final JsonMap run;
@@ -50,10 +54,24 @@ class RunDetailTabs extends StatefulWidget {
final String? copyStatus;
final VoidCallback onCopy;
/// The shared gateway and accepted-detail fold used by the visit session's
/// export-only repair. Tabs never open their own socket.
final ApiGateway gateway;
final ValueChanged<JsonMap> onRunChanged;
/// The configured server origin used to resolve a recorded session export
/// through the landed safe-link helper. Blank leaves relative urls unresolved.
final String configuredEndpoint;
/// The stage a `/runs/:id/stage/:key` route names, or null for the plain
/// detail. It selects a recorded visit; a declared but unvisited stage only
/// selects its graph node, so no visit is ever invented.
final String? initialStageKey;
/// The zero-based index among [initialStageKey]'s recorded visits. Null opens
/// the stage's latest visit, exactly as a Graph node click does.
final int? initialVisit;
@override
State<RunDetailTabs> createState() => _RunDetailTabsState();
}
@@ -63,15 +81,68 @@ class _RunDetailTabsState extends State<RunDetailTabs> {
String? _selectedStage;
int? _selectedVisit;
@override
void initState() {
super.initState();
_applyInitialVisit();
}
@override
void didUpdateWidget(covariant RunDetailTabs oldWidget) {
super.didUpdateWidget(oldWidget);
final sameRun = '${widget.run['id']}' == '${oldWidget.run['id']}';
final sameTarget =
widget.initialStageKey == oldWidget.initialStageKey &&
widget.initialVisit == oldWidget.initialVisit;
// A different run is a different detail: its visits and graph do not carry
// the previous run's selection.
if ('${widget.run['id']}' != '${oldWidget.run['id']}') {
if (!sameRun) {
_tab = RunDetailTab.summary;
_selectedStage = null;
_selectedVisit = null;
_applyInitialVisit();
} else if (!sameTarget) {
// A route that names another stage or visit is applied to the same run.
// Rebuilds from a live refresh keep the operator's own selection.
_applyInitialVisit();
}
}
/// Opens the visit a route names, without presenting any visit the run did
/// not record.
///
/// A route with a stage key and no visit opens that stage's latest recorded
/// visit, the same visit a Graph node click opens. A valid index selects that
/// visit among the stage's own visits; an out-of-range index is clamped to the
/// stage's last recorded visit, as the web client does, so the address bar and
/// the pane never disagree about which visit is real. A declared but
/// unvisited stage selects its Graph node only.
void _applyInitialVisit() {
final stageKey = widget.initialStageKey;
if (stageKey == null || stageKey.isEmpty) {
_selectedStage = null;
_selectedVisit = null;
return;
}
final index = routeDetailVisitIndex(
widget.run['steps'],
stageKey,
widget.initialVisit,
);
if (index != null) {
_selectedStage = stageKey;
_selectedVisit = index;
_tab = RunDetailTab.timeline;
return;
}
_selectedVisit = null;
// The key is not a recorded visit. Only a stage the pinned graph actually
// declares can be selected; anything else leaves the plain detail intact.
if (detailVisitHasDefinition(detailGraph(widget.run), stageKey)) {
_selectedStage = stageKey;
_tab = RunDetailTab.graph;
} else {
_selectedStage = null;
}
}
@@ -180,6 +251,8 @@ class _RunDetailTabsState extends State<RunDetailTabs> {
visitIndex: index,
step: step,
runSteps: detailRunSteps(widget.run),
gateway: widget.gateway,
onRunChanged: widget.onRunChanged,
configuredEndpoint: widget.configuredEndpoint,
cupertino: widget.cupertino,
onClose: _closeVisit,
@@ -18,6 +18,8 @@ class RunDetailView extends StatefulWidget {
required this.gateway,
required this.onBack,
this.onRunOpened,
this.initialStageKey,
this.initialVisit,
});
final RunsController controller;
@@ -30,6 +32,12 @@ class RunDetailView extends StatefulWidget {
/// the server-identified new run. Null keeps the detail on the retried run.
final ValueChanged<num>? onRunOpened;
/// The route's stage and visit, forwarded to the tab body so a `/runs/:id/
/// stage/:key[?visit=N]` deep link opens that recorded visit. Null is the
/// plain detail.
final String? initialStageKey;
final int? initialVisit;
@override
State<RunDetailView> createState() => _RunDetailViewState();
}
@@ -64,7 +72,11 @@ class _RunDetailViewState extends State<RunDetailView> {
copyStatus: _copyStatus,
onBack: widget.onBack,
onCopy: () => _copyPrompt(prompt ?? '', cupertino: true),
gateway: widget.gateway,
onRunChanged: widget.controller.acceptRunDetail,
configuredEndpoint: endpoint,
initialStageKey: widget.initialStageKey,
initialVisit: widget.initialVisit,
)
: buildMaterialRunDetail(
context: context,
@@ -76,7 +88,11 @@ class _RunDetailViewState extends State<RunDetailView> {
copyStatus: _copyStatus,
onBack: widget.onBack,
onCopy: () => _copyPrompt(prompt ?? '', cupertino: false),
gateway: widget.gateway,
onRunChanged: widget.controller.acceptRunDetail,
configuredEndpoint: endpoint,
initialStageKey: widget.initialStageKey,
initialVisit: widget.initialVisit,
);
},
);
@@ -21,6 +21,8 @@ class RunVisitPane extends StatefulWidget {
required this.visitIndex,
required this.step,
required this.runSteps,
required this.gateway,
required this.onRunChanged,
required this.configuredEndpoint,
required this.cupertino,
required this.onClose,
@@ -35,6 +37,12 @@ class RunVisitPane extends StatefulWidget {
final JsonMap step;
final List<JsonMap> runSteps;
/// The app's shared gateway and the accepted-detail fold for the session's
/// export-only repair. The visit never opens its own socket.
final ApiGateway gateway;
final ValueChanged<JsonMap> onRunChanged;
final String configuredEndpoint;
final bool cupertino;
final VoidCallback onClose;
@@ -106,6 +114,8 @@ class _RunVisitPaneState extends State<RunVisitPane> {
visitIndex: widget.visitIndex,
stageKey: widget.visit.stage,
runSteps: widget.runSteps,
gateway: widget.gateway,
onRunChanged: widget.onRunChanged,
configuredEndpoint: widget.configuredEndpoint,
cupertino: widget.cupertino,
),
@@ -108,6 +108,28 @@ String? detailVisitSessionIdentity(JsonMap step) {
return evidence == null ? null : recordedText(evidence['session_id']);
}
/// The session identity the web client requires before it offers an
/// export-only repair: the visit's own `session_id` or its original
/// `session_export.session_id`. A repair attempt's identity is not enough, and
/// neither is an identity read only from that repair, exactly as the web's
/// availability check does not widen the case.
String? detailVisitRepairIdentity(JsonMap step) {
final direct = recordedText(step['session_id']);
if (direct != null) return direct;
final original = step['session_export'];
return original is Map ? recordedText(original['session_id']) : null;
}
/// Whether the web audit pane offers the export-only repair for a document it
/// can open: only when recorded evidence is incomplete or truncated.
///
/// A legacy `session.html` selected by the no-evidence fallback has nothing to
/// compare and gets no control. A `complete` status without the server's
/// verified evidence stays [VisitSessionExportState.partial] here, so it keeps
/// the control; that is this client's deliberate, stricter rule.
bool visitSessionExportNeedsRepair(VisitSessionExport export) =>
export.truncated || (export.status != null && !export.isComplete);
/// The visit's recorded export document, or null when no recorded export name
/// is present in the inventory.
///
@@ -31,15 +31,41 @@ JsonMap? detailVisitStepAt(JsonMap run, int index) {
}
/// The row index of [stageKey]'s latest recorded visit, or null when the run
/// never recorded that stage. It reads the same ordered timeline the rows do,
/// so a Graph click opens exactly the row the operator would have selected.
int? latestDetailVisitIndex(dynamic steps, String stageKey) {
/// never recorded that stage.
///
/// The order matches [routeDetailVisitIndex] and the web client's
/// `visitsByStage`: a stage's visits follow their recorded sequence, not their
/// position in the reply's step list. So a Graph click and `/runs/:id/stage/:key`
/// open the same visit even when the steps are not in sequence order.
int? latestDetailVisitIndex(dynamic steps, String stageKey) =>
routeDetailVisitIndex(steps, stageKey, null);
/// The timeline row index a route's [stageKey] and [visit] name, or null when
/// the run recorded no visit of that stage.
///
/// A stage's visits follow their recorded sequence, as the web client's
/// `visitsByStage` does, so the same `?visit=N` selects the same visit in both
/// clients while equal sequences keep the timeline's own order. A null [visit]
/// is the stage's last recorded visit, the one a Graph node click opens; an
/// out-of-range index is clamped to that last visit, exactly as the web client
/// clamps it. Nothing is invented for a stage with no recorded visit.
int? routeDetailVisitIndex(dynamic steps, String stageKey, int? visit) {
final visits = detailTimeline(steps);
int? latest;
for (var index = 0; index < visits.length; index += 1) {
if (visits[index].stage == stageKey) latest = index;
}
return latest;
final indices = <int>[
for (var index = 0; index < visits.length; index += 1)
if (visits[index].stage == stageKey) index,
];
if (indices.isEmpty) return null;
indices.sort((a, b) {
final bySequence = (visits[a].sequence ?? 0).compareTo(
visits[b].sequence ?? 0,
);
return bySequence != 0 ? bySequence : a.compareTo(b);
});
final wanted = visit == null
? indices.length - 1
: visit.clamp(0, indices.length - 1);
return indices[wanted];
}
/// The visit's recorded facts, in the pane's order. A field the server did not
@@ -88,6 +88,8 @@ Widget runVisitSectionBody({
required int visitIndex,
required String stageKey,
required List<JsonMap> runSteps,
required ApiGateway gateway,
required ValueChanged<JsonMap> onRunChanged,
required String configuredEndpoint,
required bool cupertino,
}) {
@@ -115,7 +117,10 @@ Widget runVisitSectionBody({
);
case RunVisitSection.session:
return RunVisitSession(
run: run,
step: step,
gateway: gateway,
onRunChanged: onRunChanged,
configuredEndpoint: configuredEndpoint,
);
case RunVisitSection.definition:
@@ -6,6 +6,8 @@ import '../../../ui/adaptive/host.dart';
import '../../artifacts/domain/artifact_record.dart';
import '../../artifacts/domain/artifact_url.dart';
import '../../artifacts/ui/artifact_external_open.dart';
import '../actions/session_export_repair_action.dart';
import 'run_detail_visit_recorded.dart';
import 'run_detail_visit_session_state.dart';
/// The visit's recorded session pointer, its recorded export state and, when
@@ -15,19 +17,29 @@ import 'run_detail_visit_session_state.dart';
/// repair, a still-running session and a failed one each report what the server
/// recorded. Complete, partial, missing, skipped, repair and unrecognised
/// states each keep the server's own word and diagnostic; recorded repair
/// attempts and their open-option labels are shown read-only and make no
/// request. The open goes through the landed safe-link helper: the recorded url
/// is resolved by [resolveArtifactUrl] and passed to [openArtifactExternally]
/// without being fetched, rewritten or previewed. A refusal is reported.
/// attempts and their open-option labels stay read-only. An export whose
/// recorded evidence is incomplete or truncated offers the web client's
/// export-only repair, which sends that exact visit's recorded sequence and
/// keeps this recorded state until the server replies; a legacy `session.html`
/// with no recorded evidence offers no control, exactly as the web does. The
/// open goes through the landed safe-link helper: the recorded url is resolved
/// by [resolveArtifactUrl] and passed to [openArtifactExternally] without being
/// fetched, rewritten or previewed. A refusal is reported.
class RunVisitSession extends StatefulWidget {
const RunVisitSession({
super.key,
required this.run,
required this.step,
required this.gateway,
required this.onRunChanged,
required this.configuredEndpoint,
this.openExternal = openArtifactExternally,
});
final JsonMap run;
final JsonMap step;
final ApiGateway gateway;
final ValueChanged<JsonMap> onRunChanged;
final String configuredEndpoint;
final ArtifactExternalOpen openExternal;
@@ -57,6 +69,8 @@ class _RunVisitSessionState extends State<RunVisitSession> {
: resolveArtifactUrl(widget.configuredEndpoint, export.artifact.url);
final note = export?.statusNote;
final fact = session.exportFact;
final sequence = recordedCount(widget.step['sequence']);
final repair = _repairAction(session, sequence);
final showReason =
export != null &&
fact?.reason != null &&
@@ -84,6 +98,7 @@ class _RunVisitSessionState extends State<RunVisitSession> {
const Text(visitSessionEndpointMissing)
else
_openButton(export.artifact, resolved),
?repair,
if (_status != null)
Padding(
padding: const EdgeInsets.only(top: 8),
@@ -130,8 +145,39 @@ class _RunVisitSessionState extends State<RunVisitSession> {
);
}
/// Recorded repair attempts, in the pane's own fact rows. Nothing here is a
/// control: the repair request belongs to its own action and is not wired.
/// The export-only repair option: offered only for a visit whose recorded
/// session identity and sequence can be read again, and whose recorded export
/// evidence is incomplete or truncated (or which has no openable document at
/// all). A legacy `session.html` chosen only by the no-evidence fallback has
/// no evidence to repair and keeps the web's absence of the control. The
/// visit's own recorded sequence is sent, never a guessed one.
Widget? _repairAction(VisitSessionState session, int sequence) {
final runId = recordedCount(widget.run['id']);
if (runId < 1 || sequence < 1) return null;
if (detailVisitRepairIdentity(widget.step) == null) return null;
final export = session.export;
if (export != null && !visitSessionExportNeedsRepair(export)) return null;
final status = recordedText(widget.step['status']);
final runStatus = recordedText(widget.run['status']);
final pending = recordedCount(widget.run['export_pending_sequence']);
final running =
widget.step['agent_active'] == true ||
status == 'running' ||
status == 'queued' ||
runStatus == 'running' ||
runStatus == 'queued' ||
(runStatus == 'waiting' && pending != sequence);
return SessionExportRepairAction(
runId: runId,
sequence: sequence,
gateway: widget.gateway,
running: running,
onRepaired: widget.onRunChanged,
);
}
/// Recorded repair attempts, in the pane's own fact rows. These labels stay
/// read-only; the request is made only by [SessionExportRepairAction].
List<Widget> _repairFacts(List<VisitSessionRepair> repairs) {
final facts = <Widget>[];
for (var index = 0; index < repairs.length; index += 1) {