Merge branch 'main' into flutter/templates-gallery

This commit is contained in:
2026-10-21 22:04:02 +01:00
27 changed files with 3267 additions and 83 deletions
@@ -0,0 +1,249 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../../core/api_gateway.dart';
import '../data/chat_repository.dart';
import 'chat_draft_store.dart';
/// One plain-message send: the optimistic identity the thread shows and the
/// exact wire intent. A lost response retries the same intent with these ids.
class ChatComposerSend {
const ChatComposerSend({
required this.sessionId,
required this.text,
required this.operationId,
required this.nativeMessageId,
});
final String sessionId;
/// The trimmed wire text.
final String text;
final String operationId;
final String nativeMessageId;
/// Mirrors the web's `nativeChatMessageId(operationId) || local-<operationId>`.
String get optimisticId =>
nativeMessageId.isEmpty ? 'local-$operationId' : nativeMessageId;
}
typedef ChatSendCallback = void Function(ChatComposerSend send);
typedef ChatSendRejected = void Function(ChatComposerSend send, String error);
/// The composer state for one conversation: exact draft, the one plain prompt
/// in flight, the reply's queued flag and Stop. It is not a transcript:
/// [onOptimistic] and [onRejected] are the thread's seam; Stop settles nothing.
class ChatComposerController extends ChangeNotifier {
ChatComposerController(
this.gateway,
this.sessionId, {
ChatDraftStore? drafts,
this.onOptimistic,
this.onRejected,
this.newOperationId,
}) : _drafts = drafts ?? const SharedPreferencesChatDraftStore() {
_subscription = gateway.frames.listen(_onFrame);
}
final ApiGateway gateway;
final String sessionId;
final ChatSendCallback? onOptimistic;
final ChatSendRejected? onRejected;
final ChatDraftStore _drafts;
/// Test/fixture seam; production mints a unique id per new intent.
final String Function()? newOperationId;
late final ChatRepository _repository = ChatRepository(gateway);
StreamSubscription<JsonMap>? _subscription;
static const String draftSaveFailed =
'This draft could not be saved on this device.';
String _draft = '';
bool _edited = false;
bool _sending = false;
bool _stopping = false;
bool _queued = false;
String? _error;
String? _draftError;
int _operationSeq = 0;
int _loadGeneration = 0;
Future<void> _writes = Future<void>.value();
ChatComposerSend? _pending;
bool _disposed = false;
/// The exact text in the composer. A refusal restores it only when the
/// operator has not typed anything newer.
String get draft => _draft;
/// One prompt request is awaiting its reply; a second send is refused.
bool get sending => _sending;
/// One `chat_interrupt` is awaiting its reply.
bool get stopping => _stopping;
/// The reply said the prompt waits behind the in-flight turn.
bool get queued => _queued;
/// The last send or Stop refusal, kept visible until the next action.
String? get error => _error;
/// Set when the draft could not be persisted; in-memory text still holds.
String? get draftError => _draftError;
/// Reads this session's saved draft. Text typed while the read is pending
/// wins, so a slow store can never replace the operator's newer typing.
Future<void> loadDraft() async {
if (_disposed) return;
final generation = ++_loadGeneration;
var saved = '';
try {
saved = await _drafts.read(sessionId);
} catch (_) {
saved = '';
}
if (_disposed || _edited || generation != _loadGeneration) return;
if (saved == _draft) return;
_draft = saved;
_notify();
}
/// Updates the draft exactly as typed and persists it. A save failure leaves
/// the in-memory draft untouched and sets [draftError].
Future<void> setDraft(String text) {
if (_disposed || text == _draft) return Future<void>.value();
_draft = text;
_edited = true;
_draftError = null;
_notify();
return _persistDraft(text);
}
/// Sends the non-blank draft as one plain message. Only the wire text is
/// trimmed. A refused unchanged intent reuses its operation id; a refusal
/// restores the exact draft unless newer text is already present.
Future<void> send() async {
if (_disposed || _sending) return;
final exact = _draft;
final text = exact.trim();
if (text.isEmpty) return;
final previous = _pending;
late final ChatComposerSend intent;
if (previous != null && previous.text == text) {
intent = previous;
} else {
final operationId = _nextOperationId();
intent = ChatComposerSend(
sessionId: sessionId,
text: text,
operationId: operationId,
nativeMessageId: nativeChatMessageId(operationId),
);
}
_pending = intent;
_sending = true;
_error = null;
_draft = '';
_edited = true;
_notify();
await _persistDraft('');
if (_disposed) return;
onOptimistic?.call(intent);
try {
final reply = await _repository.prompt(
sessionId,
text,
operationId: intent.operationId,
);
if (_disposed) return;
_queued = reply['chat_queued'] == true;
_pending = null;
_sending = false;
_error = null;
_notify();
} catch (error) {
if (_disposed) return;
final message = '$error';
_sending = false;
_error = message;
if (_draft.isEmpty) {
_draft = exact;
_edited = true;
_notify();
await _persistDraft(exact);
if (_disposed) return;
}
onRejected?.call(intent, message);
_notify();
}
}
/// Stops the running turn with the exact `chat_interrupt` query. A failure
/// stays visible and settles nothing; only a reply or frame changes state.
Future<void> stop() async {
if (_disposed || _stopping) return;
_stopping = true;
_error = null;
_notify();
try {
await _repository.interrupt(sessionId);
} catch (error) {
if (!_disposed) _error = '$error';
} finally {
if (!_disposed) {
_stopping = false;
_notify();
}
}
}
void _onFrame(JsonMap envelope) {
if (_disposed || !_queued) return;
if (envelope['type'] != 'chat_event') return;
final body = envelope['chat_event'];
if (body is! Map || body['session_id'] != sessionId) return;
// Usage or compaction does not admit a queued prompt; any other frame for
// this session means the turn it waited behind moved on (web parity).
final kind = body['kind'];
if (kind == 'usage' || kind == 'compaction') return;
_queued = false;
_notify();
}
String _nextOperationId() =>
newOperationId?.call() ??
'native-chat-${DateTime.now().microsecondsSinceEpoch}-${_operationSeq++}';
Future<void> _persistDraft(String text) {
final write = _writes.then((_) async {
var stored = false;
try {
stored = await _drafts.write(sessionId, text);
} catch (_) {
stored = false;
}
if (_disposed || text != _draft) return;
final failure = stored ? null : draftSaveFailed;
if (failure != _draftError) {
_draftError = failure;
_notify();
}
});
_writes = write;
return write;
}
void _notify() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
if (_disposed) return;
_disposed = true;
_loadGeneration++;
unawaited(_subscription?.cancel());
super.dispose();
}
}
@@ -0,0 +1,92 @@
import 'package:shared_preferences/shared_preferences.dart';
/// One conversation's persisted composer draft, keyed by session id.
///
/// The draft is stored exactly as typed (untrimmed); only the wire copy is
/// trimmed. Attachments are intentionally absent: a file handle cannot be
/// serialised, and the web build keeps them memory-only too.
abstract interface class ChatDraftStore {
/// The saved draft, or an empty string when there is none or the store is
/// unavailable. Implementations may throw; the controller treats that as
/// "nothing saved" and keeps its in-memory draft.
Future<String> read(String sessionId);
/// Stores [text] exactly. A blank draft removes the entry so the store does
/// not grow without bound. Returns false when nothing was stored.
Future<bool> write(String sessionId, String text);
}
/// The app's per-session draft keys. Independent of the legacy web/Android
/// storage: no old draft is imported or written under an old key.
const String chatDraftKeyPrefix = 'pipelines.next.chatDraft.v1.';
/// `shared_preferences`-backed draft storage.
///
/// Reads are tolerant and a write reports failure instead of throwing, so the
/// composer can keep the in-memory draft and say plainly that it was not saved.
class SharedPreferencesChatDraftStore implements ChatDraftStore {
const SharedPreferencesChatDraftStore();
Future<SharedPreferences?> _preferences() async {
try {
return await SharedPreferences.getInstance();
} catch (_) {
return null;
}
}
@override
Future<String> read(String sessionId) async {
final preferences = await _preferences();
if (preferences == null) return '';
try {
return preferences.getString('$chatDraftKeyPrefix$sessionId') ?? '';
} catch (_) {
return '';
}
}
@override
Future<bool> write(String sessionId, String text) async {
final preferences = await _preferences();
if (preferences == null) return false;
try {
final key = '$chatDraftKeyPrefix$sessionId';
if (text.isEmpty) return await preferences.remove(key);
return await preferences.setString(key, text);
} catch (_) {
return false;
}
}
}
/// An in-memory store for tests and previews. It never touches the platform
/// store, so no production preference can be mutated by a fixture.
class MemoryChatDraftStore implements ChatDraftStore {
MemoryChatDraftStore({Map<String, String>? drafts}) : _drafts = {...?drafts};
final Map<String, String> _drafts;
bool failReads = false;
bool failWrites = false;
/// A snapshot of the stored entries, so a test can tell a removed key from an
/// empty string.
Map<String, String> get entries => Map.unmodifiable(_drafts);
@override
Future<String> read(String sessionId) async {
if (failReads) throw StateError('Draft storage is unavailable.');
return _drafts[sessionId] ?? '';
}
@override
Future<bool> write(String sessionId, String text) async {
if (failWrites) return false;
if (text.isEmpty) {
_drafts.remove(sessionId);
} else {
_drafts[sessionId] = text;
}
return true;
}
}
@@ -0,0 +1,191 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../ui/adaptive/host.dart';
/// Secondary text under a field, using the host's own colours and text theme.
TextStyle scheduleEditorSecondaryStyle(BuildContext context) {
if (usesCupertinoHost(context)) {
return CupertinoTheme.of(context).textTheme.textStyle.copyWith(
fontSize: 14,
color: CupertinoColors.secondaryLabel.resolveFrom(context),
);
}
final theme = Theme.of(context);
return (theme.textTheme.bodySmall ?? const TextStyle()).copyWith(
color: theme.colorScheme.onSurfaceVariant,
);
}
/// The host's semantic error colour, never a form-specific palette.
TextStyle scheduleEditorErrorStyle(BuildContext context) {
if (usesCupertinoHost(context)) {
return CupertinoTheme.of(context).textTheme.textStyle.copyWith(
color: CupertinoColors.systemRed.resolveFrom(context),
);
}
return TextStyle(color: Theme.of(context).colorScheme.error);
}
/// A wrapping label above its control, with optional helper and field error.
///
/// The browser puts the label in a sibling span, so a native floating label
/// would invent different words and truncate at large text sizes.
class ScheduleEditorField extends StatelessWidget {
const ScheduleEditorField({
super.key,
required this.label,
required this.child,
this.helper,
this.error,
});
final String label;
final Widget child;
final String? helper;
final String? error;
@override
Widget build(BuildContext context) {
final labelStyle = usesCupertinoHost(context)
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodyMedium;
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(label, style: labelStyle),
const SizedBox(height: 6),
child,
if (helper case final text?)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(text, style: scheduleEditorSecondaryStyle(context)),
),
if (error case final text?)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(text, style: scheduleEditorErrorStyle(context)),
),
],
);
}
}
/// One-line or multiline text input in the host's native field style.
class ScheduleEditorTextField extends StatelessWidget {
const ScheduleEditorTextField({
super.key,
required this.label,
required this.controller,
required this.onChanged,
this.fieldKey,
this.keyboardType,
this.minLines = 1,
this.maxLines = 1,
this.enabled = true,
this.helper,
this.error,
this.textInputAction,
});
final String label;
final TextEditingController controller;
final ValueChanged<String> onChanged;
final Key? fieldKey;
final TextInputType? keyboardType;
final int? minLines;
final int? maxLines;
final bool enabled;
final String? helper;
final String? error;
final TextInputAction? textInputAction;
@override
Widget build(BuildContext context) {
final field = usesCupertinoHost(context)
? CupertinoTextField(
key: fieldKey,
controller: controller,
enabled: enabled,
keyboardType: keyboardType,
minLines: minLines,
maxLines: maxLines,
textInputAction: textInputAction,
onChanged: onChanged,
)
: TextField(
key: fieldKey,
controller: controller,
enabled: enabled,
keyboardType: keyboardType,
minLines: minLines,
maxLines: maxLines,
textInputAction: textInputAction,
onChanged: onChanged,
);
return MergeSemantics(
child: ScheduleEditorField(
label: label,
helper: helper,
error: error,
child: field,
),
);
}
}
/// A native switch with a wrapping label and an explanatory helper.
class ScheduleEditorSwitchField extends StatelessWidget {
const ScheduleEditorSwitchField({
super.key,
required this.label,
required this.value,
required this.onChanged,
this.helper,
this.enabled = true,
this.switchKey,
});
final String label;
final bool value;
final ValueChanged<bool> onChanged;
final String? helper;
final bool enabled;
final Key? switchKey;
@override
Widget build(BuildContext context) {
final control = usesCupertinoHost(context)
? CupertinoSwitch(
key: switchKey,
value: value,
onChanged: enabled ? onChanged : null,
)
: Switch(
key: switchKey,
value: value,
onChanged: enabled ? onChanged : null,
);
return MergeSemantics(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(child: Text(label)),
const SizedBox(width: 12),
control,
],
),
if (helper case final text?)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(text, style: scheduleEditorSecondaryStyle(context)),
),
],
),
);
}
}
@@ -0,0 +1,234 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../../../../ui/adaptive/host.dart';
import '../../domain/editor/schedule_draft.dart';
import '../../domain/schedule_rule.dart';
import 'schedule_editor_form_body.dart';
import 'schedule_editor_wording.dart';
/// The server's refusal, verbatim, plus the browser's preservation promise.
String scheduleEditorRefusal(Object error) {
final reason = '$error'.trim();
return '${reason.isEmpty ? 'The schedule was not saved.' : reason} '
'$scheduleEditorDraftPreserved';
}
/// One native form over a landed [ScheduleDraft].
///
/// The form owns only editable controls: it mutates the draft on submit, asks
/// the draft to validate and assemble the exact record, and calls [onSubmit]
/// only with a non-null record. It never talks to a repository, route or
/// scheduler, and an async refusal leaves every typed value in place.
class ScheduleEditorForm extends StatefulWidget {
const ScheduleEditorForm({
super.key,
required this.draft,
required this.onSubmit,
this.onCancel,
this.title,
});
final ScheduleDraft draft;
final Future<void> Function(JsonMap record) onSubmit;
final VoidCallback? onCancel;
final String? title;
@override
State<ScheduleEditorForm> createState() => _ScheduleEditorFormState();
}
class _ScheduleEditorFormState extends State<ScheduleEditorForm> {
late final TextEditingController _name;
late final TextEditingController _prompt;
late final TextEditingController _version;
late final TextEditingController _workspace;
late final TextEditingController _every;
late final TextEditingController _times;
late final TextEditingController _timezone;
late ScheduleTimerMode _mode;
late List<String> _days;
late bool _enabled;
late String _notifyMode;
Map<String, String> _errors = const {};
String? _refusal;
bool _sending = false;
@override
void initState() {
super.initState();
final draft = widget.draft;
_name = TextEditingController(text: draft.name);
_prompt = TextEditingController(text: draft.prompt);
_version = TextEditingController(text: draft.version);
_workspace = TextEditingController(text: draft.workspace);
_every = TextEditingController(text: draft.every);
_times = TextEditingController(text: draft.times);
_timezone = TextEditingController(text: draft.timezone);
_mode = draft.mode;
_days = [...draft.days];
_enabled = draft.enabled;
_notifyMode = draft.notifyMode;
}
@override
void dispose() {
for (final controller in [
_name,
_prompt,
_version,
_workspace,
_every,
_times,
_timezone,
]) {
controller.dispose();
}
super.dispose();
}
String get _heading =>
widget.title ??
(widget.draft.source == null
? scheduleEditorAddTitle
: scheduleEditorEditTitle);
void _clearError(String field) {
if (!_errors.containsKey(field)) return;
setState(() => _errors = {..._errors}..remove(field));
}
void _applyToDraft() {
widget.draft
..name = _name.text
..prompt = _prompt.text
..version = _version.text
..workspace = _workspace.text
..enabled = _enabled
..mode = _mode
..every = _every.text
..times = _times.text
..days = [
for (final day in scheduleDays)
if (_days.contains(day)) day,
]
..timezone = _timezone.text
..notifyMode = _notifyMode;
}
Future<void> _submit() async {
if (_sending) return;
setState(() => _refusal = null);
_applyToDraft();
final result = widget.draft.build();
if (!result.isValid) {
setState(() => _errors = result.errors);
return;
}
setState(() {
_errors = const {};
_sending = true;
});
try {
await widget.onSubmit(result.record!);
} catch (error) {
if (!mounted) return;
setState(() {
_sending = false;
_refusal = scheduleEditorRefusal(error);
});
return;
}
if (mounted) setState(() => _sending = false);
}
@override
Widget build(BuildContext context) {
final cupertino = usesCupertinoHost(context);
return ScheduleEditorFormBody(
heading: _heading,
name: _name,
prompt: _prompt,
version: _version,
workspace: _workspace,
every: _every,
times: _times,
timezone: _timezone,
mode: _mode,
days: _days,
enabled: _enabled,
notifyMode: _notifyMode,
errors: _errors,
sending: _sending,
refusal: _refusal,
onModeChanged: (mode) => setState(() {
_mode = mode;
_errors = {..._errors}
..remove('every')
..remove('times');
}),
onDayToggled: (day) => setState(() {
_days = [..._days];
_days.contains(day) ? _days.remove(day) : _days.add(day);
_errors = {..._errors}..remove('days');
}),
onEnabledChanged: (enabled) => setState(() => _enabled = enabled),
onNotifyChanged: (mode) => setState(() {
_notifyMode = mode;
_errors = {..._errors}..remove('notifyMode');
}),
onEdited: _clearError,
actions: Wrap(
alignment: WrapAlignment.end,
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 12,
runSpacing: 8,
children: [
if (widget.onCancel != null)
_cancelButton(cupertino)
else
const SizedBox.shrink(),
_saveButton(cupertino),
],
),
);
}
Widget _cancelButton(bool cupertino) {
final onPressed = _sending ? null : widget.onCancel;
if (cupertino) {
return CupertinoButton(
key: scheduleEditorCancelKey,
padding: EdgeInsets.zero,
onPressed: onPressed,
child: const Text(scheduleEditorCancelLabel),
);
}
return TextButton(
key: scheduleEditorCancelKey,
onPressed: onPressed,
child: const Text(scheduleEditorCancelLabel),
);
}
Widget _saveButton(bool cupertino) {
final label = Text(
_sending ? scheduleEditorSendingLabel : scheduleEditorSubmitLabel,
);
final onPressed = _sending ? null : _submit;
if (cupertino) {
return CupertinoButton.filled(
key: scheduleEditorSubmitKey,
onPressed: onPressed,
child: label,
);
}
return FilledButton(
key: scheduleEditorSubmitKey,
onPressed: onPressed,
child: label,
);
}
}
@@ -0,0 +1,229 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../ui/adaptive/host.dart';
import '../../domain/editor/schedule_draft.dart';
import 'schedule_editor_fields.dart';
import 'schedule_editor_selectors.dart';
import 'schedule_editor_wording.dart';
/// The visible schedule editor column: native fields, field errors and the
/// Cancel/Save actions. State stays in `ScheduleEditorForm`; this widget only
/// renders the values and forwards edits.
class ScheduleEditorFormBody extends StatelessWidget {
const ScheduleEditorFormBody({
super.key,
required this.heading,
required this.name,
required this.prompt,
required this.version,
required this.workspace,
required this.every,
required this.times,
required this.timezone,
required this.mode,
required this.days,
required this.enabled,
required this.notifyMode,
required this.errors,
required this.sending,
this.refusal,
required this.onModeChanged,
required this.onDayToggled,
required this.onEnabledChanged,
required this.onNotifyChanged,
required this.onEdited,
required this.actions,
});
final String heading;
final TextEditingController name;
final TextEditingController prompt;
final TextEditingController version;
final TextEditingController workspace;
final TextEditingController every;
final TextEditingController times;
final TextEditingController timezone;
final ScheduleTimerMode mode;
final List<String> days;
final bool enabled;
final String notifyMode;
final Map<String, String> errors;
final bool sending;
final String? refusal;
final ValueChanged<ScheduleTimerMode> onModeChanged;
final ValueChanged<String> onDayToggled;
final ValueChanged<bool> onEnabledChanged;
final ValueChanged<String> onNotifyChanged;
final ValueChanged<String> onEdited;
final Widget actions;
static const _gap = SizedBox(height: 16);
static const _timerOptions = [
ScheduleEditorChoice(ScheduleTimerMode.interval, 'Interval'),
ScheduleEditorChoice(ScheduleTimerMode.clock, 'Clock times'),
];
List<ScheduleEditorChoice<String>> get _notifyOptions {
const values = ['auto', 'on', 'off'];
return [
if (!values.contains(notifyMode))
ScheduleEditorChoice(notifyMode, notifyMode),
for (final value in values) ScheduleEditorChoice(value, value),
];
}
Widget _textField({
required Key key,
required String label,
required TextEditingController controller,
required String field,
String? error,
int minLines = 1,
int? maxLines = 1,
TextInputType? keyboardType,
TextInputAction? textInputAction,
}) => ScheduleEditorTextField(
fieldKey: key,
label: label,
controller: controller,
enabled: !sending,
minLines: minLines,
maxLines: maxLines,
keyboardType: keyboardType,
textInputAction: textInputAction,
error: error,
onChanged: (_) => onEdited(field),
);
@override
Widget build(BuildContext context) {
final cupertino = usesCupertinoHost(context);
final titleStyle = cupertino
? CupertinoTheme.of(context).textTheme.navLargeTitleTextStyle
: Theme.of(context).textTheme.titleLarge;
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(heading, style: titleStyle),
const SizedBox(height: 8),
Text(scheduleEditorNote, style: scheduleEditorSecondaryStyle(context)),
_gap,
_textField(
key: scheduleEditorNameKey,
label: scheduleEditorNameLabel,
controller: name,
field: 'name',
error: errors['name'],
textInputAction: TextInputAction.next,
),
_gap,
_textField(
key: scheduleEditorPromptKey,
label: scheduleEditorPromptLabel,
controller: prompt,
field: 'prompt',
error: errors['prompt'],
minLines: 3,
maxLines: null,
keyboardType: TextInputType.multiline,
),
_gap,
_textField(
key: scheduleEditorVersionKey,
label: scheduleEditorVersionLabel,
controller: version,
field: 'version',
error: errors['version'],
keyboardType: TextInputType.number,
textInputAction: TextInputAction.next,
),
_gap,
_textField(
key: scheduleEditorWorkspaceKey,
label: scheduleEditorWorkspaceLabel,
controller: workspace,
field: 'workspace',
error: errors['workspace'],
textInputAction: TextInputAction.next,
),
_gap,
ScheduleEditorChoiceField<ScheduleTimerMode>(
fieldKey: scheduleEditorTimerKey,
label: scheduleEditorTimerLabel,
value: mode,
options: _timerOptions,
enabled: !sending,
onChanged: onModeChanged,
),
_gap,
if (mode == ScheduleTimerMode.interval)
_textField(
key: scheduleEditorEveryKey,
label: scheduleEditorEveryLabel,
controller: every,
field: 'every',
error: errors['every'],
)
else
_textField(
key: scheduleEditorTimesKey,
label: scheduleEditorTimesLabel,
controller: times,
field: 'times',
error: errors['times'],
),
_gap,
ScheduleEditorDaysField(
label: scheduleEditorDaysLabel,
days: days,
enabled: !sending,
error: errors['days'],
onToggle: onDayToggled,
),
_gap,
_textField(
key: scheduleEditorTimezoneKey,
label: scheduleEditorTimezoneLabel,
controller: timezone,
field: 'timezone',
error: errors['timezone'],
),
_gap,
ScheduleEditorSwitchField(
switchKey: scheduleEditorEnabledKey,
label: scheduleEditorEnabledLabel,
helper: scheduleEditorEnabledNote,
value: enabled,
enabled: !sending,
onChanged: onEnabledChanged,
),
_gap,
ScheduleEditorChoiceField<String>(
fieldKey: scheduleEditorNotifyKey,
label: scheduleEditorNotificationsLabel,
value: notifyMode,
options: _notifyOptions,
enabled: !sending,
error: errors['notifyMode'],
onChanged: onNotifyChanged,
),
if (refusal ?? errors['record'] ?? errors['pipelineId']
case final error?) ...[
_gap,
Semantics(
liveRegion: true,
child: Text(
error,
key: scheduleEditorErrorKey,
style: scheduleEditorErrorStyle(context),
),
),
],
_gap,
actions,
],
);
}
}
@@ -0,0 +1,200 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../ui/adaptive/host.dart';
import '../../domain/schedule_rule.dart';
import 'schedule_editor_fields.dart';
/// Day checkbox keys, shared with tests and the browser fixture.
ValueKey<String> scheduleEditorDayKey(String day) =>
ValueKey<String>('schedule-editor-day-$day');
/// One option of a [ScheduleEditorChoiceField].
class ScheduleEditorChoice<T> {
const ScheduleEditorChoice(this.value, this.label);
final T value;
final String label;
}
/// A native drop-down on Material and a native action sheet on Cupertino.
class ScheduleEditorChoiceField<T> extends StatelessWidget {
const ScheduleEditorChoiceField({
super.key,
required this.label,
required this.value,
required this.options,
required this.onChanged,
this.enabled = true,
this.helper,
this.error,
this.fieldKey,
});
final String label;
final T value;
final List<ScheduleEditorChoice<T>> options;
final ValueChanged<T> onChanged;
final bool enabled;
final String? helper;
final String? error;
final Key? fieldKey;
String get _selectedLabel {
for (final option in options) {
if (option.value == value) return option.label;
}
return '';
}
Future<void> _choose(BuildContext context) async {
final chosen = await showCupertinoModalPopup<T>(
context: context,
builder: (sheetContext) => CupertinoActionSheet(
title: Text(label),
actions: [
for (final option in options)
CupertinoActionSheetAction(
onPressed: () => Navigator.pop(sheetContext, option.value),
child: Text(option.label),
),
],
cancelButton: CupertinoActionSheetAction(
onPressed: () => Navigator.pop(sheetContext),
child: const Text('Cancel'),
),
),
);
if (chosen != null) onChanged(chosen);
}
@override
Widget build(BuildContext context) {
final control = usesCupertinoHost(context)
? CupertinoButton(
key: fieldKey,
padding: EdgeInsets.zero,
onPressed: enabled ? () => _choose(context) : null,
child: Row(
children: [
Expanded(child: Text(_selectedLabel)),
const Icon(CupertinoIcons.chevron_down),
],
),
)
: DropdownButtonFormField<T>(
key: fieldKey,
initialValue: value,
isExpanded: true,
items: [
for (final option in options)
DropdownMenuItem<T>(
value: option.value,
child: Text(option.label),
),
],
onChanged: enabled
? (chosen) {
if (chosen != null) onChanged(chosen);
}
: null,
);
return MergeSemantics(
child: ScheduleEditorField(
label: label,
helper: helper,
error: error,
child: control,
),
);
}
}
/// Weekday checkboxes in a wrapping row; no selection means every day.
class ScheduleEditorDaysField extends StatelessWidget {
const ScheduleEditorDaysField({
super.key,
required this.label,
required this.days,
required this.onToggle,
this.enabled = true,
this.error,
});
final String label;
final List<String> days;
final ValueChanged<String> onToggle;
final bool enabled;
final String? error;
@override
Widget build(BuildContext context) {
return ScheduleEditorField(
label: label,
error: error,
child: Wrap(
spacing: 12,
runSpacing: 8,
children: [
for (final day in scheduleDays)
_DayToggle(
day: day,
selected: days.contains(day),
enabled: enabled,
onTap: () => onToggle(day),
),
],
),
);
}
}
class _DayToggle extends StatelessWidget {
const _DayToggle({
required this.day,
required this.selected,
required this.enabled,
required this.onTap,
});
final String day;
final bool selected;
final bool enabled;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final cupertino = usesCupertinoHost(context);
final checkbox = cupertino
? CupertinoCheckbox(
key: scheduleEditorDayKey(day),
value: selected,
onChanged: enabled ? (_) => onTap() : null,
)
: Checkbox(
key: scheduleEditorDayKey(day),
value: selected,
onChanged: enabled ? (_) => onTap() : null,
);
final content = Padding(
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [checkbox, const SizedBox(width: 4), Text(day)],
),
);
return MergeSemantics(
child: cupertino
? GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: enabled ? onTap : null,
child: content,
)
: InkWell(
borderRadius: BorderRadius.circular(8),
onTap: enabled ? onTap : null,
child: content,
),
);
}
}
@@ -0,0 +1,45 @@
import 'package:flutter/widgets.dart';
/// Browser wording and stable keys for the saved-schedule editor, kept
/// verbatim from `web/src/views/schedules.js`.
const scheduleEditorAddTitle = 'Add schedule';
const scheduleEditorEditTitle = 'Edit schedule';
const scheduleEditorNote =
'Future runs only; does not publish or change the workflow. '
'Saving does not start a run.';
const scheduleEditorNameLabel = 'Name';
const scheduleEditorPromptLabel = 'Prompt';
const scheduleEditorVersionLabel = 'Pinned version';
const scheduleEditorWorkspaceLabel = 'Server workspace';
const scheduleEditorTimerLabel = 'Timer';
const scheduleEditorEveryLabel = 'Interval (at least 1m)';
const scheduleEditorTimesLabel = 'Clock times (24h, comma separated)';
const scheduleEditorDaysLabel = 'Weekdays (none means every day)';
const scheduleEditorTimezoneLabel = 'Timezone (blank uses server timezone)';
const scheduleEditorEnabledLabel = 'Enabled';
const scheduleEditorEnabledNote =
'Enabled schedules start future runs automatically, including model '
'usage and the workflow’s permitted tools.';
const scheduleEditorNotificationsLabel = 'Notifications';
const scheduleEditorSubmitLabel = 'Save schedule';
const scheduleEditorSendingLabel = 'Saving…';
const scheduleEditorCancelLabel = 'Cancel';
const scheduleEditorDraftPreserved =
'Your draft is preserved. If this schedule changed elsewhere, reopen it '
'before retrying.';
const scheduleEditorNameKey = ValueKey<String>('schedule-editor-name');
const scheduleEditorPromptKey = ValueKey<String>('schedule-editor-prompt');
const scheduleEditorVersionKey = ValueKey<String>('schedule-editor-version');
const scheduleEditorWorkspaceKey = ValueKey<String>(
'schedule-editor-workspace',
);
const scheduleEditorTimerKey = ValueKey<String>('schedule-editor-timer');
const scheduleEditorEveryKey = ValueKey<String>('schedule-editor-every');
const scheduleEditorTimesKey = ValueKey<String>('schedule-editor-times');
const scheduleEditorTimezoneKey = ValueKey<String>('schedule-editor-timezone');
const scheduleEditorEnabledKey = ValueKey<String>('schedule-editor-enabled');
const scheduleEditorNotifyKey = ValueKey<String>('schedule-editor-notify');
const scheduleEditorSubmitKey = ValueKey<String>('schedule-editor-submit');
const scheduleEditorCancelKey = ValueKey<String>('schedule-editor-cancel');
const scheduleEditorErrorKey = ValueKey<String>('schedule-editor-error');
@@ -79,6 +79,12 @@ class TemplateRepository {
'The server returned no pipeline detail.',
);
}
final id = detail['id'];
if (id is! num || !id.isFinite || id <= 0 || id != id.truncateToDouble()) {
throw const TemplateRepositoryException(
'The server did not confirm a created pipeline.',
);
}
return Map<String, dynamic>.from(detail);
}
}
@@ -0,0 +1,71 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'template_create_wording.dart';
/// Full wrapping native label, not a clipped placeholder/floating field label.
class TemplateCreateNameField extends StatelessWidget {
const TemplateCreateNameField({
super.key,
required this.cupertino,
required this.controller,
required this.enabled,
required this.onSubmit,
});
final bool cupertino;
final TextEditingController controller;
final bool enabled;
final VoidCallback onSubmit;
@override
Widget build(BuildContext context) => MergeSemantics(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text(templateCreateNameLabel),
const SizedBox(height: 8),
if (cupertino)
CupertinoTextField(
key: templateCreateNameKey,
controller: controller,
enabled: enabled,
autofocus: true,
textInputAction: TextInputAction.done,
onSubmitted: (_) => onSubmit(),
)
else
TextField(
key: templateCreateNameKey,
controller: controller,
enabled: enabled,
autofocus: true,
textInputAction: TextInputAction.done,
onSubmitted: (_) => onSubmit(),
),
],
),
);
}
Widget templateCreateDialogAction({
required Key key,
required bool cupertino,
required VoidCallback? onPressed,
required Widget child,
bool primary = false,
}) {
if (cupertino) {
return CupertinoDialogAction(
key: key,
isDefaultAction: primary,
onPressed: onPressed,
child: child,
);
}
if (primary) {
return FilledButton(key: key, onPressed: onPressed, child: child);
}
return TextButton(key: key, onPressed: onPressed, child: child);
}
@@ -6,6 +6,7 @@ import '../../../core/api_gateway.dart';
import '../data/template_repository.dart';
import '../domain/template_entry.dart';
import 'template_create_wording.dart';
import 'template_create_controls.dart';
/// Opens the native create prompt; resolves when it closes. Opening, typing and
/// Cancel send nothing; Create validates the source first and only a passing
@@ -156,7 +157,12 @@ class _TemplateCreateDialogState extends State<_TemplateCreateDialog> {
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_field(),
TemplateCreateNameField(
cupertino: widget.cupertino,
controller: _name,
enabled: _fieldEnabled,
onSubmit: _create,
),
// Feedback stays next to the field it belongs to. The note below can
// be pushed out of the dialog's scroll viewport on a short, large-text
// screen; a refusal or success line must not be.
@@ -189,7 +195,8 @@ class _TemplateCreateDialogState extends State<_TemplateCreateDialog> {
],
);
final actions = [
_dialogAction(
templateCreateDialogAction(
cupertino: widget.cupertino,
key: templateCreateCancelKey,
onPressed: _sending ? null : _cancel,
child: Text(
@@ -198,7 +205,8 @@ class _TemplateCreateDialogState extends State<_TemplateCreateDialog> {
: templateCreateCloseLabel,
),
),
_dialogAction(
templateCreateDialogAction(
cupertino: widget.cupertino,
key: templateCreateConfirmKey,
primary: true,
onPressed: _canSubmit ? _create : null,
@@ -228,60 +236,4 @@ class _TemplateCreateDialogState extends State<_TemplateCreateDialog> {
),
);
}
Widget _field() {
// A wrapping label above the field, like the browser's label span: the
// Material floating label is ellipsized to `New pipeline name (requ…` at 2x
// text, and a Cupertino placeholder is not exposed as the field's name.
// Merging the visible label into the field gives both hosts one node with
// the exact wording and the field's value.
final field = widget.cupertino
? CupertinoTextField(
key: templateCreateNameKey,
controller: _name,
enabled: _fieldEnabled,
autofocus: true,
textInputAction: TextInputAction.done,
onSubmitted: (_) => _create(),
)
: TextField(
key: templateCreateNameKey,
controller: _name,
enabled: _fieldEnabled,
autofocus: true,
textInputAction: TextInputAction.done,
onSubmitted: (_) => _create(),
);
return MergeSemantics(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text(templateCreateNameLabel),
const SizedBox(height: 8),
field,
],
),
);
}
Widget _dialogAction({
required Key key,
required VoidCallback? onPressed,
required Widget child,
bool primary = false,
}) {
if (widget.cupertino) {
return CupertinoDialogAction(
key: key,
isDefaultAction: primary,
onPressed: onPressed,
child: child,
);
}
if (primary) {
return FilledButton(key: key, onPressed: onPressed, child: child);
}
return TextButton(key: key, onPressed: onPressed, child: child);
}
}