Merge branch 'main' into flutter/templates-gallery
This commit is contained in:
+8
-8
@@ -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<template> native gallery/detail/source, Settings/templates entry, create refresh into list |
|
||||
| Runs list/filter/sort/live fold | Preview | full time/status/provenance filters, recency/day groups, shell live/attention state |
|
||||
| Run detail/input/output/copy/metrics | Preview | latest summary tabs/fields and exact empty/unknown states |
|
||||
| Rename run | Preview | verified exact accepted title fold; no live production mutation tested |
|
||||
| Cancel run | Preview | exact confirm/server-accepted detail+list fold; production cancellation not tested |
|
||||
| Retry/restart | Source actions/dialogs | actual detail controls, accepted new-run navigation, stale/refusal handling |
|
||||
| Human decisions | Preview waiting card/native prompt/exact accepted reply | attention/action URL entry; no production decision answered during tests |
|
||||
| Run graph | Source projection/visits | executed/unvisited routes, live activity, graph clicks open latest RECORDED visit, no definition by default |
|
||||
| Timeline/recorded visit pane | Preview text rows only | visit selection, status/outcome/duration/model/target/verdict, artifacts/session/input/output/definition tabs |
|
||||
| Changes/diffs | Source; active detail wiring67 | settled-run aggregate gate, per-visit capture, paging/raw/rendered/copy and keyboard/back routes |
|
||||
| Run graph | Source projection/visits; definition canvas landed | executed/unvisited routes, live activity, graph clicks open latest RECORDED visit, no definition by default |
|
||||
| Timeline/recorded visit pane | Preview text rows only; authored pane77 | visit selection, status/outcome/duration/model/target/verdict, artifacts/session/input/output/definition tabs |
|
||||
| Changes/diffs | Preview via run detail | settled-run aggregate gate rechecked in shell; per-visit capture entry still separate |
|
||||
| Artifact groups | Source model/list | actual visit/run gallery integration and truthful unavailable capture facts |
|
||||
| Artifact preview | Missing | image-primary in-app viewer, video/doc/text/markdown, paging, focus/back, authenticated fetch errors |
|
||||
| Artifact actions | Source safe URL resolution | separate external-open/copy/download; SHARE REAL NAMED MIME FILES, not links; slow activation/cancel/errors |
|
||||
| Session audit/export repair facts | Missing UI | session.html read-only open, partial/missing/skipped/repair choices without fabricating complete evidence |
|
||||
| Chat session management | Source | normal Chat destination, directory groups/history/search, shared rename/star/close/reopen/create, local hide/undo/seen state |
|
||||
| Chat history/live transport | Source controller72 + pure fold | integrate authoritative reconnect/paging/live-failure status and stable session navigation |
|
||||
| Chat message surfaces | Active native body70 | integrate thread, markdown (safe links/headings/lists/tables/fences), exact attachments and unknown-part retention |
|
||||
| Chat history/live transport | Source controller72; active live screen79 | authoritative reconnect/paging/live-failure status and stable session navigation in the shell |
|
||||
| Chat message surfaces | Source native body70; integrating in79 | markdown (safe links/headings/lists/tables/fences), exact attachments and unknown-part retention |
|
||||
| Chat activity/reasoning/tools | Source raw fields only | one activity line, compaction, native reasoning/tools overlays, lifecycle/input/output/error/duration/edit diff |
|
||||
| Chat composer | Missing | per-chat persisted drafts, Enter newline/Ctrl-Cmd+Enter send, Send beside Stop, optimistic identity, queued/refused restore |
|
||||
| Chat composer | Source controller75 | native composer UI, Enter newline/Ctrl-Cmd+Enter send, Send beside Stop, optimistic identity display |
|
||||
| Chat attachments | Source request facade | picker/paste, latest1MiB total wire bound, base64 files, removable named chips, exact history reconciliation |
|
||||
| Chat permissions/questions | Source request facade | native approval/risk cards and form option/free-text answers; pending/resolved/stale/error states |
|
||||
| Chat model/Info/background tasks | Source request facade | current-model selection, numeric Info modal (unknown !=0), bounded running shell pages |
|
||||
| Chat commands/notices/scroll | Missing | slash palette/actions, unknown-command send-as-message, dismissible local notices, saved scroll/follow intent |
|
||||
| Saved schedule list | Source | pipeline entry and route registration, exact timer provenance vocabulary |
|
||||
| Schedule editor | Source lossless draft74 + identity/CAS guard | native fields, stable create key, edit/pause/delete, conflict keeps draft, Schedule this run seed |
|
||||
| Schedule editor | Source draft74+CAS guard; active form78 | save/pause/delete wiring, conflict keeps draft, Schedule this run seed |
|
||||
| Search | Source screen | shell entry, close/focus/selection retention, exact pipeline/version/run/field/visit/artifact target routing |
|
||||
| Needs you | Missing | derived failed/waiting counts, native list/sheet, open/dismiss/clear snapshot, persisted identities |
|
||||
| Notifications | Missing | explicit permission/rationale, secure/unsupported/denied states, transition-only dedupe, background question notices |
|
||||
|
||||
+54
-6
@@ -34,14 +34,20 @@ All work under app/. Existing applications remain running and unchanged.
|
||||
| P2-node | One native content-sized stage-node button | run64 /e63b0115 | manager inspected126-line native control + final PNG;13 focused tests pass;61min MISSED20min target | merged main; ancestry verified | graph composition pending |
|
||||
| P2-edge | Passive routed-edge paint layer ONLY | run66 /835f16c | manager inspected160-line source + actual light PNG, reran38 painting/routing tests, pass; actual48min MISSED20min target | merged main; ancestry verified | graph composition pending |
|
||||
| A1-list | One read-only artifact visit-group list | run65 /596365d9 | manager inspected231-line source + dark Cupertino PNG;11 focused tests pass;59min MISSED20min target | merged main; ancestry verified | run-detail wiring/preview pending |
|
||||
| D1-wire | Open existing ChangesViewer from run detail | run67 /flutter/d1-wire | Task v6 Flash; one native button/recorded-steps route, no viewer rewrite | running | pending |
|
||||
| D1-wire | Open existing ChangesViewer from run detail | run67 retained + manager77c71eb | stage review limit reached; manager finished retained work,15 browser checks/20 captures incl320px2x native menus | merged main; ancestry verified | published with run detail |
|
||||
| R2-title-wire | Existing Rename action into detail/controller | run68 /3d3ee3a3 |19min total MET target; manager reviewed source/server-reply fold, focused tests + normal-app browser7 captures pass | merged main; ancestry verified | published8096 with Runs/Settings |
|
||||
| P1-wire | Register pipeline browser in actual app shell | run69 /8476cfd7 | manager reviewed, focused tests;599 integrated tests + actual app browser25 checks/9 PNGs pass;27min missed20min target | merged main; ancestry verified | published8096 |
|
||||
| C2-message | Native chat message body | run70 /flutter/chat-messages | pure native text/unknown-part disclosure, no network; focused tests/captures required | running | component first |
|
||||
| P2-canvas | Measured definition graph composition | run71 /flutter/graph-canvas | existing node/layout/routes/edge layer, actual measurements, no invented visits | running | graph hook next |
|
||||
| C2-thread | Chat paging/live controller | run72 /flutter/chat-thread | existing repository/fold, opaque cursors and reconnect; no UI/network ownership changes | running | conversation integration next |
|
||||
| T1-create | Native template create-only dialog | run73 /flutter/template-create | validate before submit, no production authoring; no gallery scope | running | gallery integration next |
|
||||
| S1-draft | Lossless schedule editor draft | run74 /flutter/schedule-draft | pure validation/CAS-preserving copy; no CRUD/timer engine | running | editor next |
|
||||
| C2-message | Native chat message body | run70 /9e4a9255 + manager2088d46 | manager preserved unknown user parts and removed forced weight; focused transcript tests pass | merged main | component; chat screen79 wiring |
|
||||
| P2-canvas | Measured definition graph composition | run71 retained/bf378c9 | deadline recovery; manager removed fixed node bound, measured label gaps, fixed labels crossing wires; graph+paint tests pass | merged main; ancestry verified | definition canvas only; pipeline hook next |
|
||||
| C2-thread | Chat paging/live controller | run72 /76437db0 + managerc970aa5 | manager exposed refused live watch separately;13min; focused tests pass | merged main | conversation integration79 |
|
||||
| T1-create | Native create-only template dialog | run73 /e69883b5 + manager37332a3,215755b | manager split controls, fail-closed created identity, Cupertino2x probe fixed;24 tests + both-host browser pass | merged main; ancestry verified | gallery76 wiring next |
|
||||
| S1-draft | Lossless schedule editor draft | run74 /914866f6 + manager87220fe |17min; manager added identity/CAS fail-closed guard after original draft would accept invalid identity | merged main; ancestry verified | native form78 next |
|
||||
| C3-state | Chat draft/send/stop controller | run75 /565cdaa |10min MET target; manager reviewed per-chat persistence, stable intent id, refusal restore, queued flag | merged main; ancestry verified | composer UI next |
|
||||
| C3-form | Native composer control | run? pending | drafts/send/stop UI atop75 | queued | pending |
|
||||
| Chat screen | Live Chat destination + read-only history | run79 /flutter/chat-live-screen | list/detail routing, paging, live one-thread, reconnect | running | pending |
|
||||
| Templates gallery | Native template gallery/detail | run76 /flutter/templates-gallery | actual catalogue/source + create prompt forwarding | running | pending |
|
||||
| Stage definition | Native authored stage pane | run77 /flutter/stage-definition | pinned definition identity, outcomes/tools/raw unknown | running | pending |
|
||||
| Schedule form | Native schedule draft editor | run78 /flutter/schedule-form | binds74, no save engine | running | pending |
|
||||
|
||||
## Next ready work
|
||||
### Current execution target (user correction)
|
||||
@@ -94,6 +100,48 @@ The user directs continued work until the whole client is ported, not just
|
||||
components. app/PARITY.md now enumerates the entire remaining behavior inventory
|
||||
against latest web behavior, distinguishing preview/source/active/missing.
|
||||
|
||||
Latest batch: two pipeline runs needed direct recovery, not replacement work.
|
||||
67 Changes wiring had completed its fixes but exhausted its Review visit limit;
|
||||
71 graph canvas hit the Code deadline while collecting evidence. In both cases the
|
||||
agents were settled and the retained edits were finished by the manager.
|
||||
|
||||
- Changes wiring now opens the landed viewer from real run detail and switches to
|
||||
a native action sheet/bottom sheet when scaled segment labels cannot fit. The
|
||||
previously hard-coded measurement font was replaced with the host's real label
|
||||
style. Rebuilt fixture:15 checks/20 captures, approved temp/
|
||||
changes-wiring-manager-browser; 320px/2x Material and Cupertino menus inspected.
|
||||
- Graph canvas no longer imposes a fixed node width or a guessed 2x rank gap; it
|
||||
measures real native nodes/labels and derives spacing from those extents. New
|
||||
resize regression plus the existing geometry suites pass. Browser inspection
|
||||
found an outcome label sitting across its own loop wire; three failing pure
|
||||
regressions were added first, then label placement was made wire-aware. Real
|
||||
Chrome cases Material light1x/2x and Cupertino light1x/dark2x each produced 5
|
||||
captures under approved temp/graph-canvas-manager-browser.
|
||||
- Chat thread exposed a refused live watch separately from readable history; the
|
||||
focused regression covers refusal then successful resync.
|
||||
- Chat message rows keep unknown user parts behind a native disclosure and no
|
||||
longer force a role font weight.
|
||||
- Template create gained a fail-closed created-identity guard, split native
|
||||
controls out of the dialog, and fixed the probe so a Cupertino 2x phone prompt
|
||||
is judged by its alert-dialog surface rather than a role assumption. Both hosts
|
||||
pass; the accepted 2x Cupertino capture was inspected. No product layout change
|
||||
was needed.
|
||||
- Schedule draft now refuses to build a save payload when the pipeline identity or
|
||||
an edited record's id/revision is invalid, closing a create-vs-update hazard.
|
||||
|
||||
Integrated main after these landings:694 tests pass; analysis clean; normal web
|
||||
build passed; the extended normal-app browser fixture passed28 captures. Published
|
||||
that verified bundle with no service restart: rollback
|
||||
build/web-before-port-1792616193, JS SHA256
|
||||
770cc339b4c3f357dc9aeb5c23e73f4992cbb3892675a2d9963af4b02ff3b7da; unauthenticated
|
||||
asset access still401. Authenticated production interactions and mobile remain
|
||||
unverified.
|
||||
|
||||
Runs still active:79 live Chat destination,76 templates gallery,77 authored stage
|
||||
pane,78 schedule form. Next queued wiring after those: composer UI on75, artifact
|
||||
gallery/viewer, retry, search shell entry, attention/notifications, then the final
|
||||
Android build.
|
||||
|
||||
Pipeline browser69 landed and was tested against the normal app build in real
|
||||
Chrome:25 checks/9 PNGs, actual dark Cupertino detail inspected; existing Runs/
|
||||
Settings regression20 captures pass. Published without service restart; previous
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../data/chat_repository.dart';
|
||||
import 'chat_draft_store.dart';
|
||||
|
||||
/// One plain-message send: the optimistic identity the thread shows and the
|
||||
/// exact wire intent. A lost response retries the same intent with these ids.
|
||||
class ChatComposerSend {
|
||||
const ChatComposerSend({
|
||||
required this.sessionId,
|
||||
required this.text,
|
||||
required this.operationId,
|
||||
required this.nativeMessageId,
|
||||
});
|
||||
|
||||
final String sessionId;
|
||||
|
||||
/// The trimmed wire text.
|
||||
final String text;
|
||||
final String operationId;
|
||||
final String nativeMessageId;
|
||||
|
||||
/// Mirrors the web's `nativeChatMessageId(operationId) || local-<operationId>`.
|
||||
String get optimisticId =>
|
||||
nativeMessageId.isEmpty ? 'local-$operationId' : nativeMessageId;
|
||||
}
|
||||
|
||||
typedef ChatSendCallback = void Function(ChatComposerSend send);
|
||||
typedef ChatSendRejected = void Function(ChatComposerSend send, String error);
|
||||
|
||||
/// The composer state for one conversation: exact draft, the one plain prompt
|
||||
/// in flight, the reply's queued flag and Stop. It is not a transcript:
|
||||
/// [onOptimistic] and [onRejected] are the thread's seam; Stop settles nothing.
|
||||
class ChatComposerController extends ChangeNotifier {
|
||||
ChatComposerController(
|
||||
this.gateway,
|
||||
this.sessionId, {
|
||||
ChatDraftStore? drafts,
|
||||
this.onOptimistic,
|
||||
this.onRejected,
|
||||
this.newOperationId,
|
||||
}) : _drafts = drafts ?? const SharedPreferencesChatDraftStore() {
|
||||
_subscription = gateway.frames.listen(_onFrame);
|
||||
}
|
||||
|
||||
final ApiGateway gateway;
|
||||
final String sessionId;
|
||||
final ChatSendCallback? onOptimistic;
|
||||
final ChatSendRejected? onRejected;
|
||||
final ChatDraftStore _drafts;
|
||||
|
||||
/// Test/fixture seam; production mints a unique id per new intent.
|
||||
final String Function()? newOperationId;
|
||||
late final ChatRepository _repository = ChatRepository(gateway);
|
||||
StreamSubscription<JsonMap>? _subscription;
|
||||
|
||||
static const String draftSaveFailed =
|
||||
'This draft could not be saved on this device.';
|
||||
|
||||
String _draft = '';
|
||||
bool _edited = false;
|
||||
bool _sending = false;
|
||||
bool _stopping = false;
|
||||
bool _queued = false;
|
||||
String? _error;
|
||||
String? _draftError;
|
||||
int _operationSeq = 0;
|
||||
int _loadGeneration = 0;
|
||||
Future<void> _writes = Future<void>.value();
|
||||
ChatComposerSend? _pending;
|
||||
bool _disposed = false;
|
||||
|
||||
/// The exact text in the composer. A refusal restores it only when the
|
||||
/// operator has not typed anything newer.
|
||||
String get draft => _draft;
|
||||
|
||||
/// One prompt request is awaiting its reply; a second send is refused.
|
||||
bool get sending => _sending;
|
||||
|
||||
/// One `chat_interrupt` is awaiting its reply.
|
||||
bool get stopping => _stopping;
|
||||
|
||||
/// The reply said the prompt waits behind the in-flight turn.
|
||||
bool get queued => _queued;
|
||||
|
||||
/// The last send or Stop refusal, kept visible until the next action.
|
||||
String? get error => _error;
|
||||
|
||||
/// Set when the draft could not be persisted; in-memory text still holds.
|
||||
String? get draftError => _draftError;
|
||||
|
||||
/// Reads this session's saved draft. Text typed while the read is pending
|
||||
/// wins, so a slow store can never replace the operator's newer typing.
|
||||
Future<void> loadDraft() async {
|
||||
if (_disposed) return;
|
||||
final generation = ++_loadGeneration;
|
||||
var saved = '';
|
||||
try {
|
||||
saved = await _drafts.read(sessionId);
|
||||
} catch (_) {
|
||||
saved = '';
|
||||
}
|
||||
if (_disposed || _edited || generation != _loadGeneration) return;
|
||||
if (saved == _draft) return;
|
||||
_draft = saved;
|
||||
_notify();
|
||||
}
|
||||
|
||||
/// Updates the draft exactly as typed and persists it. A save failure leaves
|
||||
/// the in-memory draft untouched and sets [draftError].
|
||||
Future<void> setDraft(String text) {
|
||||
if (_disposed || text == _draft) return Future<void>.value();
|
||||
_draft = text;
|
||||
_edited = true;
|
||||
_draftError = null;
|
||||
_notify();
|
||||
return _persistDraft(text);
|
||||
}
|
||||
|
||||
/// Sends the non-blank draft as one plain message. Only the wire text is
|
||||
/// trimmed. A refused unchanged intent reuses its operation id; a refusal
|
||||
/// restores the exact draft unless newer text is already present.
|
||||
Future<void> send() async {
|
||||
if (_disposed || _sending) return;
|
||||
final exact = _draft;
|
||||
final text = exact.trim();
|
||||
if (text.isEmpty) return;
|
||||
final previous = _pending;
|
||||
late final ChatComposerSend intent;
|
||||
if (previous != null && previous.text == text) {
|
||||
intent = previous;
|
||||
} else {
|
||||
final operationId = _nextOperationId();
|
||||
intent = ChatComposerSend(
|
||||
sessionId: sessionId,
|
||||
text: text,
|
||||
operationId: operationId,
|
||||
nativeMessageId: nativeChatMessageId(operationId),
|
||||
);
|
||||
}
|
||||
_pending = intent;
|
||||
_sending = true;
|
||||
_error = null;
|
||||
_draft = '';
|
||||
_edited = true;
|
||||
_notify();
|
||||
await _persistDraft('');
|
||||
if (_disposed) return;
|
||||
onOptimistic?.call(intent);
|
||||
try {
|
||||
final reply = await _repository.prompt(
|
||||
sessionId,
|
||||
text,
|
||||
operationId: intent.operationId,
|
||||
);
|
||||
if (_disposed) return;
|
||||
_queued = reply['chat_queued'] == true;
|
||||
_pending = null;
|
||||
_sending = false;
|
||||
_error = null;
|
||||
_notify();
|
||||
} catch (error) {
|
||||
if (_disposed) return;
|
||||
final message = '$error';
|
||||
_sending = false;
|
||||
_error = message;
|
||||
if (_draft.isEmpty) {
|
||||
_draft = exact;
|
||||
_edited = true;
|
||||
_notify();
|
||||
await _persistDraft(exact);
|
||||
if (_disposed) return;
|
||||
}
|
||||
onRejected?.call(intent, message);
|
||||
_notify();
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops the running turn with the exact `chat_interrupt` query. A failure
|
||||
/// stays visible and settles nothing; only a reply or frame changes state.
|
||||
Future<void> stop() async {
|
||||
if (_disposed || _stopping) return;
|
||||
_stopping = true;
|
||||
_error = null;
|
||||
_notify();
|
||||
try {
|
||||
await _repository.interrupt(sessionId);
|
||||
} catch (error) {
|
||||
if (!_disposed) _error = '$error';
|
||||
} finally {
|
||||
if (!_disposed) {
|
||||
_stopping = false;
|
||||
_notify();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _onFrame(JsonMap envelope) {
|
||||
if (_disposed || !_queued) return;
|
||||
if (envelope['type'] != 'chat_event') return;
|
||||
final body = envelope['chat_event'];
|
||||
if (body is! Map || body['session_id'] != sessionId) return;
|
||||
// Usage or compaction does not admit a queued prompt; any other frame for
|
||||
// this session means the turn it waited behind moved on (web parity).
|
||||
final kind = body['kind'];
|
||||
if (kind == 'usage' || kind == 'compaction') return;
|
||||
_queued = false;
|
||||
_notify();
|
||||
}
|
||||
|
||||
String _nextOperationId() =>
|
||||
newOperationId?.call() ??
|
||||
'native-chat-${DateTime.now().microsecondsSinceEpoch}-${_operationSeq++}';
|
||||
|
||||
Future<void> _persistDraft(String text) {
|
||||
final write = _writes.then((_) async {
|
||||
var stored = false;
|
||||
try {
|
||||
stored = await _drafts.write(sessionId, text);
|
||||
} catch (_) {
|
||||
stored = false;
|
||||
}
|
||||
if (_disposed || text != _draft) return;
|
||||
final failure = stored ? null : draftSaveFailed;
|
||||
if (failure != _draftError) {
|
||||
_draftError = failure;
|
||||
_notify();
|
||||
}
|
||||
});
|
||||
_writes = write;
|
||||
return write;
|
||||
}
|
||||
|
||||
void _notify() {
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_loadGeneration++;
|
||||
unawaited(_subscription?.cancel());
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
/// One conversation's persisted composer draft, keyed by session id.
|
||||
///
|
||||
/// The draft is stored exactly as typed (untrimmed); only the wire copy is
|
||||
/// trimmed. Attachments are intentionally absent: a file handle cannot be
|
||||
/// serialised, and the web build keeps them memory-only too.
|
||||
abstract interface class ChatDraftStore {
|
||||
/// The saved draft, or an empty string when there is none or the store is
|
||||
/// unavailable. Implementations may throw; the controller treats that as
|
||||
/// "nothing saved" and keeps its in-memory draft.
|
||||
Future<String> read(String sessionId);
|
||||
|
||||
/// Stores [text] exactly. A blank draft removes the entry so the store does
|
||||
/// not grow without bound. Returns false when nothing was stored.
|
||||
Future<bool> write(String sessionId, String text);
|
||||
}
|
||||
|
||||
/// The app's per-session draft keys. Independent of the legacy web/Android
|
||||
/// storage: no old draft is imported or written under an old key.
|
||||
const String chatDraftKeyPrefix = 'pipelines.next.chatDraft.v1.';
|
||||
|
||||
/// `shared_preferences`-backed draft storage.
|
||||
///
|
||||
/// Reads are tolerant and a write reports failure instead of throwing, so the
|
||||
/// composer can keep the in-memory draft and say plainly that it was not saved.
|
||||
class SharedPreferencesChatDraftStore implements ChatDraftStore {
|
||||
const SharedPreferencesChatDraftStore();
|
||||
|
||||
Future<SharedPreferences?> _preferences() async {
|
||||
try {
|
||||
return await SharedPreferences.getInstance();
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<String> read(String sessionId) async {
|
||||
final preferences = await _preferences();
|
||||
if (preferences == null) return '';
|
||||
try {
|
||||
return preferences.getString('$chatDraftKeyPrefix$sessionId') ?? '';
|
||||
} catch (_) {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> write(String sessionId, String text) async {
|
||||
final preferences = await _preferences();
|
||||
if (preferences == null) return false;
|
||||
try {
|
||||
final key = '$chatDraftKeyPrefix$sessionId';
|
||||
if (text.isEmpty) return await preferences.remove(key);
|
||||
return await preferences.setString(key, text);
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An in-memory store for tests and previews. It never touches the platform
|
||||
/// store, so no production preference can be mutated by a fixture.
|
||||
class MemoryChatDraftStore implements ChatDraftStore {
|
||||
MemoryChatDraftStore({Map<String, String>? drafts}) : _drafts = {...?drafts};
|
||||
|
||||
final Map<String, String> _drafts;
|
||||
bool failReads = false;
|
||||
bool failWrites = false;
|
||||
|
||||
/// A snapshot of the stored entries, so a test can tell a removed key from an
|
||||
/// empty string.
|
||||
Map<String, String> get entries => Map.unmodifiable(_drafts);
|
||||
|
||||
@override
|
||||
Future<String> read(String sessionId) async {
|
||||
if (failReads) throw StateError('Draft storage is unavailable.');
|
||||
return _drafts[sessionId] ?? '';
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> write(String sessionId, String text) async {
|
||||
if (failWrites) return false;
|
||||
if (text.isEmpty) {
|
||||
_drafts.remove(sessionId);
|
||||
} else {
|
||||
_drafts[sessionId] = text;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../../ui/adaptive/host.dart';
|
||||
|
||||
/// Secondary text under a field, using the host's own colours and text theme.
|
||||
TextStyle scheduleEditorSecondaryStyle(BuildContext context) {
|
||||
if (usesCupertinoHost(context)) {
|
||||
return CupertinoTheme.of(context).textTheme.textStyle.copyWith(
|
||||
fontSize: 14,
|
||||
color: CupertinoColors.secondaryLabel.resolveFrom(context),
|
||||
);
|
||||
}
|
||||
final theme = Theme.of(context);
|
||||
return (theme.textTheme.bodySmall ?? const TextStyle()).copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
);
|
||||
}
|
||||
|
||||
/// The host's semantic error colour, never a form-specific palette.
|
||||
TextStyle scheduleEditorErrorStyle(BuildContext context) {
|
||||
if (usesCupertinoHost(context)) {
|
||||
return CupertinoTheme.of(context).textTheme.textStyle.copyWith(
|
||||
color: CupertinoColors.systemRed.resolveFrom(context),
|
||||
);
|
||||
}
|
||||
return TextStyle(color: Theme.of(context).colorScheme.error);
|
||||
}
|
||||
|
||||
/// A wrapping label above its control, with optional helper and field error.
|
||||
///
|
||||
/// The browser puts the label in a sibling span, so a native floating label
|
||||
/// would invent different words and truncate at large text sizes.
|
||||
class ScheduleEditorField extends StatelessWidget {
|
||||
const ScheduleEditorField({
|
||||
super.key,
|
||||
required this.label,
|
||||
required this.child,
|
||||
this.helper,
|
||||
this.error,
|
||||
});
|
||||
|
||||
final String label;
|
||||
final Widget child;
|
||||
final String? helper;
|
||||
final String? error;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final labelStyle = usesCupertinoHost(context)
|
||||
? CupertinoTheme.of(context).textTheme.textStyle
|
||||
: Theme.of(context).textTheme.bodyMedium;
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(label, style: labelStyle),
|
||||
const SizedBox(height: 6),
|
||||
child,
|
||||
if (helper case final text?)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: Text(text, style: scheduleEditorSecondaryStyle(context)),
|
||||
),
|
||||
if (error case final text?)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: Text(text, style: scheduleEditorErrorStyle(context)),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// One-line or multiline text input in the host's native field style.
|
||||
class ScheduleEditorTextField extends StatelessWidget {
|
||||
const ScheduleEditorTextField({
|
||||
super.key,
|
||||
required this.label,
|
||||
required this.controller,
|
||||
required this.onChanged,
|
||||
this.fieldKey,
|
||||
this.keyboardType,
|
||||
this.minLines = 1,
|
||||
this.maxLines = 1,
|
||||
this.enabled = true,
|
||||
this.helper,
|
||||
this.error,
|
||||
this.textInputAction,
|
||||
});
|
||||
|
||||
final String label;
|
||||
final TextEditingController controller;
|
||||
final ValueChanged<String> onChanged;
|
||||
final Key? fieldKey;
|
||||
final TextInputType? keyboardType;
|
||||
final int? minLines;
|
||||
final int? maxLines;
|
||||
final bool enabled;
|
||||
final String? helper;
|
||||
final String? error;
|
||||
final TextInputAction? textInputAction;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final field = usesCupertinoHost(context)
|
||||
? CupertinoTextField(
|
||||
key: fieldKey,
|
||||
controller: controller,
|
||||
enabled: enabled,
|
||||
keyboardType: keyboardType,
|
||||
minLines: minLines,
|
||||
maxLines: maxLines,
|
||||
textInputAction: textInputAction,
|
||||
onChanged: onChanged,
|
||||
)
|
||||
: TextField(
|
||||
key: fieldKey,
|
||||
controller: controller,
|
||||
enabled: enabled,
|
||||
keyboardType: keyboardType,
|
||||
minLines: minLines,
|
||||
maxLines: maxLines,
|
||||
textInputAction: textInputAction,
|
||||
onChanged: onChanged,
|
||||
);
|
||||
return MergeSemantics(
|
||||
child: ScheduleEditorField(
|
||||
label: label,
|
||||
helper: helper,
|
||||
error: error,
|
||||
child: field,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A native switch with a wrapping label and an explanatory helper.
|
||||
class ScheduleEditorSwitchField extends StatelessWidget {
|
||||
const ScheduleEditorSwitchField({
|
||||
super.key,
|
||||
required this.label,
|
||||
required this.value,
|
||||
required this.onChanged,
|
||||
this.helper,
|
||||
this.enabled = true,
|
||||
this.switchKey,
|
||||
});
|
||||
|
||||
final String label;
|
||||
final bool value;
|
||||
final ValueChanged<bool> onChanged;
|
||||
final String? helper;
|
||||
final bool enabled;
|
||||
final Key? switchKey;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final control = usesCupertinoHost(context)
|
||||
? CupertinoSwitch(
|
||||
key: switchKey,
|
||||
value: value,
|
||||
onChanged: enabled ? onChanged : null,
|
||||
)
|
||||
: Switch(
|
||||
key: switchKey,
|
||||
value: value,
|
||||
onChanged: enabled ? onChanged : null,
|
||||
);
|
||||
return MergeSemantics(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(child: Text(label)),
|
||||
const SizedBox(width: 12),
|
||||
control,
|
||||
],
|
||||
),
|
||||
if (helper case final text?)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: Text(text, style: scheduleEditorSecondaryStyle(context)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../../core/api_gateway.dart';
|
||||
import '../../../../ui/adaptive/host.dart';
|
||||
import '../../domain/editor/schedule_draft.dart';
|
||||
import '../../domain/schedule_rule.dart';
|
||||
import 'schedule_editor_form_body.dart';
|
||||
import 'schedule_editor_wording.dart';
|
||||
|
||||
/// The server's refusal, verbatim, plus the browser's preservation promise.
|
||||
String scheduleEditorRefusal(Object error) {
|
||||
final reason = '$error'.trim();
|
||||
return '${reason.isEmpty ? 'The schedule was not saved.' : reason} '
|
||||
'$scheduleEditorDraftPreserved';
|
||||
}
|
||||
|
||||
/// One native form over a landed [ScheduleDraft].
|
||||
///
|
||||
/// The form owns only editable controls: it mutates the draft on submit, asks
|
||||
/// the draft to validate and assemble the exact record, and calls [onSubmit]
|
||||
/// only with a non-null record. It never talks to a repository, route or
|
||||
/// scheduler, and an async refusal leaves every typed value in place.
|
||||
class ScheduleEditorForm extends StatefulWidget {
|
||||
const ScheduleEditorForm({
|
||||
super.key,
|
||||
required this.draft,
|
||||
required this.onSubmit,
|
||||
this.onCancel,
|
||||
this.title,
|
||||
});
|
||||
|
||||
final ScheduleDraft draft;
|
||||
final Future<void> Function(JsonMap record) onSubmit;
|
||||
final VoidCallback? onCancel;
|
||||
final String? title;
|
||||
|
||||
@override
|
||||
State<ScheduleEditorForm> createState() => _ScheduleEditorFormState();
|
||||
}
|
||||
|
||||
class _ScheduleEditorFormState extends State<ScheduleEditorForm> {
|
||||
late final TextEditingController _name;
|
||||
late final TextEditingController _prompt;
|
||||
late final TextEditingController _version;
|
||||
late final TextEditingController _workspace;
|
||||
late final TextEditingController _every;
|
||||
late final TextEditingController _times;
|
||||
late final TextEditingController _timezone;
|
||||
late ScheduleTimerMode _mode;
|
||||
late List<String> _days;
|
||||
late bool _enabled;
|
||||
late String _notifyMode;
|
||||
|
||||
Map<String, String> _errors = const {};
|
||||
String? _refusal;
|
||||
bool _sending = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final draft = widget.draft;
|
||||
_name = TextEditingController(text: draft.name);
|
||||
_prompt = TextEditingController(text: draft.prompt);
|
||||
_version = TextEditingController(text: draft.version);
|
||||
_workspace = TextEditingController(text: draft.workspace);
|
||||
_every = TextEditingController(text: draft.every);
|
||||
_times = TextEditingController(text: draft.times);
|
||||
_timezone = TextEditingController(text: draft.timezone);
|
||||
_mode = draft.mode;
|
||||
_days = [...draft.days];
|
||||
_enabled = draft.enabled;
|
||||
_notifyMode = draft.notifyMode;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
for (final controller in [
|
||||
_name,
|
||||
_prompt,
|
||||
_version,
|
||||
_workspace,
|
||||
_every,
|
||||
_times,
|
||||
_timezone,
|
||||
]) {
|
||||
controller.dispose();
|
||||
}
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
String get _heading =>
|
||||
widget.title ??
|
||||
(widget.draft.source == null
|
||||
? scheduleEditorAddTitle
|
||||
: scheduleEditorEditTitle);
|
||||
|
||||
void _clearError(String field) {
|
||||
if (!_errors.containsKey(field)) return;
|
||||
setState(() => _errors = {..._errors}..remove(field));
|
||||
}
|
||||
|
||||
void _applyToDraft() {
|
||||
widget.draft
|
||||
..name = _name.text
|
||||
..prompt = _prompt.text
|
||||
..version = _version.text
|
||||
..workspace = _workspace.text
|
||||
..enabled = _enabled
|
||||
..mode = _mode
|
||||
..every = _every.text
|
||||
..times = _times.text
|
||||
..days = [
|
||||
for (final day in scheduleDays)
|
||||
if (_days.contains(day)) day,
|
||||
]
|
||||
..timezone = _timezone.text
|
||||
..notifyMode = _notifyMode;
|
||||
}
|
||||
|
||||
Future<void> _submit() async {
|
||||
if (_sending) return;
|
||||
setState(() => _refusal = null);
|
||||
_applyToDraft();
|
||||
final result = widget.draft.build();
|
||||
if (!result.isValid) {
|
||||
setState(() => _errors = result.errors);
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_errors = const {};
|
||||
_sending = true;
|
||||
});
|
||||
try {
|
||||
await widget.onSubmit(result.record!);
|
||||
} catch (error) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_sending = false;
|
||||
_refusal = scheduleEditorRefusal(error);
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (mounted) setState(() => _sending = false);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final cupertino = usesCupertinoHost(context);
|
||||
return ScheduleEditorFormBody(
|
||||
heading: _heading,
|
||||
name: _name,
|
||||
prompt: _prompt,
|
||||
version: _version,
|
||||
workspace: _workspace,
|
||||
every: _every,
|
||||
times: _times,
|
||||
timezone: _timezone,
|
||||
mode: _mode,
|
||||
days: _days,
|
||||
enabled: _enabled,
|
||||
notifyMode: _notifyMode,
|
||||
errors: _errors,
|
||||
sending: _sending,
|
||||
refusal: _refusal,
|
||||
onModeChanged: (mode) => setState(() {
|
||||
_mode = mode;
|
||||
_errors = {..._errors}
|
||||
..remove('every')
|
||||
..remove('times');
|
||||
}),
|
||||
onDayToggled: (day) => setState(() {
|
||||
_days = [..._days];
|
||||
_days.contains(day) ? _days.remove(day) : _days.add(day);
|
||||
_errors = {..._errors}..remove('days');
|
||||
}),
|
||||
onEnabledChanged: (enabled) => setState(() => _enabled = enabled),
|
||||
onNotifyChanged: (mode) => setState(() {
|
||||
_notifyMode = mode;
|
||||
_errors = {..._errors}..remove('notifyMode');
|
||||
}),
|
||||
onEdited: _clearError,
|
||||
actions: Wrap(
|
||||
alignment: WrapAlignment.end,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
spacing: 12,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
if (widget.onCancel != null)
|
||||
_cancelButton(cupertino)
|
||||
else
|
||||
const SizedBox.shrink(),
|
||||
_saveButton(cupertino),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _cancelButton(bool cupertino) {
|
||||
final onPressed = _sending ? null : widget.onCancel;
|
||||
if (cupertino) {
|
||||
return CupertinoButton(
|
||||
key: scheduleEditorCancelKey,
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: onPressed,
|
||||
child: const Text(scheduleEditorCancelLabel),
|
||||
);
|
||||
}
|
||||
return TextButton(
|
||||
key: scheduleEditorCancelKey,
|
||||
onPressed: onPressed,
|
||||
child: const Text(scheduleEditorCancelLabel),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _saveButton(bool cupertino) {
|
||||
final label = Text(
|
||||
_sending ? scheduleEditorSendingLabel : scheduleEditorSubmitLabel,
|
||||
);
|
||||
final onPressed = _sending ? null : _submit;
|
||||
if (cupertino) {
|
||||
return CupertinoButton.filled(
|
||||
key: scheduleEditorSubmitKey,
|
||||
onPressed: onPressed,
|
||||
child: label,
|
||||
);
|
||||
}
|
||||
return FilledButton(
|
||||
key: scheduleEditorSubmitKey,
|
||||
onPressed: onPressed,
|
||||
child: label,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../../ui/adaptive/host.dart';
|
||||
import '../../domain/editor/schedule_draft.dart';
|
||||
import 'schedule_editor_fields.dart';
|
||||
import 'schedule_editor_selectors.dart';
|
||||
import 'schedule_editor_wording.dart';
|
||||
|
||||
/// The visible schedule editor column: native fields, field errors and the
|
||||
/// Cancel/Save actions. State stays in `ScheduleEditorForm`; this widget only
|
||||
/// renders the values and forwards edits.
|
||||
class ScheduleEditorFormBody extends StatelessWidget {
|
||||
const ScheduleEditorFormBody({
|
||||
super.key,
|
||||
required this.heading,
|
||||
required this.name,
|
||||
required this.prompt,
|
||||
required this.version,
|
||||
required this.workspace,
|
||||
required this.every,
|
||||
required this.times,
|
||||
required this.timezone,
|
||||
required this.mode,
|
||||
required this.days,
|
||||
required this.enabled,
|
||||
required this.notifyMode,
|
||||
required this.errors,
|
||||
required this.sending,
|
||||
this.refusal,
|
||||
required this.onModeChanged,
|
||||
required this.onDayToggled,
|
||||
required this.onEnabledChanged,
|
||||
required this.onNotifyChanged,
|
||||
required this.onEdited,
|
||||
required this.actions,
|
||||
});
|
||||
|
||||
final String heading;
|
||||
final TextEditingController name;
|
||||
final TextEditingController prompt;
|
||||
final TextEditingController version;
|
||||
final TextEditingController workspace;
|
||||
final TextEditingController every;
|
||||
final TextEditingController times;
|
||||
final TextEditingController timezone;
|
||||
final ScheduleTimerMode mode;
|
||||
final List<String> days;
|
||||
final bool enabled;
|
||||
final String notifyMode;
|
||||
final Map<String, String> errors;
|
||||
final bool sending;
|
||||
final String? refusal;
|
||||
final ValueChanged<ScheduleTimerMode> onModeChanged;
|
||||
final ValueChanged<String> onDayToggled;
|
||||
final ValueChanged<bool> onEnabledChanged;
|
||||
final ValueChanged<String> onNotifyChanged;
|
||||
final ValueChanged<String> onEdited;
|
||||
final Widget actions;
|
||||
|
||||
static const _gap = SizedBox(height: 16);
|
||||
static const _timerOptions = [
|
||||
ScheduleEditorChoice(ScheduleTimerMode.interval, 'Interval'),
|
||||
ScheduleEditorChoice(ScheduleTimerMode.clock, 'Clock times'),
|
||||
];
|
||||
|
||||
List<ScheduleEditorChoice<String>> get _notifyOptions {
|
||||
const values = ['auto', 'on', 'off'];
|
||||
return [
|
||||
if (!values.contains(notifyMode))
|
||||
ScheduleEditorChoice(notifyMode, notifyMode),
|
||||
for (final value in values) ScheduleEditorChoice(value, value),
|
||||
];
|
||||
}
|
||||
|
||||
Widget _textField({
|
||||
required Key key,
|
||||
required String label,
|
||||
required TextEditingController controller,
|
||||
required String field,
|
||||
String? error,
|
||||
int minLines = 1,
|
||||
int? maxLines = 1,
|
||||
TextInputType? keyboardType,
|
||||
TextInputAction? textInputAction,
|
||||
}) => ScheduleEditorTextField(
|
||||
fieldKey: key,
|
||||
label: label,
|
||||
controller: controller,
|
||||
enabled: !sending,
|
||||
minLines: minLines,
|
||||
maxLines: maxLines,
|
||||
keyboardType: keyboardType,
|
||||
textInputAction: textInputAction,
|
||||
error: error,
|
||||
onChanged: (_) => onEdited(field),
|
||||
);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final cupertino = usesCupertinoHost(context);
|
||||
final titleStyle = cupertino
|
||||
? CupertinoTheme.of(context).textTheme.navLargeTitleTextStyle
|
||||
: Theme.of(context).textTheme.titleLarge;
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(heading, style: titleStyle),
|
||||
const SizedBox(height: 8),
|
||||
Text(scheduleEditorNote, style: scheduleEditorSecondaryStyle(context)),
|
||||
_gap,
|
||||
_textField(
|
||||
key: scheduleEditorNameKey,
|
||||
label: scheduleEditorNameLabel,
|
||||
controller: name,
|
||||
field: 'name',
|
||||
error: errors['name'],
|
||||
textInputAction: TextInputAction.next,
|
||||
),
|
||||
_gap,
|
||||
_textField(
|
||||
key: scheduleEditorPromptKey,
|
||||
label: scheduleEditorPromptLabel,
|
||||
controller: prompt,
|
||||
field: 'prompt',
|
||||
error: errors['prompt'],
|
||||
minLines: 3,
|
||||
maxLines: null,
|
||||
keyboardType: TextInputType.multiline,
|
||||
),
|
||||
_gap,
|
||||
_textField(
|
||||
key: scheduleEditorVersionKey,
|
||||
label: scheduleEditorVersionLabel,
|
||||
controller: version,
|
||||
field: 'version',
|
||||
error: errors['version'],
|
||||
keyboardType: TextInputType.number,
|
||||
textInputAction: TextInputAction.next,
|
||||
),
|
||||
_gap,
|
||||
_textField(
|
||||
key: scheduleEditorWorkspaceKey,
|
||||
label: scheduleEditorWorkspaceLabel,
|
||||
controller: workspace,
|
||||
field: 'workspace',
|
||||
error: errors['workspace'],
|
||||
textInputAction: TextInputAction.next,
|
||||
),
|
||||
_gap,
|
||||
ScheduleEditorChoiceField<ScheduleTimerMode>(
|
||||
fieldKey: scheduleEditorTimerKey,
|
||||
label: scheduleEditorTimerLabel,
|
||||
value: mode,
|
||||
options: _timerOptions,
|
||||
enabled: !sending,
|
||||
onChanged: onModeChanged,
|
||||
),
|
||||
_gap,
|
||||
if (mode == ScheduleTimerMode.interval)
|
||||
_textField(
|
||||
key: scheduleEditorEveryKey,
|
||||
label: scheduleEditorEveryLabel,
|
||||
controller: every,
|
||||
field: 'every',
|
||||
error: errors['every'],
|
||||
)
|
||||
else
|
||||
_textField(
|
||||
key: scheduleEditorTimesKey,
|
||||
label: scheduleEditorTimesLabel,
|
||||
controller: times,
|
||||
field: 'times',
|
||||
error: errors['times'],
|
||||
),
|
||||
_gap,
|
||||
ScheduleEditorDaysField(
|
||||
label: scheduleEditorDaysLabel,
|
||||
days: days,
|
||||
enabled: !sending,
|
||||
error: errors['days'],
|
||||
onToggle: onDayToggled,
|
||||
),
|
||||
_gap,
|
||||
_textField(
|
||||
key: scheduleEditorTimezoneKey,
|
||||
label: scheduleEditorTimezoneLabel,
|
||||
controller: timezone,
|
||||
field: 'timezone',
|
||||
error: errors['timezone'],
|
||||
),
|
||||
_gap,
|
||||
ScheduleEditorSwitchField(
|
||||
switchKey: scheduleEditorEnabledKey,
|
||||
label: scheduleEditorEnabledLabel,
|
||||
helper: scheduleEditorEnabledNote,
|
||||
value: enabled,
|
||||
enabled: !sending,
|
||||
onChanged: onEnabledChanged,
|
||||
),
|
||||
_gap,
|
||||
ScheduleEditorChoiceField<String>(
|
||||
fieldKey: scheduleEditorNotifyKey,
|
||||
label: scheduleEditorNotificationsLabel,
|
||||
value: notifyMode,
|
||||
options: _notifyOptions,
|
||||
enabled: !sending,
|
||||
error: errors['notifyMode'],
|
||||
onChanged: onNotifyChanged,
|
||||
),
|
||||
if (refusal ?? errors['record'] ?? errors['pipelineId']
|
||||
case final error?) ...[
|
||||
_gap,
|
||||
Semantics(
|
||||
liveRegion: true,
|
||||
child: Text(
|
||||
error,
|
||||
key: scheduleEditorErrorKey,
|
||||
style: scheduleEditorErrorStyle(context),
|
||||
),
|
||||
),
|
||||
],
|
||||
_gap,
|
||||
actions,
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../../ui/adaptive/host.dart';
|
||||
import '../../domain/schedule_rule.dart';
|
||||
import 'schedule_editor_fields.dart';
|
||||
|
||||
/// Day checkbox keys, shared with tests and the browser fixture.
|
||||
ValueKey<String> scheduleEditorDayKey(String day) =>
|
||||
ValueKey<String>('schedule-editor-day-$day');
|
||||
|
||||
/// One option of a [ScheduleEditorChoiceField].
|
||||
class ScheduleEditorChoice<T> {
|
||||
const ScheduleEditorChoice(this.value, this.label);
|
||||
|
||||
final T value;
|
||||
final String label;
|
||||
}
|
||||
|
||||
/// A native drop-down on Material and a native action sheet on Cupertino.
|
||||
class ScheduleEditorChoiceField<T> extends StatelessWidget {
|
||||
const ScheduleEditorChoiceField({
|
||||
super.key,
|
||||
required this.label,
|
||||
required this.value,
|
||||
required this.options,
|
||||
required this.onChanged,
|
||||
this.enabled = true,
|
||||
this.helper,
|
||||
this.error,
|
||||
this.fieldKey,
|
||||
});
|
||||
|
||||
final String label;
|
||||
final T value;
|
||||
final List<ScheduleEditorChoice<T>> options;
|
||||
final ValueChanged<T> onChanged;
|
||||
final bool enabled;
|
||||
final String? helper;
|
||||
final String? error;
|
||||
final Key? fieldKey;
|
||||
|
||||
String get _selectedLabel {
|
||||
for (final option in options) {
|
||||
if (option.value == value) return option.label;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
Future<void> _choose(BuildContext context) async {
|
||||
final chosen = await showCupertinoModalPopup<T>(
|
||||
context: context,
|
||||
builder: (sheetContext) => CupertinoActionSheet(
|
||||
title: Text(label),
|
||||
actions: [
|
||||
for (final option in options)
|
||||
CupertinoActionSheetAction(
|
||||
onPressed: () => Navigator.pop(sheetContext, option.value),
|
||||
child: Text(option.label),
|
||||
),
|
||||
],
|
||||
cancelButton: CupertinoActionSheetAction(
|
||||
onPressed: () => Navigator.pop(sheetContext),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (chosen != null) onChanged(chosen);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final control = usesCupertinoHost(context)
|
||||
? CupertinoButton(
|
||||
key: fieldKey,
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: enabled ? () => _choose(context) : null,
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(child: Text(_selectedLabel)),
|
||||
const Icon(CupertinoIcons.chevron_down),
|
||||
],
|
||||
),
|
||||
)
|
||||
: DropdownButtonFormField<T>(
|
||||
key: fieldKey,
|
||||
initialValue: value,
|
||||
isExpanded: true,
|
||||
items: [
|
||||
for (final option in options)
|
||||
DropdownMenuItem<T>(
|
||||
value: option.value,
|
||||
child: Text(option.label),
|
||||
),
|
||||
],
|
||||
onChanged: enabled
|
||||
? (chosen) {
|
||||
if (chosen != null) onChanged(chosen);
|
||||
}
|
||||
: null,
|
||||
);
|
||||
return MergeSemantics(
|
||||
child: ScheduleEditorField(
|
||||
label: label,
|
||||
helper: helper,
|
||||
error: error,
|
||||
child: control,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Weekday checkboxes in a wrapping row; no selection means every day.
|
||||
class ScheduleEditorDaysField extends StatelessWidget {
|
||||
const ScheduleEditorDaysField({
|
||||
super.key,
|
||||
required this.label,
|
||||
required this.days,
|
||||
required this.onToggle,
|
||||
this.enabled = true,
|
||||
this.error,
|
||||
});
|
||||
|
||||
final String label;
|
||||
final List<String> days;
|
||||
final ValueChanged<String> onToggle;
|
||||
final bool enabled;
|
||||
final String? error;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ScheduleEditorField(
|
||||
label: label,
|
||||
error: error,
|
||||
child: Wrap(
|
||||
spacing: 12,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
for (final day in scheduleDays)
|
||||
_DayToggle(
|
||||
day: day,
|
||||
selected: days.contains(day),
|
||||
enabled: enabled,
|
||||
onTap: () => onToggle(day),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _DayToggle extends StatelessWidget {
|
||||
const _DayToggle({
|
||||
required this.day,
|
||||
required this.selected,
|
||||
required this.enabled,
|
||||
required this.onTap,
|
||||
});
|
||||
|
||||
final String day;
|
||||
final bool selected;
|
||||
final bool enabled;
|
||||
final VoidCallback onTap;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final cupertino = usesCupertinoHost(context);
|
||||
final checkbox = cupertino
|
||||
? CupertinoCheckbox(
|
||||
key: scheduleEditorDayKey(day),
|
||||
value: selected,
|
||||
onChanged: enabled ? (_) => onTap() : null,
|
||||
)
|
||||
: Checkbox(
|
||||
key: scheduleEditorDayKey(day),
|
||||
value: selected,
|
||||
onChanged: enabled ? (_) => onTap() : null,
|
||||
);
|
||||
final content = Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [checkbox, const SizedBox(width: 4), Text(day)],
|
||||
),
|
||||
);
|
||||
return MergeSemantics(
|
||||
child: cupertino
|
||||
? GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTap: enabled ? onTap : null,
|
||||
child: content,
|
||||
)
|
||||
: InkWell(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
onTap: enabled ? onTap : null,
|
||||
child: content,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
/// Browser wording and stable keys for the saved-schedule editor, kept
|
||||
/// verbatim from `web/src/views/schedules.js`.
|
||||
const scheduleEditorAddTitle = 'Add schedule';
|
||||
const scheduleEditorEditTitle = 'Edit schedule';
|
||||
const scheduleEditorNote =
|
||||
'Future runs only; does not publish or change the workflow. '
|
||||
'Saving does not start a run.';
|
||||
const scheduleEditorNameLabel = 'Name';
|
||||
const scheduleEditorPromptLabel = 'Prompt';
|
||||
const scheduleEditorVersionLabel = 'Pinned version';
|
||||
const scheduleEditorWorkspaceLabel = 'Server workspace';
|
||||
const scheduleEditorTimerLabel = 'Timer';
|
||||
const scheduleEditorEveryLabel = 'Interval (at least 1m)';
|
||||
const scheduleEditorTimesLabel = 'Clock times (24h, comma separated)';
|
||||
const scheduleEditorDaysLabel = 'Weekdays (none means every day)';
|
||||
const scheduleEditorTimezoneLabel = 'Timezone (blank uses server timezone)';
|
||||
const scheduleEditorEnabledLabel = 'Enabled';
|
||||
const scheduleEditorEnabledNote =
|
||||
'Enabled schedules start future runs automatically, including model '
|
||||
'usage and the workflow’s permitted tools.';
|
||||
const scheduleEditorNotificationsLabel = 'Notifications';
|
||||
const scheduleEditorSubmitLabel = 'Save schedule';
|
||||
const scheduleEditorSendingLabel = 'Saving…';
|
||||
const scheduleEditorCancelLabel = 'Cancel';
|
||||
const scheduleEditorDraftPreserved =
|
||||
'Your draft is preserved. If this schedule changed elsewhere, reopen it '
|
||||
'before retrying.';
|
||||
|
||||
const scheduleEditorNameKey = ValueKey<String>('schedule-editor-name');
|
||||
const scheduleEditorPromptKey = ValueKey<String>('schedule-editor-prompt');
|
||||
const scheduleEditorVersionKey = ValueKey<String>('schedule-editor-version');
|
||||
const scheduleEditorWorkspaceKey = ValueKey<String>(
|
||||
'schedule-editor-workspace',
|
||||
);
|
||||
const scheduleEditorTimerKey = ValueKey<String>('schedule-editor-timer');
|
||||
const scheduleEditorEveryKey = ValueKey<String>('schedule-editor-every');
|
||||
const scheduleEditorTimesKey = ValueKey<String>('schedule-editor-times');
|
||||
const scheduleEditorTimezoneKey = ValueKey<String>('schedule-editor-timezone');
|
||||
const scheduleEditorEnabledKey = ValueKey<String>('schedule-editor-enabled');
|
||||
const scheduleEditorNotifyKey = ValueKey<String>('schedule-editor-notify');
|
||||
const scheduleEditorSubmitKey = ValueKey<String>('schedule-editor-submit');
|
||||
const scheduleEditorCancelKey = ValueKey<String>('schedule-editor-cancel');
|
||||
const scheduleEditorErrorKey = ValueKey<String>('schedule-editor-error');
|
||||
@@ -79,6 +79,12 @@ class TemplateRepository {
|
||||
'The server returned no pipeline detail.',
|
||||
);
|
||||
}
|
||||
final id = detail['id'];
|
||||
if (id is! num || !id.isFinite || id <= 0 || id != id.truncateToDouble()) {
|
||||
throw const TemplateRepositoryException(
|
||||
'The server did not confirm a created pipeline.',
|
||||
);
|
||||
}
|
||||
return Map<String, dynamic>.from(detail);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'template_create_wording.dart';
|
||||
|
||||
/// Full wrapping native label, not a clipped placeholder/floating field label.
|
||||
class TemplateCreateNameField extends StatelessWidget {
|
||||
const TemplateCreateNameField({
|
||||
super.key,
|
||||
required this.cupertino,
|
||||
required this.controller,
|
||||
required this.enabled,
|
||||
required this.onSubmit,
|
||||
});
|
||||
|
||||
final bool cupertino;
|
||||
final TextEditingController controller;
|
||||
final bool enabled;
|
||||
final VoidCallback onSubmit;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => MergeSemantics(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const Text(templateCreateNameLabel),
|
||||
const SizedBox(height: 8),
|
||||
if (cupertino)
|
||||
CupertinoTextField(
|
||||
key: templateCreateNameKey,
|
||||
controller: controller,
|
||||
enabled: enabled,
|
||||
autofocus: true,
|
||||
textInputAction: TextInputAction.done,
|
||||
onSubmitted: (_) => onSubmit(),
|
||||
)
|
||||
else
|
||||
TextField(
|
||||
key: templateCreateNameKey,
|
||||
controller: controller,
|
||||
enabled: enabled,
|
||||
autofocus: true,
|
||||
textInputAction: TextInputAction.done,
|
||||
onSubmitted: (_) => onSubmit(),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget templateCreateDialogAction({
|
||||
required Key key,
|
||||
required bool cupertino,
|
||||
required VoidCallback? onPressed,
|
||||
required Widget child,
|
||||
bool primary = false,
|
||||
}) {
|
||||
if (cupertino) {
|
||||
return CupertinoDialogAction(
|
||||
key: key,
|
||||
isDefaultAction: primary,
|
||||
onPressed: onPressed,
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
if (primary) {
|
||||
return FilledButton(key: key, onPressed: onPressed, child: child);
|
||||
}
|
||||
return TextButton(key: key, onPressed: onPressed, child: child);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import '../../../core/api_gateway.dart';
|
||||
import '../data/template_repository.dart';
|
||||
import '../domain/template_entry.dart';
|
||||
import 'template_create_wording.dart';
|
||||
import 'template_create_controls.dart';
|
||||
|
||||
/// Opens the native create prompt; resolves when it closes. Opening, typing and
|
||||
/// Cancel send nothing; Create validates the source first and only a passing
|
||||
@@ -156,7 +157,12 @@ class _TemplateCreateDialogState extends State<_TemplateCreateDialog> {
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
_field(),
|
||||
TemplateCreateNameField(
|
||||
cupertino: widget.cupertino,
|
||||
controller: _name,
|
||||
enabled: _fieldEnabled,
|
||||
onSubmit: _create,
|
||||
),
|
||||
// Feedback stays next to the field it belongs to. The note below can
|
||||
// be pushed out of the dialog's scroll viewport on a short, large-text
|
||||
// screen; a refusal or success line must not be.
|
||||
@@ -189,7 +195,8 @@ class _TemplateCreateDialogState extends State<_TemplateCreateDialog> {
|
||||
],
|
||||
);
|
||||
final actions = [
|
||||
_dialogAction(
|
||||
templateCreateDialogAction(
|
||||
cupertino: widget.cupertino,
|
||||
key: templateCreateCancelKey,
|
||||
onPressed: _sending ? null : _cancel,
|
||||
child: Text(
|
||||
@@ -198,7 +205,8 @@ class _TemplateCreateDialogState extends State<_TemplateCreateDialog> {
|
||||
: templateCreateCloseLabel,
|
||||
),
|
||||
),
|
||||
_dialogAction(
|
||||
templateCreateDialogAction(
|
||||
cupertino: widget.cupertino,
|
||||
key: templateCreateConfirmKey,
|
||||
primary: true,
|
||||
onPressed: _canSubmit ? _create : null,
|
||||
@@ -228,60 +236,4 @@ class _TemplateCreateDialogState extends State<_TemplateCreateDialog> {
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _field() {
|
||||
// A wrapping label above the field, like the browser's label span: the
|
||||
// Material floating label is ellipsized to `New pipeline name (requ…` at 2x
|
||||
// text, and a Cupertino placeholder is not exposed as the field's name.
|
||||
// Merging the visible label into the field gives both hosts one node with
|
||||
// the exact wording and the field's value.
|
||||
final field = widget.cupertino
|
||||
? CupertinoTextField(
|
||||
key: templateCreateNameKey,
|
||||
controller: _name,
|
||||
enabled: _fieldEnabled,
|
||||
autofocus: true,
|
||||
textInputAction: TextInputAction.done,
|
||||
onSubmitted: (_) => _create(),
|
||||
)
|
||||
: TextField(
|
||||
key: templateCreateNameKey,
|
||||
controller: _name,
|
||||
enabled: _fieldEnabled,
|
||||
autofocus: true,
|
||||
textInputAction: TextInputAction.done,
|
||||
onSubmitted: (_) => _create(),
|
||||
);
|
||||
return MergeSemantics(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const Text(templateCreateNameLabel),
|
||||
const SizedBox(height: 8),
|
||||
field,
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _dialogAction({
|
||||
required Key key,
|
||||
required VoidCallback? onPressed,
|
||||
required Widget child,
|
||||
bool primary = false,
|
||||
}) {
|
||||
if (widget.cupertino) {
|
||||
return CupertinoDialogAction(
|
||||
key: key,
|
||||
isDefaultAction: primary,
|
||||
onPressed: onPressed,
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
if (primary) {
|
||||
return FilledButton(key: key, onPressed: onPressed, child: child);
|
||||
}
|
||||
return TextButton(key: key, onPressed: onPressed, child: child);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
# 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.<session_id>`; 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-<operationId>`), 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-<microseconds>-<sequence>`; 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': <session>}}`. 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.
|
||||
- **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
|
||||
|
||||
`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.
|
||||
@@ -0,0 +1,196 @@
|
||||
# S1-form — native saved-schedule form
|
||||
|
||||
Manager acceptance: merged after inspecting the new-source-only diff. Re-ran all
|
||||
schedule tests and rebuilt the fixture; the probe passed every step and produced
|
||||
seven captures. Inspected the Cupertino dark phone form and the 320px/2x Material
|
||||
form: full wrapping labels, native fields/menus/switches, readable semantic error
|
||||
colour, no clipped helper copy. The form mutates only the caller-owned draft and
|
||||
calls the injected submit callback, so no repository/route/scheduler is implied.
|
||||
Schedule persistence, pause/delete, conflicts and the Schedule-this-run seed are
|
||||
still separate wiring work; nothing was saved to a real server.
|
||||
|
||||
## 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 `"<server reason> 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 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
|
||||
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
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
- 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; 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
|
||||
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`
|
||||
|
||||
## Honest limits
|
||||
|
||||
- **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.
|
||||
- **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`.
|
||||
@@ -1,5 +1,22 @@
|
||||
# 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.
|
||||
|
||||
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
|
||||
|
||||
A native Material/Cupertino prompt implements the browser's P5 create flow
|
||||
|
||||
@@ -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 = <Completer<String>>[];
|
||||
final writes = <String>[];
|
||||
|
||||
@override
|
||||
Future<String> read(String sessionId) {
|
||||
final completer = Completer<String>();
|
||||
reads.add(completer);
|
||||
return completer.future;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> 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);
|
||||
});
|
||||
}
|
||||
@@ -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<JsonMap>.broadcast();
|
||||
Future<JsonMap> Function(String text, String operationId)? prompt;
|
||||
Future<JsonMap> Function()? interrupt;
|
||||
|
||||
@override
|
||||
Future<JsonMap> 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
|
||||
? <String, dynamic>{}
|
||||
: prompt!('${body['text'] ?? ''}', '${body['operation_id'] ?? ''}');
|
||||
case 'chat_interrupt':
|
||||
return interrupt == null ? <String, dynamic>{} : interrupt!();
|
||||
}
|
||||
return <String, dynamic>{};
|
||||
}
|
||||
|
||||
@override
|
||||
Stream<JsonMap> get frames => _frames.stream;
|
||||
|
||||
void emitEvent(JsonMap body) =>
|
||||
_frames.add({'type': 'chat_event', 'chat_event': body});
|
||||
|
||||
List<JsonMap> get promptBodies => calls
|
||||
.where((call) => call.type == 'chat_prompt')
|
||||
.map((call) => call.fields['chat_prompt'] as JsonMap)
|
||||
.toList();
|
||||
|
||||
void close() => _frames.close();
|
||||
}
|
||||
@@ -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<ChatComposerSend> optimistic;
|
||||
late List<String> 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<Map<String, dynamic>>();
|
||||
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<Map<String, dynamic>>();
|
||||
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<Map<String, dynamic>>();
|
||||
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, '');
|
||||
});
|
||||
}
|
||||
@@ -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 = <JsonMap>[];
|
||||
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<TextField>(find.byKey(scheduleEditorVersionKey))
|
||||
.controller!
|
||||
.text,
|
||||
'2',
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('valid create sends the exact save record', (tester) async {
|
||||
final calls = <JsonMap>[];
|
||||
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 = <JsonMap>[];
|
||||
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 = <JsonMap>[];
|
||||
await pumpScheduleEditor(
|
||||
tester,
|
||||
draft: editDraft(),
|
||||
onSubmit: (record) async => calls.add(record),
|
||||
);
|
||||
expect(find.text('Edit schedule'), findsOneWidget);
|
||||
expect(
|
||||
tester
|
||||
.widget<TextField>(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],
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -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<void> pumpScheduleEditor(
|
||||
WidgetTester tester, {
|
||||
required ScheduleDraft draft,
|
||||
required Future<void> 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<void> enterField(WidgetTester tester, Key key, String value) async {
|
||||
await tester.enterText(find.byKey(key), value);
|
||||
await tester.pump();
|
||||
}
|
||||
@@ -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 = <JsonMap>[];
|
||||
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<TextField>(find.byKey(scheduleEditorNameKey))
|
||||
.controller!
|
||||
.text,
|
||||
'Probe schedule',
|
||||
);
|
||||
expect(
|
||||
tester
|
||||
.widget<TextField>(find.byKey(scheduleEditorPromptKey))
|
||||
.controller!
|
||||
.text,
|
||||
'Keep these words',
|
||||
);
|
||||
expect(
|
||||
tester
|
||||
.widget<FilledButton>(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<void>();
|
||||
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<FilledButton>(find.byKey(scheduleEditorSubmitKey))
|
||||
.onPressed,
|
||||
isNull,
|
||||
);
|
||||
expect(
|
||||
tester.widget<TextField>(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<FilledButton>(find.byKey(scheduleEditorSubmitKey))
|
||||
.onPressed,
|
||||
isNotNull,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('Cupertino form uses native fields and action sheets', (
|
||||
tester,
|
||||
) async {
|
||||
final calls = <JsonMap>[];
|
||||
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<CupertinoCheckbox>(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 = <JsonMap>[];
|
||||
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);
|
||||
});
|
||||
}
|
||||
@@ -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<RenderParagraph>(
|
||||
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(),
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -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<TemplateRepositoryException>()),
|
||||
);
|
||||
expect(gateway.calls.single.fields['create_only'], isTrue);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -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=<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 });
|
||||
}
|
||||
@@ -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,
|
||||
<String, Object?>{
|
||||
'submits': _submits,
|
||||
'records': _records,
|
||||
'pending': _pending,
|
||||
'lastError': _lastError,
|
||||
'lastRecord': _lastRecord,
|
||||
}.jsify(),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _submit(JsonMap record) async {
|
||||
_submits++;
|
||||
_pending = true;
|
||||
_publish();
|
||||
if (mounted) setState(() {});
|
||||
await Future<void>.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),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<String>('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<String>('template-probe-open'),
|
||||
onPressed: _open,
|
||||
child: const Text(
|
||||
'Create pipeline from this template',
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -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(),
|
||||
|
||||
Reference in New Issue
Block a user