merge(app): land native create-from-template prompt

This commit is contained in:
2026-10-21 20:57:34 +01:00
57 changed files with 5574 additions and 381 deletions
+195
View File
@@ -0,0 +1,195 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../core/transport/connection_state.dart';
import 'app_session.dart';
import 'server_endpoint.dart';
/// The full connection screen shown before a destination has ever loaded.
///
/// A missing native endpoint is a configuration state, not a server failure,
/// so it is explained without opening a socket. Otherwise the screen reports
/// connecting, then an honest unavailable state with a native Retry action.
class ConnectionGate extends StatelessWidget {
const ConnectionGate({
super.key,
required this.session,
required this.server,
required this.cupertino,
});
final AppSession session;
final ServerEndpoint server;
final bool cupertino;
@override
Widget build(BuildContext context) {
final state = session.connection;
if (server.requiresConfiguration) {
return _status(
context,
title: 'Server endpoint not configured',
detail:
'Build the native app with an explicit Pipelines endpoint, for '
'example --dart-define=PIPELINES_SERVER_URL=ws://host:port/connect.',
);
}
if (server.error != null) {
return _status(context, title: server.error!, detail: '');
}
// Only the very first attempt is "connecting". A failed attempt keeps the
// same honest unavailable state while the client retries behind it, so the
// screen no longer flickers between unavailable and connecting.
if (state.kind == ConnectionKind.connecting && state.attempt <= 1) {
return _status(
context,
title: 'Connecting to Pipelines…',
detail: '',
progress: true,
);
}
return _status(
context,
title: 'Pipelines server unavailable',
detail: state.retrying
? 'Retrying automatically. Check that the Pipelines server is running.'
: 'Check that the Pipelines server is running, then try again.',
onRetry: session.retry,
);
}
Widget _status(
BuildContext context, {
required String title,
required String detail,
bool progress = false,
VoidCallback? onRetry,
}) {
final theme = Theme.of(context);
return Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (progress)
Padding(
padding: const EdgeInsets.only(bottom: 12),
child: cupertino
? const CupertinoActivityIndicator()
: const CircularProgressIndicator(),
),
Semantics(
liveRegion: true,
child: Text(
title,
textAlign: TextAlign.center,
style: cupertino
? CupertinoTheme.of(context).textTheme.navTitleTextStyle
: theme.textTheme.titleMedium,
),
),
if (detail.isNotEmpty) ...[
const SizedBox(height: 8),
Text(
detail,
textAlign: TextAlign.center,
style: cupertino ? null : theme.textTheme.bodyMedium,
),
],
if (onRetry != null) ...[
const SizedBox(height: 16),
if (cupertino)
CupertinoButton(onPressed: onRetry, child: const Text('Retry'))
else
FilledButton(onPressed: onRetry, child: const Text('Retry')),
],
],
),
),
);
}
}
/// A compact status bar above retained content after the first connection.
class ConnectionBanner extends StatelessWidget {
const ConnectionBanner({
super.key,
required this.session,
required this.cupertino,
});
final AppSession session;
final bool cupertino;
@override
Widget build(BuildContext context) {
final state = session.connection;
final refused = session.subscription == RunSubscriptionState.refused;
final reconnecting =
!session.connected &&
(state.kind == ConnectionKind.connecting || state.retrying);
final String title;
final String detail;
final VoidCallback onRetry;
if (session.connected && refused) {
title = 'Not live — run updates are unavailable.';
detail = session.subscriptionError;
onRetry = session.resubscribe;
} else if (reconnecting) {
title = 'Reconnecting to Pipelines…';
detail = '';
onRetry = session.retry;
} else {
title = 'Not live — Pipelines server unavailable.';
detail = 'Check that the Pipelines server is running.';
onRetry = session.retry;
}
final textStyle = cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodyMedium;
return ColoredBox(
color: cupertino
? CupertinoDynamicColor.resolve(CupertinoColors.systemGrey5, context)
: Theme.of(context).colorScheme.surfaceContainerHighest,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Row(
children: [
if (reconnecting) ...[
cupertino
? const CupertinoActivityIndicator(radius: 7)
: const SizedBox(
width: 14,
height: 14,
child: CircularProgressIndicator(strokeWidth: 2),
),
const SizedBox(width: 10),
],
Expanded(
child: Semantics(
liveRegion: true,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title, style: textStyle),
if (detail.isNotEmpty) Text(detail, style: textStyle),
],
),
),
),
const SizedBox(width: 8),
if (cupertino)
CupertinoButton(
padding: EdgeInsets.zero,
onPressed: onRetry,
child: const Text('Retry'),
)
else
TextButton(onPressed: onRetry, child: const Text('Retry')),
],
),
),
);
}
}
+3
View File
@@ -11,6 +11,7 @@ import 'app.dart';
import 'app_route.dart';
import 'app_router.dart';
import 'app_session.dart';
import 'pipelines_destination.dart';
import 'runs_destination.dart';
import 'server_endpoint.dart';
@@ -100,6 +101,8 @@ class _PipelinesAppState extends State<PipelinesApp> {
onDestinationSelected: (destination) =>
_delegate.goTo(_routeOf(destination)),
destinationBodies: {
AppDestination.pipelines: (_) =>
PipelinesDestination(session: _session, server: widget.server),
AppDestination.runs: (_) => RunsDestination(
session: _session,
server: widget.server,
@@ -0,0 +1,61 @@
import 'package:flutter/material.dart';
import '../features/pipelines/screen.dart';
import '../ui/adaptive/host.dart';
import 'app_session.dart';
import 'connection_status.dart';
import 'server_endpoint.dart';
/// The Pipelines destination: the read-only browser plus honest status.
///
/// Before the shared socket accepts its first connection nothing is requested,
/// so an offline launch cannot look like an empty pipeline list. After that the
/// browser stays mounted through drops; a reconnect advances [syncToken] so the
/// list and the open detail refresh in place instead of losing the selection.
class PipelinesDestination extends StatelessWidget {
const PipelinesDestination({
super.key,
required this.session,
required this.server,
});
final AppSession session;
final ServerEndpoint server;
@override
Widget build(BuildContext context) => AnimatedBuilder(
animation: session,
builder: (context, _) {
final cupertino = usesCupertinoHost(context);
if ((server.requiresConfiguration || server.error != null) &&
session.endpoint == null) {
return ConnectionGate(
session: session,
server: server,
cupertino: cupertino,
);
}
if (!session.everConnected) {
if (session.connected) return _pipelinesScreen();
return ConnectionGate(
session: session,
server: server,
cupertino: cupertino,
);
}
return Column(
children: [
if (!session.connected)
ConnectionBanner(session: session, cupertino: cupertino),
Expanded(child: _pipelinesScreen()),
],
);
},
);
Widget _pipelinesScreen() => PipelinesScreen(
gateway: session.gateway,
embedded: true,
syncToken: session.connectionEpoch,
);
}
+4 -184
View File
@@ -1,10 +1,9 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../core/transport/connection_state.dart';
import '../features/runs/screen.dart';
import '../ui/adaptive/host.dart';
import 'app_session.dart';
import 'connection_status.dart';
import 'server_endpoint.dart';
/// The Runs destination: the loaded screen plus an honest connection status.
@@ -36,7 +35,7 @@ class RunsDestination extends StatelessWidget {
final cupertino = usesCupertinoHost(context);
if ((server.requiresConfiguration || server.error != null) &&
session.endpoint == null) {
return _ConnectionScreen(
return ConnectionGate(
session: session,
server: server,
cupertino: cupertino,
@@ -44,7 +43,7 @@ class RunsDestination extends StatelessWidget {
}
if (!session.everConnected) {
if (session.connected) return _runsScreen();
return _ConnectionScreen(
return ConnectionGate(
session: session,
server: server,
cupertino: cupertino,
@@ -54,7 +53,7 @@ class RunsDestination extends StatelessWidget {
children: [
if (!session.connected ||
session.subscription == RunSubscriptionState.refused)
_ConnectionBanner(session: session, cupertino: cupertino),
ConnectionBanner(session: session, cupertino: cupertino),
Expanded(child: _runsScreen()),
],
);
@@ -69,182 +68,3 @@ class RunsDestination extends StatelessWidget {
onBack: onBack,
);
}
class _ConnectionScreen extends StatelessWidget {
const _ConnectionScreen({
required this.session,
required this.server,
required this.cupertino,
});
final AppSession session;
final ServerEndpoint server;
final bool cupertino;
@override
Widget build(BuildContext context) {
final state = session.connection;
if (server.requiresConfiguration) {
return _status(
context,
title: 'Server endpoint not configured',
detail:
'Build the native app with an explicit Pipelines endpoint, for '
'example --dart-define=PIPELINES_SERVER_URL=ws://host:port/connect.',
);
}
if (server.error != null) {
return _status(context, title: server.error!, detail: '');
}
// Only the very first attempt is "connecting". A failed attempt keeps the
// same honest unavailable state while the client retries behind it, so the
// screen no longer flickers between unavailable and connecting.
if (state.kind == ConnectionKind.connecting && state.attempt <= 1) {
return _status(
context,
title: 'Connecting to Pipelines…',
detail: '',
progress: true,
);
}
return _status(
context,
title: 'Pipelines server unavailable',
detail: state.retrying
? 'Retrying automatically. Check that the Pipelines server is running.'
: 'Check that the Pipelines server is running, then try again.',
onRetry: session.retry,
);
}
Widget _status(
BuildContext context, {
required String title,
required String detail,
bool progress = false,
VoidCallback? onRetry,
}) {
final theme = Theme.of(context);
return Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (progress)
Padding(
padding: const EdgeInsets.only(bottom: 12),
child: cupertino
? const CupertinoActivityIndicator()
: const CircularProgressIndicator(),
),
Semantics(
liveRegion: true,
child: Text(
title,
textAlign: TextAlign.center,
style: cupertino
? CupertinoTheme.of(context).textTheme.navTitleTextStyle
: theme.textTheme.titleMedium,
),
),
if (detail.isNotEmpty) ...[
const SizedBox(height: 8),
Text(
detail,
textAlign: TextAlign.center,
style: cupertino ? null : theme.textTheme.bodyMedium,
),
],
if (onRetry != null) ...[
const SizedBox(height: 16),
if (cupertino)
CupertinoButton(onPressed: onRetry, child: const Text('Retry'))
else
FilledButton(onPressed: onRetry, child: const Text('Retry')),
],
],
),
),
);
}
}
/// A compact status bar above the retained Runs screen.
class _ConnectionBanner extends StatelessWidget {
const _ConnectionBanner({required this.session, required this.cupertino});
final AppSession session;
final bool cupertino;
@override
Widget build(BuildContext context) {
final state = session.connection;
final refused = session.subscription == RunSubscriptionState.refused;
final reconnecting =
!session.connected &&
(state.kind == ConnectionKind.connecting || state.retrying);
final String title;
final String detail;
final VoidCallback onRetry;
if (session.connected && refused) {
title = 'Not live — run updates are unavailable.';
detail = session.subscriptionError;
onRetry = session.resubscribe;
} else if (reconnecting) {
title = 'Reconnecting to Pipelines…';
detail = '';
onRetry = session.retry;
} else {
title = 'Not live — Pipelines server unavailable.';
detail = 'Check that the Pipelines server is running.';
onRetry = session.retry;
}
final textStyle = cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodyMedium;
return ColoredBox(
color: cupertino
? CupertinoDynamicColor.resolve(CupertinoColors.systemGrey5, context)
: Theme.of(context).colorScheme.surfaceContainerHighest,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Row(
children: [
if (reconnecting) ...[
cupertino
? const CupertinoActivityIndicator(radius: 7)
: const SizedBox(
width: 14,
height: 14,
child: CircularProgressIndicator(strokeWidth: 2),
),
const SizedBox(width: 10),
],
Expanded(
child: Semantics(
liveRegion: true,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title, style: textStyle),
if (detail.isNotEmpty) Text(detail, style: textStyle),
],
),
),
),
const SizedBox(width: 8),
if (cupertino)
CupertinoButton(
padding: EdgeInsets.zero,
onPressed: onRetry,
child: const Text('Retry'),
)
else
TextButton(onPressed: onRetry, child: const Text('Retry')),
],
),
),
);
}
}
+1 -1
View File
@@ -11,7 +11,7 @@ export 'domain/change_wording.dart';
export 'domain/file_change.dart';
export 'domain/run_changes.dart';
export 'domain/unified_patch.dart';
export 'widgets/change_style.dart' show DiffForm, usesCupertino;
export 'widgets/change_style.dart' show DiffForm, hostTextTheme, usesCupertino;
export 'widgets/changes_viewer.dart';
export 'widgets/file_diff_viewer.dart';
export 'widgets/patch_view.dart';
@@ -44,6 +44,13 @@ class RunChanges {
RunChanges runChanges(List<JsonMap> steps) =>
runChangesFor(stageCaptures(steps));
/// Whether the run-wide final-state aggregate may be presented. Ported from
/// `web/src/changes.js` `showRunChangesSummary`: only a settled succeeded run
/// has a final workspace state. A failed or running run keeps its evidence in
/// each visit's own captured section instead of claiming a settled summary.
bool showRunChangesSummary(Object? status) =>
status != null && '$status'.trim().toLowerCase() == 'succeeded';
/// The same aggregate over already-derived [stageCaptures], so a caller that
/// shows both the summary and the sections parses each capture only once.
RunChanges runChangesFor(List<StageCapture> visits) {
@@ -2,104 +2,52 @@ import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../domain/unified_patch.dart';
import 'diff_form_control.dart';
/// Which form of a recorded patch the viewer is showing.
enum DiffForm { rendered, raw }
export 'diff_form_control.dart';
/// The app's established platform switch: Material for Android/desktop/web,
/// Cupertino for iOS and macOS. Feature widgets stay portable across all three
/// targets instead of hard-coding one control set.
bool usesCupertino(BuildContext context) {
final platform = Theme.of(context).platform;
return platform == TargetPlatform.iOS || platform == TargetPlatform.macOS;
}
/// Patch text inherits the host's typography, including its font and scaler.
/// A diff is not an exception to the native-defaults requirement.
/// Patch text inherits the host's typography without a diff-specific font.
TextStyle nativeDiffText(TextStyle base) => base;
/// Native semantic colours, never a bespoke diff palette. The recorded +/-
/// markers carry meaning independently of colour. No background tint is added.
/// Keep Material-derived metadata roles readable inside a Cupertino host.
ThemeData hostTextTheme(BuildContext context) => ThemeData(
brightness: CupertinoTheme.brightnessOf(context),
platform: Theme.of(context).platform,
);
/// Native semantic roles, never a bespoke palette or added row tint. The exact
/// recorded +/- markers also distinguish changes without relying on colour.
({Color text, Color? background}) diffLineColors(
BuildContext context,
ChangeLineKind kind,
) {
return switch (kind) {
ChangeLineKind.add => (
text: usesCupertino(context)
? CupertinoColors.systemGreen.resolveFrom(context)
: Theme.of(context).colorScheme.primary,
background: null,
),
ChangeLineKind.remove => (
text: usesCupertino(context)
? CupertinoColors.destructiveRed.resolveFrom(context)
: Theme.of(context).colorScheme.error,
background: null,
),
ChangeLineKind.context => (text: labelColor(context), background: null),
};
}
) => switch (kind) {
ChangeLineKind.add => (
text: usesCupertino(context)
? CupertinoColors.systemGreen.resolveFrom(context)
: Theme.of(context).colorScheme.primary,
background: null,
),
ChangeLineKind.remove => (
text: usesCupertino(context)
? CupertinoColors.destructiveRed.resolveFrom(context)
: Theme.of(context).colorScheme.error,
background: null,
),
ChangeLineKind.context => (text: labelColor(context), background: null),
};
/// The plain body/label colour for non-diff text inside the viewer.
Color labelColor(BuildContext context) => usesCupertino(context)
? CupertinoColors.label.resolveFrom(context)
: Theme.of(context).colorScheme.onSurface;
/// The muted colour for gutters, notes and secondary metadata.
Color mutedColor(BuildContext context) => usesCupertino(context)
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant;
/// The hunk header's fill.
Color hunkHeaderColor(BuildContext context) => usesCupertino(context)
? CupertinoColors.tertiarySystemFill.resolveFrom(context)
: Theme.of(context).colorScheme.surfaceContainerHighest;
/// The viewer's shared Rendered/Raw control: a native segmented control on each
/// platform, with the same two words the browser uses.
Widget diffFormControl(
BuildContext context, {
required DiffForm form,
required ValueChanged<DiffForm> onChanged,
}) {
if (usesCupertino(context)) {
return CupertinoSlidingSegmentedControl<DiffForm>(
groupValue: form,
onValueChanged: (value) {
if (value != null) onChanged(value);
},
children: const {
DiffForm.rendered: _SegmentLabel('Rendered'),
DiffForm.raw: _SegmentLabel('Raw patch'),
},
);
}
return SegmentedButton<DiffForm>(
segments: const [
ButtonSegment(value: DiffForm.rendered, label: Text('Rendered')),
ButtonSegment(value: DiffForm.raw, label: Text('Raw patch')),
],
selected: {form},
showSelectedIcon: false,
onSelectionChanged: (selection) {
if (selection.isNotEmpty) onChanged(selection.first);
},
);
}
class _SegmentLabel extends StatelessWidget {
const _SegmentLabel(this.label);
final String label;
@override
Widget build(BuildContext context) =>
Padding(padding: const EdgeInsets.all(6), child: Text(label));
}
/// Copy the server's raw patch exactly as recorded. Disabled when the entry has
/// no readable patch, so the action never copies a fabricated empty diff.
Widget copyPatchControl(
BuildContext context, {
required bool enabled,
@@ -128,7 +76,6 @@ Widget copyPatchControl(
);
}
/// The standard close action, labelled exactly on both platforms.
Widget closeDiffControl(BuildContext context, VoidCallback onClose) {
if (usesCupertino(context)) {
return Semantics(
@@ -17,7 +17,11 @@ import 'file_diff_viewer.dart';
/// Scaffold body, tab body or Expanded child). It never opens its own socket or
/// requests data; the caller passes the run detail's `steps`.
class ChangesViewer extends StatefulWidget {
const ChangesViewer({super.key, required this.steps});
const ChangesViewer({
super.key,
required this.steps,
this.showSummary = true,
});
/// The run detail's steps exactly as the server returned them. Each step's
/// `file_changes` may be null (no capture), a complete/partial/unavailable
@@ -27,6 +31,11 @@ class ChangesViewer extends StatefulWidget {
/// captures and the summary are derived from it rather than on every rebuild.
final List<JsonMap> steps;
/// Whether the run-wide final-state header and filter are shown. The web
/// client gates its aggregate on [showRunChangesSummary]; the per-stage
/// sections stay the evidence for a run without a settled final state.
final bool showSummary;
@override
State<ChangesViewer> createState() => _ChangesViewerState();
}
@@ -67,49 +76,51 @@ class _ChangesViewerState extends State<ChangesViewer> {
Widget build(BuildContext context) {
final run = _run;
final captures = _captures;
final showSummary = widget.showSummary;
final hasFiles = captures.any(
(visit) => visit.capture?.files.isNotEmpty ?? false,
);
final note = runChangesNote(run);
final note = showSummary ? runChangesNote(run) : '';
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
runChangesHeader(run),
style: Theme.of(context).textTheme.titleMedium,
),
if (note.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(
note,
style: Theme.of(context).textTheme.bodySmall,
),
if (showSummary)
Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
runChangesHeader(run),
style: Theme.of(context).textTheme.titleMedium,
),
if (hasFiles)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(
'The summary counts each path once, as the last recorded '
'visit left it. Each stage/visit below lists what its own '
'capture recorded.',
style: Theme.of(context).textTheme.bodySmall,
if (note.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(
note,
style: Theme.of(context).textTheme.bodySmall,
),
),
),
],
if (hasFiles)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(
'The summary counts each path once, as the last recorded '
'visit left it. Each stage/visit below lists what its own '
'capture recorded.',
style: Theme.of(context).textTheme.bodySmall,
),
),
],
),
),
),
if (hasFiles)
if (showSummary && hasFiles)
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
child: _filterField(context, run),
),
const Divider(height: 1),
if (showSummary) const Divider(height: 1),
Expanded(
child: captures.isEmpty
? SingleChildScrollView(
@@ -0,0 +1,138 @@
import 'dart:math' as math;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
enum DiffForm { rendered, raw }
bool usesCupertino(BuildContext context) => usesCupertinoHost(context);
const diffFormLabels = <DiffForm, String>{
DiffForm.rendered: 'Rendered',
DiffForm.raw: 'Raw patch',
};
/// Conservatively choose between two stock controls using the current native
/// label role and text scaler. This does not size or restyle either control.
bool diffFormSegmentsFit(BuildContext context, double maxWidth) {
final style = usesCupertino(context)
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.labelLarge ??
DefaultTextStyle.of(context).style;
var widest = 0.0;
for (final label in diffFormLabels.values) {
final painter = TextPainter(
text: TextSpan(text: label, style: style),
textDirection: Directionality.of(context),
textScaler: MediaQuery.textScalerOf(context),
maxLines: 1,
)..layout();
widest = math.max(widest, painter.width);
painter.dispose();
}
return (widest + 48) * 2 <= maxWidth;
}
Widget diffFormControl(
BuildContext context, {
required DiffForm form,
required ValueChanged<DiffForm> onChanged,
}) {
if (usesCupertino(context)) {
return CupertinoSlidingSegmentedControl<DiffForm>(
groupValue: form,
onValueChanged: (value) {
if (value != null) onChanged(value);
},
children: {
for (final entry in diffFormLabels.entries)
entry.key: Padding(
padding: const EdgeInsets.all(6),
child: Text(entry.value),
),
},
);
}
return SegmentedButton<DiffForm>(
segments: [
for (final entry in diffFormLabels.entries)
ButtonSegment(value: entry.key, label: Text(entry.value)),
],
selected: {form},
showSelectedIcon: false,
onSelectionChanged: (selection) {
if (selection.isNotEmpty) onChanged(selection.first);
},
);
}
/// Native action sheet/bottom sheet when fixed segment labels cannot fit.
Widget diffFormMenu(
BuildContext context, {
required DiffForm form,
required ValueChanged<DiffForm> onChanged,
}) {
if (usesCupertino(context)) {
return Semantics(
label: 'Diff form',
button: true,
child: CupertinoButton(
padding: EdgeInsets.zero,
onPressed: () => showCupertinoModalPopup<void>(
context: context,
builder: (sheetContext) => CupertinoActionSheet(
title: const Text('Diff form'),
actions: [
for (final entry in diffFormLabels.entries)
CupertinoActionSheetAction(
isDefaultAction: entry.key == form,
onPressed: () {
Navigator.of(sheetContext).pop();
onChanged(entry.key);
},
child: Text(entry.value),
),
],
),
),
child: const Icon(CupertinoIcons.ellipsis),
),
);
}
return IconButton(
tooltip: 'Diff form',
icon: const Icon(Icons.more_vert),
onPressed: () => showModalBottomSheet<void>(
context: context,
showDragHandle: true,
builder: (sheetContext) => SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
child: Align(
alignment: AlignmentDirectional.centerStart,
child: Text(
'Diff form',
style: Theme.of(sheetContext).textTheme.titleMedium,
),
),
),
for (final entry in diffFormLabels.entries)
ListTile(
title: Text(entry.value),
selected: entry.key == form,
onTap: () {
Navigator.of(sheetContext).pop();
onChanged(entry.key);
},
),
],
),
),
),
);
}
@@ -10,6 +10,7 @@ import '../domain/file_change.dart';
import '../domain/unified_patch.dart';
import 'change_style.dart';
import 'patch_view.dart';
import 'raw_patch_view.dart';
/// The reusable viewer for one recorded file change: its kind, path, stat,
/// tags, the rendered or raw unified patch, Copy patch (the server's exact
@@ -38,6 +39,8 @@ class _FileDiffViewerState extends State<FileDiffViewer> {
super.dispose();
}
void _selectForm(DiffForm value) => setState(() => _form = value);
void _close() {
final close = widget.onClose;
if (close != null) {
@@ -147,16 +150,33 @@ class _FileDiffViewerState extends State<FileDiffViewer> {
crossAxisAlignment: WrapCrossAlignment.center,
children: [
if (file.hasPatch)
diffFormControl(
context,
form: _form,
onChanged: (value) => setState(() => _form = value),
LayoutBuilder(
builder: (context, constraints) {
// Two native segmented-control segments cannot show both
// fixed words at 2x text on a narrow host; their menu
// shows the same labels whole, one per row.
final control =
diffFormSegmentsFit(context, constraints.maxWidth)
? diffFormControl(
context,
form: _form,
onChanged: _selectForm,
)
: diffFormMenu(
context,
form: _form,
onChanged: _selectForm,
);
return control;
},
),
_scrollsWhenTooWide(
copyPatchControl(
context,
enabled: file.hasPatch,
copied: _copied,
onPressed: _copy,
),
copyPatchControl(
context,
enabled: file.hasPatch,
copied: _copied,
onPressed: _copy,
),
],
),
@@ -167,13 +187,13 @@ class _FileDiffViewerState extends State<FileDiffViewer> {
? CupertinoColors.separator.resolveFrom(context)
: Theme.of(context).dividerColor,
),
Flexible(child: _body(context, cupertino, mono)),
Flexible(child: _body(context, mono)),
],
),
);
}
Widget _body(BuildContext context, bool cupertino, TextStyle mono) {
Widget _body(BuildContext context, TextStyle mono) {
final file = widget.file;
if (file.binary) return _message(context, binaryDiffMessage);
if (!file.hasPatch) {
@@ -184,24 +204,7 @@ class _FileDiffViewerState extends State<FileDiffViewer> {
container: true,
label: 'Raw patch for ${file.path}',
value: file.patch,
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
child: SingleChildScrollView(
// Raw patch bytes are one line each: scroll them sideways like the
// web view instead of wrapping a continuation under a new line.
scrollDirection: Axis.horizontal,
child: ExcludeSemantics(
child: SelectionArea(
child: Text(
file.patch!,
style: mono,
softWrap: false,
overflow: TextOverflow.visible,
),
),
),
),
),
child: RawPatchView(patch: file.patch!, style: mono),
);
}
return SingleChildScrollView(
@@ -218,6 +221,15 @@ class _FileDiffViewerState extends State<FileDiffViewer> {
}
}
/// Gives a native control its intrinsic width and lets it scroll sideways when
/// the dialog is narrower than the control, instead of letting the control clip
/// or break one of its fixed labels.
///
/// The scroll view shrink-wraps when the control already fits, so the action
/// keeps its usual layout until scaled text or a narrow phone demands more room.
Widget _scrollsWhenTooWide(Widget control) =>
SingleChildScrollView(scrollDirection: Axis.horizontal, child: control);
/// Open [file] in the platform's standard modal: a Material dialog on
/// Android/desktop/web, a Cupertino dialog with a popup surface on iOS/macOS.
Future<void> showFileDiffViewer(BuildContext context, FileChange file) {
@@ -231,15 +243,20 @@ Future<void> showFileDiffViewer(BuildContext context, FileChange file) {
// A popup surface spans the window unless it is inset; on a phone the
// screen edge would clip its native rounded corners.
final width = MediaQuery.sizeOf(dialogContext).width;
return Padding(
padding: EdgeInsets.symmetric(
horizontal: width < 600 ? 16 : 40,
vertical: 24,
),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 900),
child: CupertinoPopupSurface(child: SafeArea(child: viewer)),
return Theme(
// Dialogs open on the app Navigator, above the Changes page's own
// brightness-aware theme, so the popup needs its own.
data: hostTextTheme(dialogContext),
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: width < 600 ? 16 : 40,
vertical: 24,
),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 900),
child: CupertinoPopupSurface(child: SafeArea(child: viewer)),
),
),
),
);
@@ -0,0 +1,75 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'change_style.dart';
/// The recorded raw patch bytes, one recorded line per line, in the host's own
/// selectable body.
///
/// Material uses [SelectionArea]; a Cupertino host has no
/// [MaterialLocalizations], so it renders the same text in the read-only
/// [CupertinoTextField] the run detail already uses for plain selectable text.
/// Both forms keep their intrinsic line width, so long lines scroll sideways
/// instead of wrapping a continuation under a new line.
class RawPatchView extends StatefulWidget {
const RawPatchView({super.key, required this.patch, required this.style});
final String patch;
final TextStyle style;
@override
State<RawPatchView> createState() => _RawPatchViewState();
}
class _RawPatchViewState extends State<RawPatchView> {
late final TextEditingController _text = TextEditingController(
text: widget.patch,
);
@override
void didUpdateWidget(RawPatchView oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.patch != _text.text) _text.text = widget.patch;
}
@override
void dispose() {
_text.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final cupertino = usesCupertino(context);
return SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: cupertino
? IntrinsicWidth(
child: ExcludeSemantics(
child: CupertinoTextField(
key: const ValueKey('raw-patch-field'),
controller: _text,
readOnly: true,
maxLines: null,
padding: EdgeInsets.zero,
decoration: const BoxDecoration(),
style: widget.style,
),
),
)
: ExcludeSemantics(
child: SelectionArea(
child: Text(
widget.patch,
style: widget.style,
softWrap: false,
overflow: TextOverflow.visible,
),
),
),
),
);
}
}
@@ -0,0 +1,236 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../../core/api_gateway.dart';
import '../data/chat_repository.dart';
import '../domain/chat_transcript.dart';
/// One open conversation's transcript and live turn state.
///
/// The controller attaches to exactly one session: it subscribes that session
/// with `chat_subscribe`, then reads the newest history page. Pushed frames for
/// any other session are ignored, a superseded or disposed read never lands, and
/// a reconnect/resync replaces the held turn with the newest authoritative page
/// instead of merging stale state. The server detaches subscriptions when the
/// socket closes, so disposal only cancels the local stream (there is no
/// `chat_unsubscribe`).
class ChatThreadController extends ChangeNotifier {
ChatThreadController(this.gateway, this.sessionId) {
_subscription = gateway.frames.listen(_onFrame);
}
final ApiGateway gateway;
final String sessionId;
late final ChatRepository _repository = ChatRepository(gateway);
StreamSubscription<JsonMap>? _subscription;
List<JsonMap> _messages = const [];
bool _running = false;
bool _loaded = false;
bool _loading = false;
bool _hasMore = false;
String _cursor = '';
String _nativeTurnId = '';
String? _error;
bool _subscribed = false;
String? _subscriptionError;
bool _disposed = false;
int _generation = 0;
bool _resyncing = false;
bool _resyncAgain = false;
List<JsonMap> get messages => _messages;
bool get running => _running;
bool get loaded => _loaded;
bool get loading => _loading;
bool get hasMore => _hasMore;
/// The server's opaque older-page cursor. Never interpreted, only passed back.
String get cursor => _cursor;
String? get error => _error;
bool get subscribed => _subscribed;
String? get subscriptionError => _subscriptionError;
/// Subscribes this session, then loads its newest history page.
Future<void> load() async {
if (_disposed) return;
final token = ++_generation;
_loading = true;
_error = null;
_notify();
await _attach();
if (!_owned(token)) return;
await _readNewest(token, replaceHeldTurn: false);
}
/// Reads the next older page. Only offered while the server says `has_more`;
/// the cursor is the server's own `next_cursor`, passed back verbatim.
Future<void> loadOlder() async {
if (_disposed || _loading || !_hasMore) return;
final token = ++_generation;
_loading = true;
_error = null;
_notify();
try {
final page = await _repository.history(
sessionId,
cursor: _cursor,
limit: 200,
);
if (!_owned(token)) return;
final merged = mergeChatHistory(
{'messages': _messages},
page,
older: true,
);
_applyPage(merged);
} catch (error) {
if (!_owned(token)) return;
_loading = false;
_error = '$error';
}
_notify();
}
/// The reconnect/resync repair: settle the held turn, re-attach the session,
/// then replace the conversation with the newest authoritative page. Activity
/// replayed while re-attaching (a running step) is fresh native state
/// and survives the replacement. A resync frame also lands here.
Future<void> resync() async {
if (_disposed) return;
if (_resyncing) {
_resyncAgain = true;
return;
}
_resyncing = true;
do {
_resyncAgain = false;
await _resyncOnce();
} while (_resyncAgain && !_disposed);
_resyncing = false;
}
Future<void> _resyncOnce() async {
final token = ++_generation;
_loading = true;
// A socket drop removed the frames feeding the turn, so no held turn may
// keep claiming to run until the re-subscribe proves otherwise.
_running = false;
_nativeTurnId = '';
_notify();
await _attach(force: true);
if (!_owned(token)) return;
await _readNewest(token, replaceHeldTurn: true);
}
Future<void> _readNewest(int token, {required bool replaceHeldTurn}) async {
try {
final page = await _repository.history(sessionId, limit: 200);
if (!_owned(token)) return;
if (replaceHeldTurn) {
_messages = (page['messages'] as List? ?? const [])
.whereType<Map>()
.map((message) => Map<String, dynamic>.from(message))
.toList();
_cursor = '${page['nextCursor'] ?? ''}';
_hasMore = page['hasMore'] == true;
} else {
// A live frame may have arrived while the page was loading; merge it
// over the held transcript instead of replacing it.
_applyPage(mergeChatHistory({'messages': _messages}, page));
}
_loaded = true;
_loading = false;
_error = null;
} catch (error) {
if (!_owned(token)) return;
// A refused read is not an empty successful history: the reason stays
// visible and the held transcript is kept.
_loaded = true;
_loading = false;
_error = '$error';
}
_notify();
}
/// Attaches the session stream once per connection. A refusal leaves history
/// usable (the live stream is simply not attached) and is retried on resync.
Future<void> _attach({bool force = false}) async {
if (_disposed || (_subscribed && !force)) return;
try {
await _repository.subscribe(sessionId);
if (_disposed) return;
_subscribed = true;
_subscriptionError = null;
} catch (error) {
// History stays usable, but the UI must report that live updates failed.
if (_disposed) return;
_subscribed = false;
_subscriptionError = '$error';
}
}
void _onFrame(JsonMap envelope) {
if (_disposed) return;
final body = _eventBody(envelope);
if (body == null || body['session_id'] != sessionId) return;
if (body['kind'] == 'resync') {
unawaited(resync());
return;
}
final current = _thread;
final next = applyChatEvent(current, body);
if (identical(next, current)) return;
_messages = (next['messages'] as List? ?? const [])
.whereType<Map>()
.map((message) => Map<String, dynamic>.from(message))
.toList();
_running = next['running'] == true;
_nativeTurnId = '${next['nativeTurnId'] ?? ''}';
_notify();
}
/// 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.
JsonMap? _eventBody(JsonMap envelope) {
if (envelope['type'] != 'chat_event') return null;
final body = envelope['chat_event'];
if (body is! Map) return null;
return Map<String, dynamic>.from(body);
}
JsonMap get _thread => {
'sessionId': sessionId,
'messages': _messages,
'running': _running,
'nativeTurnId': _nativeTurnId,
};
void _applyPage(JsonMap page) {
_messages = (page['messages'] as List? ?? const [])
.whereType<Map>()
.map((message) => Map<String, dynamic>.from(message))
.toList();
_cursor = '${page['nextCursor'] ?? ''}';
_hasMore = page['hasMore'] == true;
_loaded = true;
_loading = false;
}
bool _owned(int token) => !_disposed && token == _generation;
void _notify() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
_generation++;
unawaited(_subscription?.cancel());
super.dispose();
}
}
+57 -16
View File
@@ -21,18 +21,31 @@ const double kPipelinesWideBreakpoint = 720;
///
/// [graphBuilder] is the optional integration hook for the later graph item.
/// Without it the Graph tab states that graph rendering is pending.
///
/// Standalone use keeps the screen's own native scaffolding. The application
/// shell sets [embedded] because it already owns the one navigation bar, and
/// supplies [syncToken] so a reconnect refreshes in place.
class PipelinesScreen extends StatefulWidget {
const PipelinesScreen({
super.key,
required this.gateway,
this.graphBuilder,
this.onStageSelected,
this.embedded = false,
this.syncToken = 0,
});
final ApiGateway gateway;
final PipelineGraphBuilder? graphBuilder;
final ValueChanged<PipelineStageRef>? onStageSelected;
/// True under the application shell, which owns the single navigation bar.
final bool embedded;
/// Advances when the shared socket is replaced. The mounted controller
/// reloads the list and the selected detail without losing the selection.
final int syncToken;
@override
State<PipelinesScreen> createState() => _PipelinesScreenState();
}
@@ -54,6 +67,10 @@ class _PipelinesScreenState extends State<PipelinesScreen> {
_controller.dispose();
_controller = PipelinesController(PipelinesRepository(widget.gateway))
..load();
} else if (oldWidget.syncToken != widget.syncToken) {
// The socket was replaced; re-read through the existing controller so the
// selected pipeline and requested version survive the reconnect.
_controller.load();
}
}
@@ -102,6 +119,7 @@ class _PipelinesScreenState extends State<PipelinesScreen> {
);
},
);
if (widget.embedded) return _embeddedBody(context, body);
return useCupertinoControls(context)
? _cupertinoShell(context, body)
: _materialShell(context, body);
@@ -109,6 +127,43 @@ class _PipelinesScreenState extends State<PipelinesScreen> {
);
}
/// The shell owns the navigation bar here, so the content keeps a native
/// Refresh action without adding a second bar.
Widget _embeddedBody(BuildContext context, Widget body) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Align(
alignment: AlignmentDirectional.centerEnd,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: _refreshButton(context),
),
),
Expanded(child: body),
],
);
}
Widget _refreshButton(BuildContext context) {
if (useCupertinoControls(context)) {
return Semantics(
button: true,
label: 'Refresh',
child: CupertinoButton(
padding: EdgeInsets.zero,
onPressed: _controller.load,
child: const Icon(CupertinoIcons.refresh),
),
);
}
return IconButton(
tooltip: 'Refresh',
onPressed: _controller.load,
icon: const Icon(Icons.refresh),
);
}
Widget _divider(BuildContext context) {
if (useCupertinoControls(context)) {
return Container(
@@ -123,13 +178,7 @@ class _PipelinesScreenState extends State<PipelinesScreen> {
return Scaffold(
appBar: AppBar(
title: const Text('Pipelines'),
actions: [
IconButton(
tooltip: 'Refresh',
onPressed: _controller.load,
icon: const Icon(Icons.refresh),
),
],
actions: [_refreshButton(context)],
),
body: SafeArea(child: body),
);
@@ -139,15 +188,7 @@ class _PipelinesScreenState extends State<PipelinesScreen> {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: const Text('Pipelines'),
trailing: Semantics(
button: true,
label: 'Refresh',
child: CupertinoButton(
padding: EdgeInsets.zero,
onPressed: _controller.load,
child: const Icon(CupertinoIcons.refresh),
),
),
trailing: _refreshButton(context),
),
child: SafeArea(top: false, child: body),
);
@@ -0,0 +1,126 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../../../ui/adaptive/host.dart';
import '../../changes/changes.dart';
/// The run detail's action and page label. The viewer itself owns the
/// recorded summary and capture wording, so this bar stays neutral.
const runChangesLabel = 'Changes';
const runChangesButtonKey = ValueKey<String>('run-detail-changes');
/// The detail's `steps` exactly as returned by the server. The pushed page
/// snapshots the returned list once, so it never re-derives on each rebuild.
List<JsonMap> runDetailChangeSteps(JsonMap run) {
final steps = run['steps'];
if (steps is List<JsonMap>) return steps;
if (steps is List) return steps.cast<JsonMap>();
return const <JsonMap>[];
}
const _executingStatuses = {'queued', 'running', 'waiting'};
/// Whether the run detail offers the action at all. The opened page is a
/// snapshot of the recorded steps, so it is offered only once nothing is
/// executing: the server's own `executing` flag (which can stay true on a
/// failed run whose step is still active) or a queued/running/waiting status
/// would otherwise show a page that silently goes stale.
bool showRunChangesAction(JsonMap run) =>
run['executing'] != true &&
!_executingStatuses.contains('${run['status'] ?? ''}'.trim().toLowerCase());
/// A standard native button for the run detail body. It opens the recorded
/// changes in a platform page whose single navigation bar is the only chrome.
class RunChangesButton extends StatelessWidget {
const RunChangesButton({super.key, required this.run});
final JsonMap run;
@override
Widget build(BuildContext context) {
final steps = runDetailChangeSteps(run);
// The web client shows the run-wide aggregate only for a succeeded run; a
// failed run still keeps each visit's own recorded capture.
final summary = showRunChangesSummary(run['status']);
void open() => showRunChanges(context, steps: steps, showSummary: summary);
if (usesCupertinoHost(context)) {
return CupertinoButton.tinted(
key: runChangesButtonKey,
onPressed: open,
child: const Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(CupertinoIcons.doc_text),
SizedBox(width: 6),
Text(runChangesLabel),
],
),
);
}
return FilledButton.tonalIcon(
key: runChangesButtonKey,
onPressed: open,
icon: const Icon(Icons.difference_outlined),
label: const Text(runChangesLabel),
);
}
}
/// Opens the already-landed [ChangesViewer] for [steps] on a native page.
/// The bar is the one title bar; the viewer's own summary and capture facts
/// are passed through untouched, except for the caller's [showSummary] gate.
Future<void> showRunChanges(
BuildContext context, {
required List<JsonMap> steps,
required bool showSummary,
}) {
final cupertino = usesCupertinoHost(context);
return Navigator.of(context).push<void>(
cupertino
? CupertinoPageRoute<void>(
builder: (_) =>
_CupertinoChangesPage(steps: steps, showSummary: showSummary),
)
: MaterialPageRoute<void>(
builder: (_) =>
_MaterialChangesPage(steps: steps, showSummary: showSummary),
),
);
}
class _MaterialChangesPage extends StatelessWidget {
const _MaterialChangesPage({required this.steps, required this.showSummary});
final List<JsonMap> steps;
final bool showSummary;
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text(runChangesLabel)),
body: SafeArea(
top: false,
child: ChangesViewer(steps: steps, showSummary: showSummary),
),
);
}
class _CupertinoChangesPage extends StatelessWidget {
const _CupertinoChangesPage({required this.steps, required this.showSummary});
final List<JsonMap> steps;
final bool showSummary;
@override
Widget build(BuildContext context) => CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(middle: Text(runChangesLabel)),
child: SafeArea(
// A CupertinoApp supplies no Material theme; follow the host brightness
// so the viewer's Material-derived section text stays readable.
child: Theme(
data: hostTextTheme(context),
child: ChangesViewer(steps: steps, showSummary: showSummary),
),
),
);
}
@@ -0,0 +1,54 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../../../ui/adaptive/host.dart';
import '../actions/decision_action.dart';
import '../actions/decision_wording.dart';
import '../domain/run_decisions.dart';
/// A recorded human checkpoint, never an audit-export/resource wait.
class RunDecisionNotice extends StatelessWidget {
const RunDecisionNotice({
super.key,
required this.run,
required this.gateway,
required this.onRunChanged,
});
final JsonMap run;
final ApiGateway gateway;
final ValueChanged<JsonMap> onRunChanged;
@override
Widget build(BuildContext context) {
final pending = pendingDecision(run);
if (pending == null) return const SizedBox.shrink();
final content = Padding(
padding: const EdgeInsets.all(16),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Semantics(header: true, child: const Text(decisionWaitingTitle)),
Text(decisionMeta(pending)),
HumanDecisionAction(
run: run,
gateway: gateway,
onRunChanged: onRunChanged,
),
],
),
);
if (usesCupertinoHost(context)) {
return CupertinoListSection.insetGrouped(
children: [
DefaultTextStyle(
style: CupertinoTheme.of(context).textTheme.textStyle,
child: content,
),
],
);
}
return Card(child: content);
}
}
@@ -0,0 +1,44 @@
import 'package:flutter/widgets.dart';
import '../../../core/api_gateway.dart';
import '../actions/cancel_run_action.dart';
import '../actions/title_action.dart';
import 'run_decision_notice.dart';
/// Native actions on the loaded run, all using the app's one gateway and
/// applying only accepted server detail through the same controller callback.
class RunDetailActions extends StatelessWidget {
const RunDetailActions({
super.key,
required this.run,
required this.gateway,
required this.onRunChanged,
});
final JsonMap run;
final ApiGateway gateway;
final ValueChanged<JsonMap> onRunChanged;
@override
Widget build(BuildContext context) => Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Wrap(
children: [
RunTitleAction(
run: run,
gateway: gateway,
onRunChanged: onRunChanged,
),
CancelRunAction(
run: run,
gateway: gateway,
onRunChanged: onRunChanged,
),
],
),
RunDecisionNotice(run: run, gateway: gateway, onRunChanged: onRunChanged),
],
);
}
@@ -2,6 +2,7 @@ import 'package:flutter/cupertino.dart';
import '../../../core/api_gateway.dart';
import '../domain/run_models.dart';
import 'run_changes_action.dart';
import 'run_detail_content.dart';
/// The runs detail with standard Cupertino controls. It has no Material
@@ -10,7 +11,7 @@ import 'run_detail_content.dart';
Widget buildCupertinoRunDetail({
required BuildContext context,
required JsonMap run,
required Widget titleAction,
required Widget headerActions,
required bool detailLoading,
required String? error,
required bool copying,
@@ -27,7 +28,11 @@ Widget buildCupertinoRunDetail({
children: [
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0),
child: Row(
child: Wrap(
alignment: WrapAlignment.spaceBetween,
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 8,
runSpacing: 4,
children: [
CupertinoButton(
padding: EdgeInsets.zero,
@@ -41,7 +46,7 @@ Widget buildCupertinoRunDetail({
],
),
),
const Spacer(),
if (showRunChangesAction(run)) RunChangesButton(run: run),
if (copying) const CupertinoActivityIndicator(),
],
),
@@ -65,7 +70,7 @@ Widget buildCupertinoRunDetail({
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0),
child: Align(
alignment: AlignmentDirectional.centerStart,
child: titleAction,
child: headerActions,
),
),
if (detailLoading) const _CupertinoNotice('Refreshing run details…'),
@@ -2,13 +2,14 @@ import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../domain/run_models.dart';
import 'run_changes_action.dart';
import 'run_detail_content.dart';
/// The runs detail with standard Material controls.
Widget buildMaterialRunDetail({
required BuildContext context,
required JsonMap run,
required Widget titleAction,
required Widget headerActions,
required bool detailLoading,
required String? error,
required bool copying,
@@ -24,13 +25,18 @@ Widget buildMaterialRunDetail({
key: ValueKey<String>('run-detail-${run['id']}'),
padding: const EdgeInsets.all(16),
children: [
Align(
alignment: AlignmentDirectional.centerStart,
child: TextButton.icon(
onPressed: onBack,
icon: const Icon(Icons.arrow_back),
label: const Text('Back to list'),
),
Wrap(
spacing: 8,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
TextButton.icon(
onPressed: onBack,
icon: const Icon(Icons.arrow_back),
label: const Text('Back to list'),
),
if (showRunChangesAction(run)) RunChangesButton(run: run),
],
),
Text(detailTitle(run), style: theme.textTheme.headlineSmall),
const SizedBox(height: 8),
@@ -42,7 +48,7 @@ Widget buildMaterialRunDetail({
Chip(label: Text(runStatusLabel(run))),
Text('Run ${run['id']}'),
Text('Pipeline ${detailPipeline(run)}'),
titleAction,
headerActions,
],
),
if (detailLoading) const _Notice('Refreshing run details…'),
@@ -4,7 +4,7 @@ import 'package:flutter/services.dart';
import '../../../core/api_gateway.dart';
import '../../../ui/adaptive/host.dart';
import '../actions/title_action.dart';
import 'run_detail_actions.dart';
import 'run_detail_content.dart';
import 'run_detail_cupertino.dart';
import 'run_detail_material.dart';
@@ -40,7 +40,7 @@ class _RunDetailViewState extends State<RunDetailView> {
final run = widget.controller.detail;
if (run == null) return _placeholder(context, cupertino: cupertino);
final prompt = detailPrompt(run);
final titleAction = RunTitleAction(
final headerActions = RunDetailActions(
run: run,
gateway: widget.gateway,
onRunChanged: widget.controller.acceptRunDetail,
@@ -49,7 +49,7 @@ class _RunDetailViewState extends State<RunDetailView> {
? buildCupertinoRunDetail(
context: context,
run: run,
titleAction: titleAction,
headerActions: headerActions,
detailLoading: widget.controller.detailLoading,
error: widget.controller.error,
copying: _copying,
@@ -60,7 +60,7 @@ class _RunDetailViewState extends State<RunDetailView> {
: buildMaterialRunDetail(
context: context,
run: run,
titleAction: titleAction,
headerActions: headerActions,
detailLoading: widget.controller.detailLoading,
error: widget.controller.error,
copying: _copying,
+21 -1
View File
@@ -114,12 +114,32 @@ class RunsController extends ChangeNotifier {
if (id == null) return;
var changed = false;
if (detail?['id'] == id) {
++_detailGeneration;
_cancelDetailRefresh();
detail = run;
detailLoading = false;
error = null;
changed = true;
}
final index = runs.indexWhere((row) => row['id'] == id);
if (index >= 0) {
runs = [...runs]..[index] = {...runs[index], 'title': run['title'] ?? ''};
// 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',
};
runs = [...runs]
..[index] = {
...runs[index],
for (final entry in run.entries)
if (!detailOnly.contains(entry.key)) entry.key: entry.value,
};
changed = true;
}
if (changed) notifyListeners();
@@ -0,0 +1,223 @@
import '../../../../core/api_gateway.dart';
import '../saved_schedule.dart';
import '../schedule_rule.dart';
/// Which half of the timer rule the editor is writing.
enum ScheduleTimerMode { interval, clock }
/// Either a ready-to-send `save_schedule` record or field errors keyed by the
/// draft field the control binds to. [record] is null when any field fails, so
/// an invalid draft can never be mistaken for a save payload.
class ScheduleSaveResult {
ScheduleSaveResult(this.record, this.errors);
final JsonMap? record;
final Map<String, String> errors;
bool get isValid => record != null;
}
/// Core editor state for one saved schedule, mirroring the web editor draft.
///
/// Pure draft only: no network, timer calculation or timezone conversion.
/// [build] mirrors `serializeSchedule` in `web/src/schedules.js` for name,
/// prompt, pinned version, server workspace, timer rule, weekdays and
/// timezone. It starts from a deep copy of the server record, so unknown
/// record/input/rule/run-option fields and the exact revision survive an edit.
class ScheduleDraft {
ScheduleDraft._(this.source, this.pipelineId);
/// The record this draft edits; null for a create.
final SavedSchedule? source;
final int? pipelineId;
String name = '';
String prompt = '';
String version = '';
String workspace = '';
bool enabled = true;
ScheduleTimerMode mode = ScheduleTimerMode.interval;
String every = '24h';
String times = '';
List<String> days = [];
String timezone = '';
String notifyMode = 'auto';
/// New schedule: the server's create sentinel is `id: 0` with no revision.
factory ScheduleDraft.create({
required int pipelineId,
String version = '',
String workspace = '',
String timezone = '',
}) => ScheduleDraft._(null, pipelineId)
..version = version
..workspace = workspace
..timezone = timezone;
/// Existing record: every field starts from the server value, never from a
/// default that could overwrite it.
factory ScheduleDraft.fromSchedule(SavedSchedule s, {int? pipelineId}) {
final rule = s.rule;
return ScheduleDraft._(s, s.pipelineId ?? pipelineId)
..name = s.name
..prompt = s.prompt
..version = s.version?.toString() ?? ''
..workspace = s.workspace
..enabled = s.raw['enabled'] is bool ? s.enabled : true
..mode = rule.isClock
? ScheduleTimerMode.clock
: ScheduleTimerMode.interval
..every = rule.raw['every'] is String ? rule.every : '24h'
..times = rule.times.join(', ')
..days = [...rule.days]
..timezone = rule.timezone
..notifyMode = s.raw['notify_mode'] is String ? s.notifyMode : 'auto';
}
/// Validates every field and assembles the exact `save_schedule` record.
/// The draft and the source snapshot are never mutated.
ScheduleSaveResult build() {
final errors = <String, String>{};
void fail(String field, String message) =>
errors.putIfAbsent(field, () => message);
final selectedPipeline = source?.pipelineId ?? pipelineId;
if (!_validIdentity(selectedPipeline)) {
fail('pipelineId', 'Choose a valid pipeline.');
}
if (source != null &&
(!_validIdentity(source!.id) || !_validIdentity(source!.revision))) {
fail(
'record',
'Schedule identity or revision is missing. Refresh before editing.',
);
}
if (name.trim().isEmpty) fail('name', 'Enter a schedule name.');
if (prompt.trim().isEmpty) fail('prompt', 'Enter a prompt.');
final pinned = int.tryParse(version);
if (!_digits.hasMatch(version) ||
pinned == null ||
pinned < 1 ||
pinned > _maxSafeInteger) {
fail('version', 'Choose a positive pinned version, not latest (0).');
}
if (!workspace.startsWith('/') || _workspaceBreaks.hasMatch(workspace)) {
fail('workspace', 'Enter an absolute workspace path on the server.');
}
if (!const {'auto', 'on', 'off'}.contains(notifyMode)) {
fail('notifyMode', 'Choose a notification mode.');
}
if (days.any((day) => !scheduleDays.contains(day)) ||
days.toSet().length != days.length) {
fail('days', 'Choose valid, distinct weekdays.');
}
List<String>? clock;
if (mode == ScheduleTimerMode.interval) {
if (!_validDuration(every)) {
fail(
'every',
'Interval must be at least 1m (for example 24h or 1h30m).',
);
}
} else {
clock = [for (final time in times.split(',')) time.trim()];
if (clock.any((time) => !_timeOfDay.hasMatch(time)) ||
clock.toSet().length != clock.length) {
fail('times', 'Enter distinct 24-hour times, such as 09:00, 17:30.');
}
}
if (!_validTimezone(timezone.trim())) {
fail('timezone', 'Enter a valid IANA timezone.');
}
if (errors.isNotEmpty) return ScheduleSaveResult(null, errors);
final record = source?.toJson() ?? <String, dynamic>{};
if (source == null) record['id'] = 0;
record['name'] = name.trim();
record['pipeline_id'] = selectedPipeline;
record['version'] = pinned;
record['enabled'] = enabled;
record['input'] = (source?.input ?? <String, dynamic>{})
..['prompt'] = prompt;
// Untrimmed like `workspace: draft.workspace`; validation also runs on the
// untrimmed value, so a valid workspace is sent exactly as the operator
// entered it.
record['workspace'] = workspace;
final rule = source?.rule.toJson() ?? <String, dynamic>{};
for (final key in const ['every', 'times', 'days', 'timezone']) {
rule.remove(key);
}
if (mode == ScheduleTimerMode.interval) {
rule['every'] = every.trim();
} else {
rule['times'] = clock;
}
if (days.isNotEmpty) {
final prior = source?.rule.days ?? const <String>[];
final unchanged =
prior.length == days.length && prior.every(days.contains);
rule['days'] = unchanged ? [...prior] : [...days];
}
if (timezone.trim().isNotEmpty) rule['timezone'] = timezone.trim();
record['rule'] = rule;
record['notify_mode'] = notifyMode;
return ScheduleSaveResult(record, const {});
}
}
const _maxSafeInteger = 9007199254740991;
bool _validIdentity(int? value) =>
value != null && value > 0 && value <= _maxSafeInteger;
final _digits = RegExp(r'^\d+$');
final _timeOfDay = RegExp(r'^([01]\d|2[0-3]):[0-5]\d$');
final _workspaceBreaks = RegExp(r'[\x00\r\n]');
final _zonePart = RegExp(r'^[A-Za-z0-9_+\-]+$');
const _durationPart = r'((?:\d+(?:\.\d*)?|\.\d+))(ms|us|µs|ns|h|m|s)';
final _areas =
'Africa America Antarctica Arctic Asia Atlantic Australia '
'Brazil Canada Chile Etc Europe Indian Mexico Pacific US'
.split(' ');
final _singleZones =
'UTC GMT UCT Zulu Universal Greenwich CET EET EST HST '
'MST WET GB NZ PRC ROC ROK W-SU Egypt Eire Iceland Iran Israel Jamaica '
'Japan Kwajalein Libya Navajo Poland Portugal Singapore Turkey Cuba '
'Hongkong'
.split(' ');
double? _unit(String unit) => switch (unit) {
'h' => 3600000,
'm' => 60000,
's' => 1000,
'ms' => 1,
'us' || 'µs' => .001,
'ns' => .000001,
_ => null,
};
/// Go-style compound duration, at least one minute, as the web client accepts.
bool _validDuration(String text) {
final every = text.trim();
final parts = RegExp(_durationPart).allMatches(every).toList();
final duration = parts.fold<double>(
0,
(sum, part) => sum + double.parse(part[1]!) * _unit(part[2]!)!,
);
return parts.map((part) => part[0]!).join() == every &&
duration.isFinite &&
duration >= 60000;
}
/// Structural IANA check. Dart carries no timezone database, so a known area
/// plus a well-formed location is the strongest pure check; the server stays
/// the final validator.
bool _validTimezone(String value) {
if (value.isEmpty || value == 'Local' || _singleZones.contains(value)) {
return true;
}
final parts = value.split('/');
return parts.length > 1 &&
_areas.contains(parts.first) &&
parts.every(_zonePart.hasMatch);
}