From 37332a3d404c4fddb6c703143f3dc21114352879 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 21:22:02 +0100 Subject: [PATCH 01/10] fix(app): keep template controls small and verify create confirmation --- .../templates/data/template_repository.dart | 6 ++ .../ui/template_create_controls.dart | 71 +++++++++++++++++++ .../templates/ui/template_create_dialog.dart | 70 +++--------------- app/notes/T1-create.md | 8 +++ .../data/template_confirmation_test.dart | 25 +++++++ 5 files changed, 121 insertions(+), 59 deletions(-) create mode 100644 app/lib/features/templates/ui/template_create_controls.dart create mode 100644 app/test/features/templates/data/template_confirmation_test.dart diff --git a/app/lib/features/templates/data/template_repository.dart b/app/lib/features/templates/data/template_repository.dart index da56f5ea..d1464ae4 100644 --- a/app/lib/features/templates/data/template_repository.dart +++ b/app/lib/features/templates/data/template_repository.dart @@ -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.from(detail); } } diff --git a/app/lib/features/templates/ui/template_create_controls.dart b/app/lib/features/templates/ui/template_create_controls.dart new file mode 100644 index 00000000..a236cac1 --- /dev/null +++ b/app/lib/features/templates/ui/template_create_controls.dart @@ -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); +} diff --git a/app/lib/features/templates/ui/template_create_dialog.dart b/app/lib/features/templates/ui/template_create_dialog.dart index 584b128d..f2297ed4 100644 --- a/app/lib/features/templates/ui/template_create_dialog.dart +++ b/app/lib/features/templates/ui/template_create_dialog.dart @@ -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); - } } diff --git a/app/notes/T1-create.md b/app/notes/T1-create.md index 80fbf106..67668cbc 100644 --- a/app/notes/T1-create.md +++ b/app/notes/T1-create.md @@ -1,5 +1,13 @@ # T1 — native create-from-template prompt +Manager integration: retained both sides' compatible run-test gateway/scroll +repairs when merging. Split native field/action controls from dialog state so +production files remain under250lines. Added a fail-closed repository guard: +an empty/malformed created detail without a positive integral pipeline identity +cannot be reported as successful creation. The new regression failed before the +guard; all24 template tests pass after. Source/native capture recheck precedes +actual gallery/Settings delivery; no production definition was created. + ## Result A native Material/Cupertino prompt implements the browser's P5 create flow diff --git a/app/test/features/templates/data/template_confirmation_test.dart b/app/test/features/templates/data/template_confirmation_test.dart new file mode 100644 index 00000000..bbd1329c --- /dev/null +++ b/app/test/features/templates/data/template_confirmation_test.dart @@ -0,0 +1,25 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/templates/data/template_repository.dart'; + +import 'template_test_support.dart'; + +void main() { + test( + 'a malformed created detail never becomes a claimed successful create', + () async { + for (final id in [null, 0, -1, 'unknown', 1.5]) { + final gateway = RecordingGateway([ + { + 'type': 'submitted', + 'detail': {'id': id, 'name': 'Unconfirmed'}, + }, + ]); + await expectLater( + TemplateRepository(gateway).submit('Topic', source), + throwsA(isA()), + ); + expect(gateway.calls.single.fields['create_only'], isTrue); + } + }, + ); +} From 565cdaaa1b2c5c6ef5527ab6d15f7594a018d8c8 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 21:25:51 +0100 Subject: [PATCH 02/10] feat(app): add native chat composer draft and send state Persist the exact per-session draft, send one plain prompt with a stable operation/native identity, restore a refused draft without overwriting newer typing, track the reply's queued flag and stop through chat_interrupt. No UI, transport, server or platform change; the optimistic/rejection callbacks and loadDraft are the thread integration seam. --- .../chat_composer_controller.dart | 249 ++++++++++++++++++ .../chat/conversation/chat_draft_store.dart | 92 +++++++ app/notes/C3-state.md | 121 +++++++++ .../chat_composer_draft_test.dart | 180 +++++++++++++ .../conversation/chat_composer_fixtures.dart | 40 +++ .../conversation/chat_composer_send_test.dart | 240 +++++++++++++++++ 6 files changed, 922 insertions(+) create mode 100644 app/lib/features/chat/conversation/chat_composer_controller.dart create mode 100644 app/lib/features/chat/conversation/chat_draft_store.dart create mode 100644 app/notes/C3-state.md create mode 100644 app/test/features/chat/conversation/chat_composer_draft_test.dart create mode 100644 app/test/features/chat/conversation/chat_composer_fixtures.dart create mode 100644 app/test/features/chat/conversation/chat_composer_send_test.dart diff --git a/app/lib/features/chat/conversation/chat_composer_controller.dart b/app/lib/features/chat/conversation/chat_composer_controller.dart new file mode 100644 index 00000000..3f56cc9d --- /dev/null +++ b/app/lib/features/chat/conversation/chat_composer_controller.dart @@ -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-`. + 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? _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 _writes = Future.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 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 setDraft(String text) { + if (_disposed || text == _draft) return Future.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 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 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 _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(); + } +} diff --git a/app/lib/features/chat/conversation/chat_draft_store.dart b/app/lib/features/chat/conversation/chat_draft_store.dart new file mode 100644 index 00000000..3cb29151 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_draft_store.dart @@ -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 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 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 _preferences() async { + try { + return await SharedPreferences.getInstance(); + } catch (_) { + return null; + } + } + + @override + Future read(String sessionId) async { + final preferences = await _preferences(); + if (preferences == null) return ''; + try { + return preferences.getString('$chatDraftKeyPrefix$sessionId') ?? ''; + } catch (_) { + return ''; + } + } + + @override + Future 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? drafts}) : _drafts = {...?drafts}; + + final Map _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 get entries => Map.unmodifiable(_drafts); + + @override + Future read(String sessionId) async { + if (failReads) throw StateError('Draft storage is unavailable.'); + return _drafts[sessionId] ?? ''; + } + + @override + Future write(String sessionId, String text) async { + if (failWrites) return false; + if (text.isEmpty) { + _drafts.remove(sessionId); + } else { + _drafts[sessionId] = text; + } + return true; + } +} diff --git a/app/notes/C3-state.md b/app/notes/C3-state.md new file mode 100644 index 00000000..d8710652 --- /dev/null +++ b/app/notes/C3-state.md @@ -0,0 +1,121 @@ +# C3-state — per-chat composer draft, prompt identity, queued flag and Stop + +Plain-message composer state for one conversation. Nonvisual item: no UI, +widget, shell, transport, server, pubspec or platform change. The existing +`ChatRepository.prompt`/`interrupt`/`nativeChatMessageId` are reused unchanged. + +## What changed + +New files only (no existing file edited): + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/chat/conversation/chat_draft_store.dart` | 92 | injected draft store, `shared_preferences` implementation, in-memory fixture store | +| `lib/features/chat/conversation/chat_composer_controller.dart` | 249 | one conversation's draft, single in-flight prompt, queued flag, Stop, optimistic/rejection seam | +| `test/features/chat/conversation/chat_composer_fixtures.dart` | 40 | fake gateway recording `chat_prompt`/`chat_interrupt` and pushing frames | +| `test/features/chat/conversation/chat_composer_send_test.dart` | 240 | wire identity, guard, retry, queue/frames, Stop, disposal | +| `test/features/chat/conversation/chat_composer_draft_test.dart` | 180 | exact persistence, isolation, load race, storage failures | + +## Draft state + +- `draft` is the exact field text (untrimmed). Only the wire copy is trimmed, + matching the task's "trim wire text only". +- `setDraft` updates memory at once and persists in a serialised write chain, so + rapid edits cannot land out of order. It adds no UI copy of its own. +- The key is `pipelines.next.chatDraft.v1.`; blank drafts remove the + entry. No legacy web/Android key is read or written. Attachments are not + modelled or persisted. +- `loadDraft` is explicit (the thread/screen integration calls it). A store read + that completes after the operator has typed, or after a new load, is ignored, + so a slow store cannot replace newer text. Storage reads that fail mean "no + saved draft"; saves return false, keep the in-memory text and expose + `draftError = "This draft could not be saved on this device."`. +- `MemoryChatDraftStore` is fixture-only; the production default is + `SharedPreferencesChatDraftStore`. + +## Send and identity + +`send()` is a no-op for a blank/whitespace-only draft and while a previous send +is awaiting its reply (`sending` guard). It clears the draft and broadcasts, +then emits the optimistic seam before the request: + +- wire: `{'chat_prompt': {session_id, text: trimmed, operation_id, + native_message_id: nativeChatMessageId(operation_id)}}`, no `files` or + `attachments` keys; +- `ChatComposerSend` gives the thread `operationId`, `nativeMessageId`, + `optimisticId` (`nativeChatMessageId`, else `local-`), trimmed + text and session. No transcript rows are built here. +- A refused send keeps its operation id; sending the same trimmed intent again + reuses that id and native message id (response-loss retry). A different intent + mints a new id. Success clears the retry id, so the next message is new. +- A refusal sets `error`, restores the exact original draft and persists it only + when the composer is still empty. Newer typing wins and is not overwritten; + the rejection callback still reports the refused intent. A failed draft write + is reported through `draftError` and does not prevent the prompt being sent. + +Default operation ids are `native-chat--`; tests inject a +deterministic factory. + +## Queued and Stop + +- `chat_queued == true` on the prompt reply sets `queued`; an absent/false field + clears it. +- Only a `chat_event` for this controller's session clears `queued`, and only + for a frame that means the turn moved on. `usage` and `compaction` frames are + ignored, mirroring `queuedAfterFrame` in `web/src/chat.js`. Other sessions' + frames are ignored. +- `stop()` sends exactly + `chat_interrupt` `{'chat_query': {'session_id': }}`. A failure stays in + `error`; success/failure changes neither `queued` nor any running bit. The + thread's frame owns settlement; no synthetic settle or notice is invented. + +## Checks actually run + +``` +flutter pub get +dart format lib/features/chat/conversation test/features/chat/conversation + # formatted 5 files +flutter analyze # No issues found! (ran in 1.4s) +flutter test test/features/chat # 74 passed +flutter test test/features/chat/conversation # 28 passed +``` + +New regressions (17) cover: + +- exact `chat_prompt` body plus trimmed text, exact native id, cleared draft; +- whitespace-only/no request and double-send guard; +- refusal exposes the server words, restores the exact draft, reuses the same + operation/native id for the unchanged retry, and mints a new id for a new + intent; +- newer typing survives a refusal while the rejected callback still carries the + original intent; +- reply queued flag, other-session/usage/compaction frames ignored, owned frame + clears it, absent reply flag clears a previous one; +- exact `chat_interrupt` body, refusal visible and no queued state change; +- late reply after disposal changes nothing and calls no rejection seam; +- SharedPreferences exact round-trip and blank-key removal; +- per-session isolation, explicit load, load-versus-typing race, unreadable + store, failed save recovery, ordered rapid edits, failed clear still sends. + +## Honest limits + +- **No UI, keyboard, Enter/Ctrl/Cmd+Enter, slash, attachment picker or model + work.** Draft typing, send, Stop and queued notices are not wired into + `chat_thread_controller` or a screen yet; the callbacks and `loadDraft` are the + integration seam for that later item. Attachments remain unsupported. +- **Queued clearing copies the web's `queuedAfterFrame` rule** but does not own + the running bit; a UI must read the thread controller for Send/Stop choice. +- **No browser capture or fixture proof.** Nothing renders in this item; only + unit/controller tests with fake gateways and mock SharedPreferences ran. The + real-device preference write path was not exercised (no device/ADB). +- **Mobile unverified.** Source is pure Dart/Flutter and portable; no Android, + iOS or emulator build was run. +- **No production session, provider turn or network fixture** was used. +- **Not committed/pushed/deployed.** The stage forbids it; work remains + uncommitted in the `flutter/chat-composer` worktree. + +## Preserved work + +`git status --short` shows only the six new paths (the five above plus this +note); no tracked file, pubspec/lock, shell, server, `web/`, legacy client or +platform file changed. Concurrent lanes' and manager commits are untouched. diff --git a/app/test/features/chat/conversation/chat_composer_draft_test.dart b/app/test/features/chat/conversation/chat_composer_draft_test.dart new file mode 100644 index 00000000..99e6f07c --- /dev/null +++ b/app/test/features/chat/conversation/chat_composer_draft_test.dart @@ -0,0 +1,180 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_composer_controller.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'chat_composer_fixtures.dart'; + +/// A store whose read resolves only when the test says so. +class _DelayedDraftStore implements ChatDraftStore { + _DelayedDraftStore(this.saved); + final String saved; + final reads = >[]; + final writes = []; + + @override + Future read(String sessionId) { + final completer = Completer(); + reads.add(completer); + return completer.future; + } + + @override + Future write(String sessionId, String text) async { + writes.add(text); + return true; + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test( + 'SharedPreferences stores the exact per-session draft and clears it', + () async { + SharedPreferences.setMockInitialValues({}); + const store = SharedPreferencesChatDraftStore(); + + expect(await store.write('a', ' line one\nline two '), isTrue); + expect(await store.read('a'), ' line one\nline two '); + expect(await store.read('b'), ''); + + final preferences = await SharedPreferences.getInstance(); + expect( + preferences.getString('${chatDraftKeyPrefix}a'), + ' line one\nline two ', + ); + + expect(await store.write('a', ''), isTrue); + expect(await store.read('a'), ''); + expect(preferences.getString('${chatDraftKeyPrefix}a'), isNull); + }, + ); + + test('drafts stay isolated per conversation and load exactly', () async { + final drafts = MemoryChatDraftStore(); + final firstGateway = FakeComposerGateway(); + final secondGateway = FakeComposerGateway(); + final first = ChatComposerController(firstGateway, 'a', drafts: drafts); + final second = ChatComposerController(secondGateway, 'b', drafts: drafts); + addTearDown(first.dispose); + addTearDown(second.dispose); + addTearDown(firstGateway.close); + addTearDown(secondGateway.close); + + await first.setDraft('draft a\n'); + await second.setDraft('draft b'); + + expect(drafts.entries, {'a': 'draft a\n', 'b': 'draft b'}); + + final reopened = ChatComposerController( + FakeComposerGateway(), + 'a', + drafts: drafts, + ); + addTearDown(reopened.dispose); + await reopened.loadDraft(); + expect(reopened.draft, 'draft a\n'); + }); + + test('a draft typed while the saved draft loads is not replaced', () async { + final store = _DelayedDraftStore('saved'); + final controller = ChatComposerController( + FakeComposerGateway(), + 's', + drafts: store, + ); + addTearDown(controller.dispose); + + final loading = controller.loadDraft(); + await pumpEventQueue(); + await controller.setDraft('typed'); + store.reads.single.complete('saved'); + await loading; + + expect(controller.draft, 'typed'); + expect(store.writes.last, 'typed'); + }); + + test( + 'an unreadable store leaves the draft empty and can load later', + () async { + final drafts = MemoryChatDraftStore(drafts: {'s': 'saved'}) + ..failReads = true; + final controller = ChatComposerController( + FakeComposerGateway(), + 's', + drafts: drafts, + ); + addTearDown(controller.dispose); + + await controller.loadDraft(); + expect(controller.draft, ''); + + drafts.failReads = false; + await controller.loadDraft(); + expect(controller.draft, 'saved'); + }, + ); + + test( + 'a failed draft save keeps the text and reports it, then clears', + () async { + final drafts = MemoryChatDraftStore()..failWrites = true; + final controller = ChatComposerController( + FakeComposerGateway(), + 's', + drafts: drafts, + ); + addTearDown(controller.dispose); + + await controller.setDraft('still here'); + expect(controller.draft, 'still here'); + expect(controller.draftError, ChatComposerController.draftSaveFailed); + expect(drafts.entries, isEmpty); + + drafts.failWrites = false; + await controller.setDraft('saved now'); + expect(controller.draftError, isNull); + expect(drafts.entries, {'s': 'saved now'}); + }, + ); + + test('rapid edits persist in order and the newest draft wins', () async { + final drafts = MemoryChatDraftStore(); + final controller = ChatComposerController( + FakeComposerGateway(), + 's', + drafts: drafts, + ); + addTearDown(controller.dispose); + + final first = controller.setDraft('a'); + final second = controller.setDraft('ab'); + final third = controller.setDraft('abc'); + await Future.wait([first, second, third]); + + expect(controller.draft, 'abc'); + expect(drafts.entries, {'s': 'abc'}); + }); + + test('a failed draft clear still sends and stays visibly unsaved', () async { + final drafts = MemoryChatDraftStore()..failWrites = true; + final gateway = FakeComposerGateway(); + gateway.prompt = (_, _) async => const {}; + final controller = ChatComposerController(gateway, 's', drafts: drafts); + addTearDown(controller.dispose); + addTearDown(gateway.close); + + await controller.setDraft('send me'); + await controller.send(); + + expect(gateway.promptBodies.single['text'], 'send me'); + expect(controller.draft, ''); + expect(controller.error, isNull); + // The in-memory draft cleared; the device store still reports the failure. + expect(controller.draftError, ChatComposerController.draftSaveFailed); + }); +} diff --git a/app/test/features/chat/conversation/chat_composer_fixtures.dart b/app/test/features/chat/conversation/chat_composer_fixtures.dart new file mode 100644 index 00000000..121ff138 --- /dev/null +++ b/app/test/features/chat/conversation/chat_composer_fixtures.dart @@ -0,0 +1,40 @@ +import 'dart:async'; + +import 'package:pipelines_app/core/api_gateway.dart'; + +/// A fake gateway for the composer. The test controls each prompt/interrupt +/// reply; unsolicited frames are pushed through [emitEvent]. +class FakeComposerGateway implements ApiGateway { + final calls = <({String type, JsonMap fields})>[]; + final _frames = StreamController.broadcast(); + Future Function(String text, String operationId)? prompt; + Future Function()? interrupt; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add((type: type, fields: fields)); + switch (type) { + case 'chat_prompt': + final body = fields['chat_prompt'] as JsonMap? ?? const {}; + return prompt == null + ? {} + : prompt!('${body['text'] ?? ''}', '${body['operation_id'] ?? ''}'); + case 'chat_interrupt': + return interrupt == null ? {} : interrupt!(); + } + return {}; + } + + @override + Stream get frames => _frames.stream; + + void emitEvent(JsonMap body) => + _frames.add({'type': 'chat_event', 'chat_event': body}); + + List get promptBodies => calls + .where((call) => call.type == 'chat_prompt') + .map((call) => call.fields['chat_prompt'] as JsonMap) + .toList(); + + void close() => _frames.close(); +} diff --git a/app/test/features/chat/conversation/chat_composer_send_test.dart b/app/test/features/chat/conversation/chat_composer_send_test.dart new file mode 100644 index 00000000..a7f6257f --- /dev/null +++ b/app/test/features/chat/conversation/chat_composer_send_test.dart @@ -0,0 +1,240 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_composer_controller.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart'; + +import 'chat_composer_fixtures.dart'; + +void main() { + late FakeComposerGateway gateway; + late MemoryChatDraftStore drafts; + late ChatComposerController controller; + late List optimistic; + late List rejected; + late int sequence; + + setUp(() { + gateway = FakeComposerGateway(); + drafts = MemoryChatDraftStore(); + optimistic = []; + rejected = []; + sequence = 0; + controller = ChatComposerController( + gateway, + 's', + drafts: drafts, + newOperationId: () => 'op/${++sequence}', + onOptimistic: optimistic.add, + onRejected: (send, error) => rejected.add(error), + ); + }); + + tearDown(() { + controller.dispose(); + gateway.close(); + }); + + test('sends the exact trimmed wire identity and clears the draft', () async { + await controller.setDraft(' hello '); + + await controller.send(); + + expect(gateway.calls, hasLength(1)); + expect(gateway.calls.single.type, 'chat_prompt'); + expect(gateway.calls.single.fields, { + 'chat_prompt': { + 'session_id': 's', + 'text': 'hello', + 'operation_id': 'op/1', + 'native_message_id': 'msg_op1', + }, + }); + expect(controller.draft, ''); + expect(drafts.entries, isEmpty); + expect(controller.sending, isFalse); + expect(controller.error, isNull); + expect(optimistic.single.text, 'hello'); + expect(optimistic.single.operationId, 'op/1'); + expect(optimistic.single.nativeMessageId, 'msg_op1'); + expect(optimistic.single.optimisticId, 'msg_op1'); + }); + + test('a whitespace-only draft sends nothing', () async { + await controller.setDraft(' \n '); + + await controller.send(); + + expect(gateway.calls, isEmpty); + expect(optimistic, isEmpty); + expect(controller.draft, ' \n '); + expect(controller.sending, isFalse); + }); + + test('a second send is refused while one request is in flight', () async { + final reply = Completer>(); + gateway.prompt = (_, _) => reply.future; + await controller.setDraft('one'); + + final first = controller.send(); + await pumpEventQueue(); + expect(controller.sending, isTrue); + expect(gateway.promptBodies, hasLength(1)); + + await controller.send(); + expect(gateway.promptBodies, hasLength(1)); + expect(optimistic, hasLength(1)); + + reply.complete(const {}); + await first; + expect(controller.sending, isFalse); + }); + + test('a refused unchanged intent retries with the same identity', () async { + var fail = true; + gateway.prompt = (_, _) async { + if (fail) throw StateError('response lost'); + return const {}; + }; + await controller.setDraft(' keep me '); + + await controller.send(); + expect(controller.error, contains('response lost')); + expect(controller.draft, ' keep me '); + expect(await drafts.read('s'), ' keep me '); + expect(rejected.single, contains('response lost')); + + fail = false; + await controller.send(); + expect(gateway.promptBodies.map((body) => body['operation_id']), [ + 'op/1', + 'op/1', + ]); + expect(gateway.promptBodies.map((body) => body['native_message_id']), [ + 'msg_op1', + 'msg_op1', + ]); + expect(controller.draft, ''); + expect(controller.error, isNull); + + fail = true; + await controller.setDraft('other'); + await controller.send(); + expect(gateway.promptBodies.last['operation_id'], 'op/2'); + expect(gateway.promptBodies.last['native_message_id'], 'msg_op2'); + }); + + test('a refusal keeps newer typing instead of restoring the draft', () async { + final reply = Completer>(); + gateway.prompt = (_, _) => reply.future; + await controller.setDraft('original'); + + final sending = controller.send(); + await pumpEventQueue(); + await controller.setDraft('newer'); + + reply.completeError(StateError('refused')); + await sending; + + expect(controller.draft, 'newer'); + expect(await drafts.read('s'), 'newer'); + expect(controller.error, contains('refused')); + expect(rejected.single, contains('refused')); + // The optimistic turn still carries the intent that was refused. + expect(optimistic.single.text, 'original'); + }); + + test( + 'takes the queued flag from the reply and clears it on a live frame', + () async { + gateway.prompt = (_, _) async => {'chat_queued': true}; + + await controller.setDraft('first'); + await controller.send(); + expect(controller.queued, isTrue); + + gateway.emitEvent({'session_id': 'other', 'kind': 'text'}); + await pumpEventQueue(); + expect(controller.queued, isTrue, reason: 'not this conversation'); + + gateway.emitEvent({'session_id': 's', 'kind': 'usage'}); + gateway.emitEvent({'session_id': 's', 'kind': 'compaction'}); + await pumpEventQueue(); + expect(controller.queued, isTrue, reason: 'no turn moved on'); + + gateway.emitEvent({'session_id': 's', 'kind': 'step'}); + await pumpEventQueue(); + expect(controller.queued, isFalse); + }, + ); + + test('a reply without chat_queued clears a previous queued flag', () async { + gateway.prompt = (_, _) async => {'chat_queued': true}; + await controller.setDraft('first'); + await controller.send(); + expect(controller.queued, isTrue); + + gateway.prompt = (_, _) async => const {}; + await controller.setDraft('second'); + await controller.send(); + expect(controller.queued, isFalse); + }); + + test( + 'Stop sends the exact interrupt query and leaves state to the frame', + () async { + gateway.prompt = (_, _) async => {'chat_queued': true}; + await controller.setDraft('queued'); + await controller.send(); + + await controller.stop(); + + final stop = gateway.calls.singleWhere( + (call) => call.type == 'chat_interrupt', + ); + expect(stop.fields, { + 'chat_query': {'session_id': 's'}, + }); + expect(controller.error, isNull); + expect(controller.stopping, isFalse); + // Nothing settles the queued prompt behind the composer's back. + expect(controller.queued, isTrue); + }, + ); + + test('a refused Stop stays visible and settles nothing', () async { + gateway.prompt = (_, _) async => {'chat_queued': true}; + await controller.setDraft('queued'); + await controller.send(); + gateway.interrupt = () async => throw StateError('cannot stop'); + + await controller.stop(); + + expect(controller.error, contains('cannot stop')); + expect(controller.stopping, isFalse); + expect(controller.queued, isTrue); + expect(controller.sending, isFalse); + }); + + test('a late reply after disposal changes and reports nothing', () async { + final reply = Completer>(); + gateway.prompt = (_, _) => reply.future; + await controller.setDraft('bye'); + + final sending = controller.send(); + await pumpEventQueue(); + expect(optimistic, hasLength(1)); + + controller.dispose(); + gateway.emitEvent({'session_id': 's', 'kind': 'step'}); + await controller.send(); + expect(gateway.promptBodies, hasLength(1)); + + reply.completeError(StateError('late response')); + await sending; + + expect(rejected, isEmpty); + expect(controller.error, isNull); + expect(controller.draft, ''); + }); +} From d6e6a65db11778765e14cb7de0222bbc9db0752d Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 21:27:10 +0100 Subject: [PATCH 03/10] docs(app): record the C3 composer candidate as committed Keep the task note honest about the committed branch and the server-owned landing. --- app/notes/C3-state.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/app/notes/C3-state.md b/app/notes/C3-state.md index d8710652..f10869a2 100644 --- a/app/notes/C3-state.md +++ b/app/notes/C3-state.md @@ -111,8 +111,9 @@ New regressions (17) cover: - **Mobile unverified.** Source is pure Dart/Flutter and portable; no Android, iOS or emulator build was run. - **No production session, provider turn or network fixture** was used. -- **Not committed/pushed/deployed.** The stage forbids it; work remains - uncommitted in the `flutter/chat-composer` worktree. +- **Committed, not pushed or deployed.** The feature lives on + `flutter/chat-composer`; the landing stage merged `main` into it and the server + owns landing. This lane pushed nothing and changed no service. ## Preserved work From 8760a01b175e75c07d84b7c62d4367fab735db5d Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 21:51:15 +0100 Subject: [PATCH 04/10] feat(app): add native saved-schedule editor form --- .../ui/editor/schedule_editor_fields.dart | 191 +++++++++ .../ui/editor/schedule_editor_form.dart | 234 +++++++++++ .../ui/editor/schedule_editor_form_body.dart | 229 +++++++++++ .../ui/editor/schedule_editor_selectors.dart | 200 ++++++++++ .../ui/editor/schedule_editor_wording.dart | 45 +++ app/notes/S1-form.md | 176 +++++++++ .../ui/editor/schedule_editor_form_test.dart | 162 ++++++++ .../ui/editor/schedule_editor_harness.dart | 82 ++++ .../schedule_editor_interaction_test.dart | 164 ++++++++ .../editor/schedule_editor_layout_test.dart | 80 ++++ app/tool/schedule_editor_probe.mjs | 368 ++++++++++++++++++ app/tool/schedule_editor_probe_app.dart | 170 ++++++++ 12 files changed, 2101 insertions(+) create mode 100644 app/lib/features/schedules/ui/editor/schedule_editor_fields.dart create mode 100644 app/lib/features/schedules/ui/editor/schedule_editor_form.dart create mode 100644 app/lib/features/schedules/ui/editor/schedule_editor_form_body.dart create mode 100644 app/lib/features/schedules/ui/editor/schedule_editor_selectors.dart create mode 100644 app/lib/features/schedules/ui/editor/schedule_editor_wording.dart create mode 100644 app/notes/S1-form.md create mode 100644 app/test/features/schedules/ui/editor/schedule_editor_form_test.dart create mode 100644 app/test/features/schedules/ui/editor/schedule_editor_harness.dart create mode 100644 app/test/features/schedules/ui/editor/schedule_editor_interaction_test.dart create mode 100644 app/test/features/schedules/ui/editor/schedule_editor_layout_test.dart create mode 100644 app/tool/schedule_editor_probe.mjs create mode 100644 app/tool/schedule_editor_probe_app.dart diff --git a/app/lib/features/schedules/ui/editor/schedule_editor_fields.dart b/app/lib/features/schedules/ui/editor/schedule_editor_fields.dart new file mode 100644 index 00000000..044a98e3 --- /dev/null +++ b/app/lib/features/schedules/ui/editor/schedule_editor_fields.dart @@ -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 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 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)), + ), + ], + ), + ); + } +} diff --git a/app/lib/features/schedules/ui/editor/schedule_editor_form.dart b/app/lib/features/schedules/ui/editor/schedule_editor_form.dart new file mode 100644 index 00000000..8862e3d6 --- /dev/null +++ b/app/lib/features/schedules/ui/editor/schedule_editor_form.dart @@ -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 Function(JsonMap record) onSubmit; + final VoidCallback? onCancel; + final String? title; + + @override + State createState() => _ScheduleEditorFormState(); +} + +class _ScheduleEditorFormState extends State { + 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 _days; + late bool _enabled; + late String _notifyMode; + + Map _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 _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, + ); + } +} diff --git a/app/lib/features/schedules/ui/editor/schedule_editor_form_body.dart b/app/lib/features/schedules/ui/editor/schedule_editor_form_body.dart new file mode 100644 index 00000000..5b4a2f19 --- /dev/null +++ b/app/lib/features/schedules/ui/editor/schedule_editor_form_body.dart @@ -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 days; + final bool enabled; + final String notifyMode; + final Map errors; + final bool sending; + final String? refusal; + final ValueChanged onModeChanged; + final ValueChanged onDayToggled; + final ValueChanged onEnabledChanged; + final ValueChanged onNotifyChanged; + final ValueChanged onEdited; + final Widget actions; + + static const _gap = SizedBox(height: 16); + static const _timerOptions = [ + ScheduleEditorChoice(ScheduleTimerMode.interval, 'Interval'), + ScheduleEditorChoice(ScheduleTimerMode.clock, 'Clock times'), + ]; + + List> 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( + 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( + 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, + ], + ); + } +} diff --git a/app/lib/features/schedules/ui/editor/schedule_editor_selectors.dart b/app/lib/features/schedules/ui/editor/schedule_editor_selectors.dart new file mode 100644 index 00000000..637689fb --- /dev/null +++ b/app/lib/features/schedules/ui/editor/schedule_editor_selectors.dart @@ -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 scheduleEditorDayKey(String day) => + ValueKey('schedule-editor-day-$day'); + +/// One option of a [ScheduleEditorChoiceField]. +class ScheduleEditorChoice { + 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 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> options; + final ValueChanged 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 _choose(BuildContext context) async { + final chosen = await showCupertinoModalPopup( + 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( + key: fieldKey, + initialValue: value, + isExpanded: true, + items: [ + for (final option in options) + DropdownMenuItem( + 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 days; + final ValueChanged 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, + ), + ); + } +} diff --git a/app/lib/features/schedules/ui/editor/schedule_editor_wording.dart b/app/lib/features/schedules/ui/editor/schedule_editor_wording.dart new file mode 100644 index 00000000..1fa78e52 --- /dev/null +++ b/app/lib/features/schedules/ui/editor/schedule_editor_wording.dart @@ -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('schedule-editor-name'); +const scheduleEditorPromptKey = ValueKey('schedule-editor-prompt'); +const scheduleEditorVersionKey = ValueKey('schedule-editor-version'); +const scheduleEditorWorkspaceKey = ValueKey( + 'schedule-editor-workspace', +); +const scheduleEditorTimerKey = ValueKey('schedule-editor-timer'); +const scheduleEditorEveryKey = ValueKey('schedule-editor-every'); +const scheduleEditorTimesKey = ValueKey('schedule-editor-times'); +const scheduleEditorTimezoneKey = ValueKey('schedule-editor-timezone'); +const scheduleEditorEnabledKey = ValueKey('schedule-editor-enabled'); +const scheduleEditorNotifyKey = ValueKey('schedule-editor-notify'); +const scheduleEditorSubmitKey = ValueKey('schedule-editor-submit'); +const scheduleEditorCancelKey = ValueKey('schedule-editor-cancel'); +const scheduleEditorErrorKey = ValueKey('schedule-editor-error'); diff --git a/app/notes/S1-form.md b/app/notes/S1-form.md new file mode 100644 index 00000000..07dd36dd --- /dev/null +++ b/app/notes/S1-form.md @@ -0,0 +1,176 @@ +# S1-form — native saved-schedule form + +## What changed + +New files only. No existing feature, shell, route, `main`, pubspec, server, `web/`, +Android/iOS or deployment source was edited. + +| File | Lines | Responsibility | +| --- | ---: | --- | +| `lib/features/schedules/ui/editor/schedule_editor_form.dart` | 234 | state/controllers, submit/validation/refusal, native Cancel/Save actions | +| `lib/features/schedules/ui/editor/schedule_editor_form_body.dart` | 229 | visible column: heading, note, native fields, live error slot | +| `lib/features/schedules/ui/editor/schedule_editor_fields.dart` | 191 | wrapping label shell, native text field/switch, host secondary/error styles | +| `lib/features/schedules/ui/editor/schedule_editor_selectors.dart` | 200 | native timer/notification menus and weekday checkboxes | +| `lib/features/schedules/ui/editor/schedule_editor_wording.dart` | 45 | verbatim browser copy and stable keys | +| `test/features/schedules/ui/editor/schedule_editor_form_test.dart` | 162 | invalid/create/clock/edit record tests | +| `test/features/schedules/ui/editor/schedule_editor_interaction_test.dart` | 164 | refusal, duplicate submit, Cupertino fields/switch/day, Cancel | +| `test/features/schedules/ui/editor/schedule_editor_layout_test.dart` | 80 | 320px/2x wrapping and native dark Cupertino | +| `test/features/schedules/ui/editor/schedule_editor_harness.dart` | 82 | 390/320 Material and Cupertino hosts | +| `tool/schedule_editor_probe_app.dart` | 170 | standalone local fixture with refusing/accepted fake callback | +| `tool/schedule_editor_probe.mjs` | 368 | real Chrome interaction and seven captures | + +The original aim was two production files. The landing draft, the form state, the +native control primitives, the selectors and the verbatim copy do not fit under +the working agreement's 250-line aim together, so they are split by +responsibility rather than into arbitrary fragments. No generic form framework, +inherited controller or schema was introduced; every file is specific to saved +schedules. + +## Behavior + +`ScheduleEditorForm` binds the landed `ScheduleDraft` and nothing else. It opens +with the draft's current values and mutates only the editable fields on submit. +It then calls `draft.build()`: + +- invalid draft — the returned field errors are shown under their controls and + the injected callback is **not** called; there is no partial record; +- valid draft — every control is disabled, Save reads `Saving…`, and + `onSubmit(record)` receives the exact non-null `build()` record once; +- async refusal — controls re-enable, typed controller values stay verbatim, + and the form shows `" Your draft is preserved. If this schedule + changed elsewhere, reopen it before retrying."` (a blank reason gets `The + schedule was not saved.`). The line is a live-region semantics node, so it is + announced like the browser's `role="alert"`; the browser probe asserts its + visible text after scrolling to it. + +After an accepted callback the form re-enables; the integrating caller owns +closing/replacing it, exactly as the web editor closes its modal on success. No +close/route/save logic exists in this slice. + +The form reads its draft once, in `initState` (the Material selectors also take +an `initialValue`). A caller that reuses the widget with a different draft must +give it a new key, e.g. by operation or `draft.id`, so the controls reinitialise; +mutating the draft in place without a new key is not reflected in the UI. + +Editable in this slice: name, prompt, pinned version, absolute server workspace, +timer mode, interval, clock times, weekdays, timezone, enabled and notification +mode. `draft.source`/`pipelineId` are not editable here. The advanced run options +(`model`, `stage_models`, other input keys, `write_paths`, `allow_tools`, `title`, +`output_format`) are not rendered and are **preserved exactly** because the +landed draft starts every edit from the server snapshot. A create still emits the +web sentinel `id: 0`; an edit keeps its exact `id` and `revision`. + +Weekday toggles send one day key per interaction and the form applies them in +server weekday order, so two quick taps cannot lose the first selection. A raw +notification value outside `auto|on|off` stays visible/selectable and is then +rejected by the draft's validation rather than crashing a dropdown assertion. + +## Native presentation + +- Labels are wrapping text above each control, matching the browser's sibling + label word and avoiding a floating-label ellipsis at 2x text. Helper text and + field errors wrap below the control; no fixed control/row heights. +- Material: `TextField`, `Switch`, `Checkbox`, `DropdownButtonFormField`, + `TextButton`, `FilledButton`. +- Cupertino: `CupertinoTextField`, `CupertinoSwitch`, `CupertinoCheckbox`, + `CupertinoButton` menuing through `CupertinoActionSheet`, plus the same + `CupertinoButton` actions. +- Typography and colours come from `Theme`/`CupertinoTheme` semantic roles and + dynamic label/secondary/error colours. Material helpers use `bodySmall`; the + Cupertino secondary style stays on the theme's text style at the native 14pt + detail size and is still scaled by the text scaler. No bespoke palette or + control clone was added. +- The dark Cupertino fixture is a real `CupertinoApp` with + `CupertinoThemeData(brightness: dark)`; its base page background is the native + `systemBackground` black, while fields, labels, blue actions and the green + switch resolve from the dark Cupertino roles. The widget test also asserts the + dark brightness, dark label colour and that no Material control is present. + +## Browser fixture + +`tool/schedule_editor_probe_app.dart` is standalone: an in-process +`ScheduleDraft.create` (pipeline 4, version 2, `/srv/research`, +`Europe/London`) and a fake `onSubmit`. The first valid submit is refused after +900 ms; the retry is accepted. The state is published at +`globalThis.scheduleEditorProbe`; the accepted record is rendered on the page. +No socket, server, authentication or real schedule is involved. + +## Checks actually run + +``` +dart format lib/features/schedules/ui/editor test/features/schedules/ui/editor \ + tool/schedule_editor_probe_app.dart # clean +flutter analyze # No issues found! +flutter test test/features/schedules # 69 passed +flutter test # 686 passed +flutter build web # ✓ Built build/web +flutter build web -t tool/schedule_editor_probe_app.dart \ + -o build/schedule_editor_probe_web # ✓ Built +node --check tool/schedule_editor_probe.mjs # clean +OPENCODE_ARTIFACT_DIR=…/78/public/s1-form-captures \ + node tool/schedule_editor_probe.mjs # all checks passed +``` + +Browser checks that actually ran in real headless Chrome against the fixture: + +- blank submit: 0 callbacks, both field errors exposed; +- first valid submit: pending state, 1 callback, a second click left the count at + 1; +- refusal: `lastError = conflict: revision 13 is stale`, `records = 0`, name and + prompt still `Probe schedule` / `Summarise the release notes.`, and the visible + line contains `Your draft is preserved.`; +- retry: exactly one accepted record, deep-equal to + `{id:0, name:"Probe schedule", pipeline_id:4, version:2, enabled:true, + input:{prompt:"Summarise the release notes."}, workspace:"/srv/research", + rule:{every:"24h", timezone:"Europe/London"}, notify_mode:"auto"}`; +- 320px at 2x text: labels/helpers and both actions still present and readable; +- Cupertino dark at 390px: native fields, switch, checkboxes and actions rendered. + +Captures (shared artifact): + +``` +/Users/alan/.local/share/pipelines/data/artifacts/78/public/s1-form-captures/ + s1-form-material-390-invalid.png + s1-form-material-390-refusal.png + s1-form-material-390-record.png + s1-form-material-320-2x-top.png + s1-form-material-320-2x-bottom.png + s1-form-cupertino-dark-390-top.png + s1-form-cupertino-dark-390-bottom.png + manifest.json +``` + +The refusal copy is visible in +`s1-form-material-390-refusal.png`; the exact accepted record is visible in +`s1-form-material-390-record.png`; wrapping at 320/2x is visible in the two +`320-2x` captures. + +## Full diff + +Every path is new and currently untracked; `git status --short` lists only those +paths and no existing file is modified. The complete patch is saved at: + +`/Users/alan/.local/share/pipelines/data/artifacts/78/public/s1-form.diff` + +## Honest limits + +- **Not committed, pushed or deployed.** This stage forbids that. The candidate + is in the `flutter/schedule-form` worktree for the manager. +- **Not wired into the normal Schedules screen or shell.** There is no editor + dialog/route, no `screen.dart` integration and no navigation; the Schedules + destination's editor entry is a later integration slice. +- **No save engine, repository, network, create/update/pause/delete.** The form + only calls its injected callback and never opens a socket. The existing draft + and repository were not changed. +- **Advanced run options stay preserved but are not editable** in this slice + (`model`, stage models, other input keys, write paths, allow tools, title, + output format). No control was invented for them. +- **Timezone validity remains the landed draft's structural check.** The UI only + displays the draft's error; Dart still has no IANA database here. +- **Mobile unverified.** Only web-targeted Flutter tests/analyze/build ran. No + Android/iOS build, emulator, ADB or device was used. +- **Live server unverified.** Browser evidence is fixture-only; no production + authentication, schedule or run was created or changed. +- **Refusal prefix is the caller's error text.** The real `ProtocolError` has a + clean `toString()`; the fixture throws a custom refusal so the capture does not + show Dart's `Bad state:` prefix from `StateError`. diff --git a/app/test/features/schedules/ui/editor/schedule_editor_form_test.dart b/app/test/features/schedules/ui/editor/schedule_editor_form_test.dart new file mode 100644 index 00000000..050b118d --- /dev/null +++ b/app/test/features/schedules/ui/editor/schedule_editor_form_test.dart @@ -0,0 +1,162 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/schedules/ui/editor/schedule_editor_selectors.dart'; +import 'package:pipelines_app/features/schedules/ui/editor/schedule_editor_wording.dart'; + +import 'schedule_editor_harness.dart'; + +void main() { + testWidgets('invalid draft shows field errors and sends nothing', ( + tester, + ) async { + final calls = []; + await pumpScheduleEditor( + tester, + draft: createDraft(), + onSubmit: (record) async => calls.add(record), + ); + expect(find.text('Add schedule'), findsOneWidget); + + await tester.tap(find.byKey(scheduleEditorSubmitKey)); + await tester.pump(); + + expect(find.text('Enter a schedule name.'), findsOneWidget); + expect(find.text('Enter a prompt.'), findsOneWidget); + expect(calls, isEmpty); + expect( + tester + .widget(find.byKey(scheduleEditorVersionKey)) + .controller! + .text, + '2', + ); + }); + + testWidgets('valid create sends the exact save record', (tester) async { + final calls = []; + final draft = createDraft(); + await pumpScheduleEditor( + tester, + draft: draft, + onSubmit: (record) async => calls.add(record), + ); + + await enterField(tester, scheduleEditorNameKey, 'Probe schedule'); + await enterField( + tester, + scheduleEditorPromptKey, + 'Summarise the release notes.', + ); + await tester.tap(find.byKey(scheduleEditorDayKey('mon'))); + await tester.tap(find.byKey(scheduleEditorDayKey('wed'))); + await tester.pump(); + await tester.tap(find.byKey(scheduleEditorSubmitKey)); + await tester.pumpAndSettle(); + + expect(calls, hasLength(1)); + expect(calls.single, { + 'id': 0, + 'name': 'Probe schedule', + 'pipeline_id': 4, + 'version': 2, + 'enabled': true, + 'input': {'prompt': 'Summarise the release notes.'}, + 'workspace': '/srv/research', + 'rule': { + 'every': '24h', + 'days': ['mon', 'wed'], + 'timezone': 'Europe/London', + }, + 'notify_mode': 'auto', + }); + expect(calls.single.containsKey('revision'), isFalse); + expect(draft.source, isNull); + }); + + testWidgets('clock times, paused state and notifications reach the record', ( + tester, + ) async { + final calls = []; + await pumpScheduleEditor( + tester, + draft: createDraft(name: 'Clock schedule', prompt: 'Run at times'), + onSubmit: (record) async => calls.add(record), + ); + + await tester.tap(find.byKey(scheduleEditorTimerKey)); + await tester.pumpAndSettle(); + await tester.tap(find.text('Clock times').last); + await tester.pumpAndSettle(); + expect(find.text('Clock times (24h, comma separated)'), findsOneWidget); + expect(find.text('Interval (at least 1m)'), findsNothing); + + await enterField(tester, scheduleEditorTimesKey, '09:00, 17:30'); + await tester.tap(find.byKey(scheduleEditorEnabledKey)); + await tester.tap(find.byKey(scheduleEditorNotifyKey)); + await tester.pumpAndSettle(); + await tester.tap(find.text('off').last); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(scheduleEditorSubmitKey)); + await tester.pumpAndSettle(); + + expect(calls.single['enabled'], isFalse); + expect(calls.single['notify_mode'], 'off'); + expect(calls.single['rule'], { + 'times': ['09:00', '17:30'], + 'timezone': 'Europe/London', + }); + }); + + testWidgets('editing keeps CAS identity and unknown raw fields', ( + tester, + ) async { + final calls = []; + await pumpScheduleEditor( + tester, + draft: editDraft(), + onSubmit: (record) async => calls.add(record), + ); + expect(find.text('Edit schedule'), findsOneWidget); + expect( + tester + .widget(find.byKey(scheduleEditorNameKey)) + .controller! + .text, + 'Saved topic', + ); + + await enterField(tester, scheduleEditorNameKey, 'Edited topic'); + await tester.tap(find.byKey(scheduleEditorSubmitKey)); + await tester.pumpAndSettle(); + + final record = calls.single; + expect(record['id'], 9); + expect(record['revision'], 13); + expect(record['pipeline_id'], 4); + expect(record['name'], 'Edited topic'); + expect(record['input'], { + 'prompt': 'Topic', + 'count': 4, + 'flag': false, + 'nested': { + 'list': [null, 2], + }, + }); + expect(record['rule'], { + 'times': ['09:00', '17:30'], + 'days': ['fri', 'mon'], + 'future': 'keep', + }); + expect(record['model'], 'provider/model'); + expect(record['stage_models'], {'research': 'provider/other'}); + expect(record['write_paths'], ['src/file.go']); + expect(record['allow_tools'], isTrue); + expect(record['title'], 'Saved title'); + expect(record['output_format'], 'json'); + expect(record['notify_mode'], 'off'); + expect(record['server_extra'], { + 'keep': [1, true], + }); + }); +} diff --git a/app/test/features/schedules/ui/editor/schedule_editor_harness.dart b/app/test/features/schedules/ui/editor/schedule_editor_harness.dart new file mode 100644 index 00000000..71052bc0 --- /dev/null +++ b/app/test/features/schedules/ui/editor/schedule_editor_harness.dart @@ -0,0 +1,82 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/schedules/domain/editor/schedule_draft.dart'; +import 'package:pipelines_app/features/schedules/domain/saved_schedule.dart'; +import 'package:pipelines_app/features/schedules/ui/editor/schedule_editor_form.dart'; + +import '../../domain/editor/draft_fixtures.dart'; + +ScheduleDraft createDraft({ + String name = '', + String prompt = '', + String version = '2', + String workspace = '/srv/research', + String timezone = 'Europe/London', +}) => + ScheduleDraft.create( + pipelineId: 4, + version: version, + workspace: workspace, + timezone: timezone, + ) + ..name = name + ..prompt = prompt; + +ScheduleDraft editDraft() => + ScheduleDraft.fromSchedule(SavedSchedule(deepCopy(completeRecord()))); + +Future pumpScheduleEditor( + WidgetTester tester, { + required ScheduleDraft draft, + required Future Function(JsonMap record) onSubmit, + bool cupertino = false, + bool dark = false, + double width = 390, + double height = 1600, + double textScale = 1, + VoidCallback? onCancel, +}) async { + tester.view.physicalSize = Size(width, height); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final form = SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: ScheduleEditorForm( + draft: draft, + onSubmit: onSubmit, + onCancel: onCancel, + ), + ); + Widget scaled(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp( + theme: CupertinoThemeData( + brightness: dark ? Brightness.dark : Brightness.light, + ), + builder: scaled, + home: CupertinoPageScaffold(child: SafeArea(child: form)), + ) + : MaterialApp( + theme: ThemeData( + brightness: dark ? Brightness.dark : Brightness.light, + ), + builder: scaled, + home: Scaffold(body: SafeArea(child: form)), + ), + ); + await tester.pumpAndSettle(); +} + +Future enterField(WidgetTester tester, Key key, String value) async { + await tester.enterText(find.byKey(key), value); + await tester.pump(); +} diff --git a/app/test/features/schedules/ui/editor/schedule_editor_interaction_test.dart b/app/test/features/schedules/ui/editor/schedule_editor_interaction_test.dart new file mode 100644 index 00000000..e56e65f5 --- /dev/null +++ b/app/test/features/schedules/ui/editor/schedule_editor_interaction_test.dart @@ -0,0 +1,164 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/schedules/ui/editor/schedule_editor_selectors.dart'; +import 'package:pipelines_app/features/schedules/ui/editor/schedule_editor_wording.dart'; + +import 'schedule_editor_harness.dart'; + +void main() { + testWidgets('async refusal keeps typed values and a retry can succeed', ( + tester, + ) async { + final calls = []; + Object? refusal = StateError('revision 13 is stale'); + await pumpScheduleEditor( + tester, + draft: createDraft(name: 'Probe schedule', prompt: 'Keep these words'), + onSubmit: (record) async { + calls.add(record); + if (refusal case final error?) throw error; + }, + ); + + await tester.tap(find.byKey(scheduleEditorSubmitKey)); + await tester.pumpAndSettle(); + expect(find.byKey(scheduleEditorErrorKey), findsOneWidget); + expect(find.textContaining('revision 13 is stale'), findsOneWidget); + expect(find.textContaining('Your draft is preserved.'), findsOneWidget); + expect( + tester + .widget(find.byKey(scheduleEditorNameKey)) + .controller! + .text, + 'Probe schedule', + ); + expect( + tester + .widget(find.byKey(scheduleEditorPromptKey)) + .controller! + .text, + 'Keep these words', + ); + expect( + tester + .widget(find.byKey(scheduleEditorSubmitKey)) + .onPressed, + isNotNull, + ); + + refusal = null; + await tester.tap(find.byKey(scheduleEditorSubmitKey)); + await tester.pumpAndSettle(); + expect(calls, hasLength(2)); + expect(calls.last['name'], 'Probe schedule'); + expect(find.byKey(scheduleEditorErrorKey), findsNothing); + }); + + testWidgets('a sending form locks controls and rejects a second submit', ( + tester, + ) async { + final gate = Completer(); + var calls = 0; + await pumpScheduleEditor( + tester, + draft: createDraft(name: 'Probe schedule', prompt: 'Run once'), + onSubmit: (_) { + calls++; + return gate.future; + }, + ); + + await tester.tap(find.byKey(scheduleEditorSubmitKey)); + await tester.pump(); + expect(find.text('Saving…'), findsOneWidget); + expect( + tester + .widget(find.byKey(scheduleEditorSubmitKey)) + .onPressed, + isNull, + ); + expect( + tester.widget(find.byKey(scheduleEditorNameKey)).enabled, + isFalse, + ); + + await tester.tap(find.byKey(scheduleEditorSubmitKey)); + await tester.pump(); + expect(calls, 1); + + gate.complete(); + await tester.pumpAndSettle(); + expect(find.text('Save schedule'), findsOneWidget); + expect( + tester + .widget(find.byKey(scheduleEditorSubmitKey)) + .onPressed, + isNotNull, + ); + }); + + testWidgets('Cupertino form uses native fields and action sheets', ( + tester, + ) async { + final calls = []; + await pumpScheduleEditor( + tester, + cupertino: true, + draft: createDraft(name: 'Cupertino schedule', prompt: 'Native fields'), + onSubmit: (record) async => calls.add(record), + ); + expect(find.byType(CupertinoTextField), findsNWidgets(6)); + expect(find.byType(TextField), findsNothing); + expect(find.byType(CupertinoSwitch), findsOneWidget); + expect(find.byType(Switch), findsNothing); + expect(find.byType(CupertinoCheckbox), findsNWidgets(7)); + expect(find.byType(Checkbox), findsNothing); + + await tester.tap(find.byKey(scheduleEditorTimerKey)); + await tester.pumpAndSettle(); + await tester.tap(find.text('Clock times').last); + await tester.pumpAndSettle(); + await enterField(tester, scheduleEditorTimesKey, '06:30'); + await tester.tap(find.byKey(scheduleEditorDayKey('mon'))); + await tester.pump(); + expect( + tester + .widget(find.byKey(scheduleEditorDayKey('mon'))) + .value, + isTrue, + ); + await tester.tap(find.byKey(scheduleEditorEnabledKey)); + await tester.pump(); + await tester.tap(find.byKey(scheduleEditorSubmitKey)); + await tester.pumpAndSettle(); + + expect(calls.single['enabled'], isFalse); + expect(calls.single['rule'], { + 'times': ['06:30'], + 'days': ['mon'], + 'timezone': 'Europe/London', + }); + }); + + testWidgets('Cancel calls the injected callback and sends nothing', ( + tester, + ) async { + var cancelled = 0; + final calls = []; + await pumpScheduleEditor( + tester, + draft: createDraft(name: 'Probe schedule', prompt: 'Prompt'), + onSubmit: (record) async => calls.add(record), + onCancel: () => cancelled++, + ); + + await tester.tap(find.byKey(scheduleEditorCancelKey)); + await tester.pump(); + expect(cancelled, 1); + expect(calls, isEmpty); + }); +} diff --git a/app/test/features/schedules/ui/editor/schedule_editor_layout_test.dart b/app/test/features/schedules/ui/editor/schedule_editor_layout_test.dart new file mode 100644 index 00000000..55613296 --- /dev/null +++ b/app/test/features/schedules/ui/editor/schedule_editor_layout_test.dart @@ -0,0 +1,80 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/schedules/ui/editor/schedule_editor_wording.dart'; + +import 'schedule_editor_harness.dart'; + +const _labels = [ + scheduleEditorNameLabel, + scheduleEditorPromptLabel, + scheduleEditorVersionLabel, + scheduleEditorWorkspaceLabel, + scheduleEditorTimerLabel, + scheduleEditorEveryLabel, + scheduleEditorDaysLabel, + scheduleEditorTimezoneLabel, + scheduleEditorEnabledLabel, + scheduleEditorEnabledNote, + scheduleEditorNotificationsLabel, + scheduleEditorSubmitLabel, +]; + +void main() { + testWidgets('Material labels wrap at 320px with 2x text', (tester) async { + await pumpScheduleEditor( + tester, + width: 320, + height: 1800, + textScale: 2, + draft: createDraft(), + onSubmit: (JsonMap record) async {}, + ); + expect(tester.takeException(), isNull); + for (final label in _labels) { + expect(find.text(label), findsOneWidget, reason: label); + } + expect(find.byType(TextField), findsNWidgets(6)); + expect(find.byType(Switch), findsOneWidget); + expect(find.byType(Checkbox), findsNWidgets(7)); + final note = tester.renderObject( + find.text(scheduleEditorEnabledNote), + ); + expect(note.size.width, lessThanOrEqualTo(320 - 32)); + }); + + testWidgets('Cupertino dark uses native controls and the native palette', ( + tester, + ) async { + await pumpScheduleEditor( + tester, + cupertino: true, + dark: true, + width: 320, + height: 1800, + textScale: 2, + draft: createDraft(), + onSubmit: (JsonMap record) async {}, + ); + expect(tester.takeException(), isNull); + for (final label in _labels) { + expect(find.text(label), findsOneWidget, reason: label); + } + expect(find.byType(CupertinoTextField), findsNWidgets(6)); + expect(find.byType(CupertinoSwitch), findsOneWidget); + expect(find.byType(CupertinoCheckbox), findsNWidgets(7)); + expect(find.byType(Material), findsNothing); + expect(find.byType(TextField), findsNothing); + expect(find.byType(Switch), findsNothing); + expect(find.byType(Checkbox), findsNothing); + + final context = tester.element(find.byKey(scheduleEditorNameKey)); + expect(CupertinoTheme.of(context).brightness, Brightness.dark); + expect( + CupertinoColors.label.resolveFrom(context).toARGB32(), + CupertinoColors.label.darkColor.toARGB32(), + ); + }); +} diff --git a/app/tool/schedule_editor_probe.mjs b/app/tool/schedule_editor_probe.mjs new file mode 100644 index 00000000..941d253a --- /dev/null +++ b/app/tool/schedule_editor_probe.mjs @@ -0,0 +1,368 @@ +import { createServer } from 'node:http'; +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { setTimeout as delay } from 'node:timers/promises'; +import { join, extname, resolve, sep } from 'node:path'; +import { tmpdir } from 'node:os'; +import { deepStrictEqual } from 'node:assert/strict'; + +// Real-browser acceptance for the native saved-schedule form. +// +// flutter build web -t tool/schedule_editor_probe_app.dart \ +// -o build/schedule_editor_probe_web +// OPENCODE_ARTIFACT_DIR= node tool/schedule_editor_probe.mjs +// +// The fixture callback and record are in-process; no Pipelines server, +// authentication or real schedule is contacted. + +const root = resolve(process.env.PROBE_WEB_ROOT ?? 'build/schedule_editor_probe_web'); +const output = process.env.OPENCODE_ARTIFACT_DIR; +if (!output) throw new Error('Set OPENCODE_ARTIFACT_DIR for the probe captures'); +await mkdir(output, { recursive: true }); +const chromePath = process.env.CHROME_PATH + ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +const mime = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.mjs': 'text/javascript; charset=utf-8', + '.json': 'application/json', + '.wasm': 'application/wasm', + '.png': 'image/png', + '.otf': 'font/otf', + '.ttf': 'font/ttf', + '.woff': 'font/woff', + '.woff2': 'font/woff2', + '.ico': 'image/x-icon', + '.bin': 'application/octet-stream', +}; + +const server = createServer(async (req, res) => { + try { + const pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname); + const path = resolve(root, `.${pathname}`); + if (path !== root && !path.startsWith(root + sep)) { + return res.writeHead(403).end(); + } + const filePath = path === root || path.endsWith('/') ? join(path, 'index.html') : path; + const file = await readFile(filePath); + res + .writeHead(200, { + 'content-type': mime[extname(filePath)] ?? 'application/octet-stream', + 'cache-control': 'no-store', + }) + .end(file); + } catch { + res.writeHead(404).end('not found'); + } +}); +server.listen(0, '127.0.0.1'); +await once(server, 'listening'); +const origin = `http://127.0.0.1:${server.address().port}`; + +const profile = await mkdtemp(join(tmpdir(), 's1-form-chrome-')); +const chrome = spawn(chromePath, [ + '--headless=new', + '--no-first-run', + '--no-default-browser-check', + '--disable-gpu', + '--remote-debugging-port=0', + `--user-data-dir=${profile}`, + 'about:blank', +], { stdio: ['ignore', 'ignore', 'pipe'] }); +let stderr = ''; +chrome.stderr.on('data', (data) => { stderr += data; }); + +const waitFor = async (fn, label, attempts = 220) => { + for (let i = 0; i < attempts; i++) { + const value = await fn(); + if (value) return value; + await delay(100); + } + throw new Error(`Timed out waiting for ${label}\n${stderr.slice(-1200)}`); +}; + +let ws; +try { + const endpoint = await waitFor( + () => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1], + 'Chrome DevTools', + ); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + const pageErrors = []; + ws.addEventListener('message', (event) => { + const message = JSON.parse(event.data); + if (message.method === 'Runtime.exceptionThrown') { + pageErrors.push(message.params?.exceptionDetails?.exception?.description ?? 'page exception'); + } + if (message.id && pending.has(message.id)) { + pending.get(message.id)(message); + pending.delete(message.id); + } + }); + const send = (method, params = {}, sessionId) => new Promise((resolveCall) => { + const callId = ++id; + pending.set(callId, resolveCall); + ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) })); + }); + const created = await send('Target.createTarget', { url: 'about:blank' }); + if (!created.result) throw new Error(`Target creation failed: ${JSON.stringify(created)}`); + const target = created.result.targetId; + const session = ( + await send('Target.attachToTarget', { targetId: target, flatten: true }) + ).result.sessionId; + await send('Page.enable', {}, session); + await send('Runtime.enable', {}, session); + + let width = 390; + let height = 844; + const evaluate = async (expression) => { + const response = await send( + 'Runtime.evaluate', + { expression, returnByValue: true, awaitPromise: true }, + session, + ); + if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`); + if (response.result?.exceptionDetails) { + throw new Error(`Runtime exception: ${JSON.stringify(response.result.exceptionDetails)}`); + } + return response.result?.result?.value; + }; + + const text = () => evaluate(`(() => { + const chunks = []; + for (const el of document.querySelectorAll('flt-semantics')) { + const label = el.getAttribute('aria-label'); + if (label) chunks.push(label); + if (!el.children.length && el.innerText) chunks.push(el.innerText); + } + for (const el of document.querySelectorAll('input, textarea')) { + if (el.getAttribute('aria-label')) chunks.push(el.getAttribute('aria-label') + '=' + el.value); + } + if (document.body?.innerText) chunks.push(document.body.innerText); + return [...new Set(chunks)].join('\\n'); + })()`); + + const assertText = async (needle) => { + try { + await waitFor(async () => (await text()).includes(needle), `text ${JSON.stringify(needle)}`); + } catch (error) { + throw new Error(`${error.message}\nText now:\n${(await text()).slice(0, 3000)}`); + } + }; + + const click = async (needle, optional = false) => { + const clicked = await evaluate(`(() => { + const wanted = ${JSON.stringify(needle)}; + const nodes = [...document.querySelectorAll('flt-semantics')]; + const node = nodes.find((x) => (x.getAttribute('aria-label') || '').trim() === wanted) + || nodes.find((x) => (x.innerText || '').trim() === wanted) + || nodes.find((x) => (x.getAttribute('aria-label') || x.innerText || '').trim().startsWith(wanted)); + if (!node) return false; + node.click(); + return true; + })()`); + if (!clicked && !optional) { + throw new Error(`Could not click ${JSON.stringify(needle)}\n${(await text()).slice(0, 3000)}`); + } + await delay(350); + return clicked; + }; + + const inputs = () => evaluate(`[...document.querySelectorAll('input,textarea')].map((el) => ({ + label: el.getAttribute('aria-label') || '', + value: el.value, + disabled: el.disabled, + }))`); + + const typeField = async (label, value) => { + const focused = await evaluate(`(() => { + const wanted = ${JSON.stringify(label)}; + const el = [...document.querySelectorAll('input, textarea')].find((input) => { + const name = input.getAttribute('aria-label') || ''; + return name === wanted || name.startsWith(wanted + '\\n'); + }); + if (!el) return false; + el.focus(); + el.select?.(); + el.setSelectionRange?.(0, (el.value || '').length); + return true; + })()`); + if (!focused) throw new Error(`No field ${JSON.stringify(label)}\n${(await text()).slice(0, 3000)}`); + await delay(250); + await send('Input.insertText', { text: value }, session); + await delay(350); + }; + + const state = () => evaluate('globalThis.scheduleEditorProbe ?? null'); + const wheel = async (delta) => { + await send( + 'Input.dispatchMouseEvent', + { type: 'mouseWheel', x: Math.floor(width / 2), y: Math.floor(height / 2), deltaX: 0, deltaY: delta }, + session, + ); + await delay(400); + }; + const capture = async (name) => { + const data = (await send('Page.captureScreenshot', { format: 'png' }, session)).result.data; + const file = `${name}.png`; + await writeFile(join(output, file), Buffer.from(data, 'base64')); + captures.push({ name, file, width, height }); + return file; + }; + + const load = async (query, nextWidth, nextHeight) => { + width = nextWidth; + height = nextHeight; + await send( + 'Emulation.setDeviceMetricsOverride', + { width, height, deviceScaleFactor: 1, mobile: width < 600 }, + session, + ); + const navigation = await send('Page.navigate', { url: `${origin}/?${query}` }, session); + if (navigation.error || navigation.result?.errorText) { + throw new Error(`Navigation failed: ${JSON.stringify(navigation)}`); + } + await waitFor( + () => evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"), + 'semantics placeholder', + ); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(1200); + await assertText('Add schedule'); + }; + + const checks = []; + const captures = []; + + // Material phone: invalid -> valid -> refusal -> exact record. + await load('host=material&scale=1', 390, 844); + await assertText('Future runs only; does not publish or change the workflow.'); + await assertText('Weekdays (none means every day)'); + await assertText('Enabled schedules start future runs automatically'); + await click('Save schedule'); + await delay(500); + let current = await state(); + let fields = await inputs(); + const nameField = fields.find((field) => field.label.startsWith('Name')); + const promptField = fields.find((field) => field.label.startsWith('Prompt')); + if (current?.submits !== 0) throw new Error(`Invalid form submitted: ${JSON.stringify(current)}`); + if (!nameField?.label.includes('Enter a schedule name.')) { + throw new Error(`Name error missing: ${JSON.stringify(fields)}`); + } + if (!promptField?.label.includes('Enter a prompt.')) { + throw new Error(`Prompt error missing: ${JSON.stringify(fields)}`); + } + await capture('s1-form-material-390-invalid'); + checks.push({ + check: 'invalid submit showed both field errors and sent nothing', + submits: current.submits, + fields, + }); + + await typeField('Name', 'Probe schedule'); + await typeField('Prompt', 'Summarise the release notes.'); + await click('Save schedule'); + await delay(200); + current = await state(); + if (current?.pending !== true || current?.submits !== 1) { + throw new Error(`First submit did not enter the sending state: ${JSON.stringify(current)}`); + } + await click('Saving…', true); + await delay(150); + current = await state(); + if (current?.submits !== 1) { + throw new Error(`A second submit escaped while sending: ${JSON.stringify(current)}`); + } + checks.push({ check: 'sending disabled a duplicate submit', submits: current.submits }); + + await delay(1100); + current = await state(); + fields = await inputs(); + if (current?.pending !== false || current?.records !== 0) { + throw new Error(`Refusal state drifted: ${JSON.stringify(current)}`); + } + if (current?.lastError !== 'conflict: revision 13 is stale') { + throw new Error(`Refusal was not the fixture's: ${JSON.stringify(current)}`); + } + if ( + fields.find((field) => field.label.startsWith('Name'))?.value !== 'Probe schedule' + || fields.find((field) => field.label.startsWith('Prompt'))?.value + !== 'Summarise the release notes.' + ) { + throw new Error(`Refusal lost typed values: ${JSON.stringify(fields)}`); + } + await wheel(900); + await assertText('Your draft is preserved.'); + await capture('s1-form-material-390-refusal'); + checks.push({ + check: 'refusal kept both typed values, showed the preservation copy and re-enabled the form', + lastError: current.lastError, + refusalCopy: 'Your draft is preserved.', + values: fields.map((field) => [field.label.split('\n')[0], field.value]), + }); + + await click('Save schedule'); + await waitFor(async () => (await state())?.records === 1, 'the accepted record'); + current = await state(); + deepStrictEqual(current.lastRecord, { + id: 0, + name: 'Probe schedule', + pipeline_id: 4, + version: 2, + enabled: true, + input: { prompt: 'Summarise the release notes.' }, + workspace: '/srv/research', + rule: { every: '24h', timezone: 'Europe/London' }, + notify_mode: 'auto', + }); + await delay(500); + await wheel(1400); + await capture('s1-form-material-390-record'); + checks.push({ + check: 'retry submitted the exact create record once', + submits: current.submits, + records: current.records, + record: current.lastRecord, + }); + + // Narrow phone at 2x text: labels and helpers wrap, nothing overflows. + await load('host=material&scale=2', 320, 844); + await click('Save schedule'); + await delay(600); + await capture('s1-form-material-320-2x-top'); + for (let i = 0; i < 5; i++) await wheel(600); + await capture('s1-form-material-320-2x-bottom'); + await assertText('Enabled schedules start future runs automatically'); + await assertText('Save schedule'); + checks.push({ check: '320px at 2x text kept every label and the actions', width: 320, scale: 2 }); + + // Actual Cupertino dark host, not a Material fallback. + await load('host=cupertino&brightness=dark&scale=1', 390, 844); + await assertText('Add schedule'); + await capture('s1-form-cupertino-dark-390-top'); + for (let i = 0; i < 3; i++) await wheel(600); + await capture('s1-form-cupertino-dark-390-bottom'); + await assertText('Notifications'); + checks.push({ check: 'Cupertino dark rendered the native form', host: 'cupertino', brightness: 'dark' }); + + if (pageErrors.length) throw new Error(`Page exceptions: ${JSON.stringify(pageErrors)}`); + const manifest = { + url: origin, + fixture: 'tool/schedule_editor_probe_app.dart', + output, + checks, + captures, + }; + await writeFile(join(output, 'manifest.json'), JSON.stringify(manifest, null, 2)); + console.log(JSON.stringify(manifest, null, 2)); +} finally { + ws?.close(); + chrome.kill('SIGTERM'); + await Promise.race([once(chrome, 'exit'), delay(3000)]); + server.close(); + await rm(profile, { recursive: true, force: true }); +} diff --git a/app/tool/schedule_editor_probe_app.dart b/app/tool/schedule_editor_probe_app.dart new file mode 100644 index 00000000..d65c1db8 --- /dev/null +++ b/app/tool/schedule_editor_probe_app.dart @@ -0,0 +1,170 @@ +import 'dart:convert'; +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/schedules/domain/editor/schedule_draft.dart'; +import 'package:pipelines_app/features/schedules/ui/editor/schedule_editor_form.dart'; + +/// Isolated browser fixture for the native saved-schedule form. +/// +/// flutter build web -t tool/schedule_editor_probe_app.dart +/// +/// Query: `host=cupertino`, `brightness=dark`, `scale=2`. The injected callback +/// refuses the first valid submit and accepts the retry; it never opens a +/// socket or touches a real schedule. Its counters/record are published at +/// `globalThis.scheduleEditorProbe` for the Chrome probe. +void main() => runApp(const _ProbeApp()); + +class _ProbeApp extends StatelessWidget { + const _ProbeApp(); + + @override + Widget build(BuildContext context) { + final parameters = Uri.base.queryParameters; + final cupertino = parameters['host'] == 'cupertino'; + final dark = parameters['brightness'] == 'dark'; + final scale = double.tryParse(parameters['scale'] ?? '') ?? 1.0; + Widget media(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(scale)), + child: app!, + ); + final home = _ProbeHome(cupertino: cupertino); + if (cupertino) { + return CupertinoApp( + theme: CupertinoThemeData( + brightness: dark ? Brightness.dark : Brightness.light, + ), + builder: media, + home: CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar( + middle: Text('Schedule editor probe'), + ), + child: SafeArea(child: home), + ), + ); + } + return MaterialApp( + theme: ThemeData( + brightness: dark ? Brightness.dark : Brightness.light, + platform: TargetPlatform.android, + ), + builder: media, + home: Scaffold( + appBar: AppBar(title: const Text('Schedule editor probe')), + body: SafeArea(child: home), + ), + ); + } +} + +class _Refusal implements Exception { + const _Refusal(); + + @override + String toString() => 'conflict: revision 13 is stale'; +} + +class _ProbeHome extends StatefulWidget { + const _ProbeHome({required this.cupertino}); + + final bool cupertino; + + @override + State<_ProbeHome> createState() => _ProbeHomeState(); +} + +class _ProbeHomeState extends State<_ProbeHome> { + final _draft = ScheduleDraft.create( + pipelineId: 4, + version: '2', + workspace: '/srv/research', + timezone: 'Europe/London', + ); + int _submits = 0; + int _records = 0; + bool _pending = false; + bool _refuseNext = true; + String? _lastError; + JsonMap? _lastRecord; + + @override + void initState() { + super.initState(); + _publish(); + } + + void _publish() { + globalContext.setProperty( + 'scheduleEditorProbe'.toJS, + { + 'submits': _submits, + 'records': _records, + 'pending': _pending, + 'lastError': _lastError, + 'lastRecord': _lastRecord, + }.jsify(), + ); + } + + Future _submit(JsonMap record) async { + _submits++; + _pending = true; + _publish(); + if (mounted) setState(() {}); + await Future.delayed(const Duration(milliseconds: 900)); + if (_refuseNext) { + _refuseNext = false; + _pending = false; + _lastError = 'conflict: revision 13 is stale'; + _publish(); + if (mounted) setState(() {}); + throw const _Refusal(); + } + _pending = false; + _records++; + _lastRecord = record; + _publish(); + if (mounted) setState(() {}); + } + + @override + Widget build(BuildContext context) { + final record = _lastRecord; + return SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 640), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + ScheduleEditorForm( + draft: _draft, + onSubmit: _submit, + onCancel: () {}, + ), + if (record != null) ...[ + const SizedBox(height: 24), + Text( + 'Submitted record', + style: widget.cupertino + ? CupertinoTheme.of(context).textTheme.navTitleTextStyle + : Theme.of(context).textTheme.titleMedium, + ), + const SizedBox(height: 8), + SelectableText( + const JsonEncoder.withIndent(' ').convert(record), + ), + ], + ], + ), + ), + ), + ); + } +} From 215755bb1eee1b1fc73160b6681617c39c3060d7 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 21:52:57 +0100 Subject: [PATCH 05/10] test(app): accept the Cupertino create prompt at 2x without role assumptions --- app/notes/T1-create.md | 13 +++++++++++-- app/tool/template_create_probe.dart | 28 +++++++++++++++++++++------- app/tool/template_create_probe.mjs | 13 ++++++++++--- 3 files changed, 42 insertions(+), 12 deletions(-) diff --git a/app/notes/T1-create.md b/app/notes/T1-create.md index 67668cbc..90d7561f 100644 --- a/app/notes/T1-create.md +++ b/app/notes/T1-create.md @@ -5,8 +5,17 @@ repairs when merging. Split native field/action controls from dialog state so production files remain under250lines. Added a fail-closed repository guard: an empty/malformed created detail without a positive integral pipeline identity cannot be reported as successful creation. The new regression failed before the -guard; all24 template tests pass after. Source/native capture recheck precedes -actual gallery/Settings delivery; no production definition was created. +guard; all24 template tests pass after. + +Browser acceptance now also covers Cupertino at 2x on a phone. The probe found +the prompt open and usable; its old "is the prompt open?" test required a +`role=button` Create node, which the Cupertino action row does not expose at that +scale even though the action is present and tappable. The probe now tests the +native alert-dialog surface directly and keeps the Material-only aria-disabled +check, with disabled-state coverage for Cupertino in widget tests. The probe's +own opener is now a bounded scrollable column so a long button label cannot run +past a phone viewport. No product layout change was needed: the Cupertino dialog +fits at 2x and its success capture was inspected. ## Result diff --git a/app/tool/template_create_probe.dart b/app/tool/template_create_probe.dart index 94776fda..47596931 100644 --- a/app/tool/template_create_probe.dart +++ b/app/tool/template_create_probe.dart @@ -145,10 +145,18 @@ class _ProbeHomeState extends State<_ProbeHome> { navigationBar: const CupertinoNavigationBar( middle: Text('Template create probe'), ), + // One bounded, scrollable column keeps the opener reachable at 2x text, + // where a long button label is wider than a phone viewport. child: Center( - child: CupertinoButton.filled( - onPressed: _open, - child: const Text('Create pipeline from this template'), + child: SingleChildScrollView( + padding: const EdgeInsets.all(24), + child: CupertinoButton.filled( + onPressed: _open, + child: const Text( + 'Create pipeline from this template', + textAlign: TextAlign.center, + ), + ), ), ), ); @@ -156,10 +164,16 @@ class _ProbeHomeState extends State<_ProbeHome> { return Scaffold( appBar: AppBar(title: const Text('Template create probe')), body: Center( - child: FilledButton( - key: const ValueKey('template-probe-open'), - onPressed: _open, - child: const Text('Create pipeline from this template'), + child: SingleChildScrollView( + padding: const EdgeInsets.all(24), + child: FilledButton( + key: const ValueKey('template-probe-open'), + onPressed: _open, + child: const Text( + 'Create pipeline from this template', + textAlign: TextAlign.center, + ), + ), ), ), ); diff --git a/app/tool/template_create_probe.mjs b/app/tool/template_create_probe.mjs index 14860200..06d7244c 100644 --- a/app/tool/template_create_probe.mjs +++ b/app/tool/template_create_probe.mjs @@ -178,7 +178,14 @@ try { await delay(400); }; - // Null while the prompt is closed; true/false is the Create button's state. + // The prompt is open as soon as its native alert-dialog surface exists. The + // Create action's button role/aria-disabled is host- and scale-dependent on + // the web semantics layer, so the disabled state is asserted module-side for + // Material and by widget tests for Cupertino. + const promptOpen = () => + evaluate("Boolean(document.querySelector('[role=alertdialog]'))"); + + // Null unless a Material Create button exposes its disabled state. const createDisabled = () => evaluate(`(() => { const el = [...document.querySelectorAll('flt-semantics')].find( @@ -232,7 +239,7 @@ try { await assertBody('Create pipeline from this template'); await clickLabel('Create pipeline from this template'); - await waitFor(() => createDisabled().then((value) => value !== null), 'the create prompt'); + await waitFor(promptOpen, 'the create prompt'); await assertBody('Create from Release workflow'); await assertBody('New pipeline name (required)'); await assertBody("Creates a new draft pipeline on the server from this template's source; it is not run."); @@ -301,7 +308,7 @@ try { }); await clickLabel('Close'); - await waitFor(async () => (await createDisabled()) === null, 'the prompt to close'); + await waitFor(async () => !(await promptOpen()), 'the prompt to close'); checks.push({ check: 'Close dismissed the prompt without another request', state: await state(), From 475e1ae5081d4158a4ccf58bf23e370e598ef431 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 21:53:55 +0100 Subject: [PATCH 06/10] docs(app): record landed state for the schedule editor form --- app/notes/S1-form.md | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/app/notes/S1-form.md b/app/notes/S1-form.md index 07dd36dd..db4bccd6 100644 --- a/app/notes/S1-form.md +++ b/app/notes/S1-form.md @@ -102,7 +102,8 @@ dart format lib/features/schedules/ui/editor test/features/schedules/ui/editor \ tool/schedule_editor_probe_app.dart # clean flutter analyze # No issues found! flutter test test/features/schedules # 69 passed -flutter test # 686 passed +flutter test # 686 passed before the + # main merge, 687 after flutter build web # ✓ Built build/web flutter build web -t tool/schedule_editor_probe_app.dart \ -o build/schedule_editor_probe_web # ✓ Built @@ -111,6 +112,11 @@ OPENCODE_ARTIFACT_DIR=…/78/public/s1-form-captures \ node tool/schedule_editor_probe.mjs # all checks passed ``` +After merging `main` into `flutter/schedule-form` (conflict-free; the incoming +commit only touches templates), the same checks were re-run on the merged tree: +`flutter analyze` clean, 69 schedules tests, 687 whole-app tests, `flutter build +web`, and all six fixture probe checks with no page errors. + Browser checks that actually ran in real headless Chrome against the fixture: - blank submit: 0 callbacks, both field errors exposed; @@ -147,15 +153,18 @@ The refusal copy is visible in ## Full diff -Every path is new and currently untracked; `git status --short` lists only those -paths and no existing file is modified. The complete patch is saved at: +Every path is new; no existing file is modified. The reviewed patch is committed +as `feat(app): add native saved-schedule editor form` on +`flutter/schedule-form`, followed by a conflict-free merge of `main`. The +complete patch is also saved at: `/Users/alan/.local/share/pipelines/data/artifacts/78/public/s1-form.diff` ## Honest limits -- **Not committed, pushed or deployed.** This stage forbids that. The candidate - is in the `flutter/schedule-form` worktree for the manager. +- **Committed but not deployed.** The candidate commit is merged with `main` and + checked on `flutter/schedule-form`; no push, deployment or canonical URL + change was performed by this work. - **Not wired into the normal Schedules screen or shell.** There is no editor dialog/route, no `screen.dart` integration and no navigation; the Schedules destination's editor entry is a later integration slice. From f9db64a916e1749cf8f120523cef82baf45566fe Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 21:56:41 +0100 Subject: [PATCH 07/10] docs(app): record merged schedule form checks --- app/notes/S1-form.md | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/app/notes/S1-form.md b/app/notes/S1-form.md index db4bccd6..6ed7eafa 100644 --- a/app/notes/S1-form.md +++ b/app/notes/S1-form.md @@ -102,8 +102,8 @@ dart format lib/features/schedules/ui/editor test/features/schedules/ui/editor \ tool/schedule_editor_probe_app.dart # clean flutter analyze # No issues found! flutter test test/features/schedules # 69 passed -flutter test # 686 passed before the - # main merge, 687 after +flutter test # 686 before merging main; + # 704 on the merged tree flutter build web # ✓ Built build/web flutter build web -t tool/schedule_editor_probe_app.dart \ -o build/schedule_editor_probe_web # ✓ Built @@ -112,10 +112,11 @@ OPENCODE_ARTIFACT_DIR=…/78/public/s1-form-captures \ node tool/schedule_editor_probe.mjs # all checks passed ``` -After merging `main` into `flutter/schedule-form` (conflict-free; the incoming -commit only touches templates), the same checks were re-run on the merged tree: -`flutter analyze` clean, 69 schedules tests, 687 whole-app tests, `flutter build -web`, and all six fixture probe checks with no page errors. +After merging the current `main` into `flutter/schedule-form` (conflict-free; +the incoming work was unrelated template and chat-composer state changes), the +same checks were re-run on the merged tree: `flutter analyze` clean, 69 schedules +tests, 704 whole-app tests, `flutter build web`, and all six fixture probe checks +with no page errors. Browser checks that actually ran in real headless Chrome against the fixture: From ca9e42e08032493f6897e3220532ae0ce79cecc5 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 21:57:03 +0100 Subject: [PATCH 08/10] docs(app): clarify reviewed patch snapshot in schedule form notes --- app/notes/S1-form.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/notes/S1-form.md b/app/notes/S1-form.md index 6ed7eafa..ac572fbc 100644 --- a/app/notes/S1-form.md +++ b/app/notes/S1-form.md @@ -157,7 +157,8 @@ The refusal copy is visible in Every path is new; no existing file is modified. The reviewed patch is committed as `feat(app): add native saved-schedule editor form` on `flutter/schedule-form`, followed by a conflict-free merge of `main`. The -complete patch is also saved at: +reviewed patch snapshot, taken before these landing-state note edits, is saved +at: `/Users/alan/.local/share/pipelines/data/artifacts/78/public/s1-form.diff` From 365e72c22a5d474a737557d1ba993a88f6ba26f7 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 21:57:10 +0100 Subject: [PATCH 09/10] docs(app): record recovered landings and current port inventory --- app/PARITY.md | 16 +++++++------- app/WORK.md | 60 +++++++++++++++++++++++++++++++++++++++++++++------ 2 files changed, 62 insertions(+), 14 deletions(-) diff --git a/app/PARITY.md b/app/PARITY.md index a9e3a727..e27822da 100644 --- a/app/PARITY.md +++ b/app/PARITY.md @@ -26,31 +26,31 @@ or scratch servers only, never real operator sessions/runs/workflows. | Pipeline list/filter/sort/detail/source/versions | Preview | latest summary metadata/miniatures, pinned detail URLs | | Definition graph | Source nodes/layout/routes/edges; active canvas71 | compose measured native nodes+labels, graph tab, pan/zoom, expanded view, definition stage pane | | Start a pipeline | Missing | native prompt/workspace/notify dialog, exact pinned run request, response-loss intent | -| Templates | Source repository; active create dialog73 | gallery/detail/source, Settings entry, validate/create-only dialog integration and refresh | +| Templates | Source repository/create prompt + active gallery76 | Set