feat(app): add saved-schedule repository and domain record
Port the web client's list/save/delete schedule request shapes and reply checks, with a typed record that preserves the whole server payload including unknown fields. Revision stays the CAS token; server refusals propagate unchanged.
This commit is contained in:
+4
-1
@@ -45,6 +45,9 @@ app.*.map.json
|
||||
/android/app/release
|
||||
|
||||
# The repository ignores runtime data/ directories. Feature repository source
|
||||
# is code, not runtime data, and must be included in fresh checkouts.
|
||||
# and its tests are code, not runtime data, and must be included in fresh
|
||||
# checkouts.
|
||||
!/lib/**/data/
|
||||
!/lib/**/data/**
|
||||
!/test/**/data/
|
||||
!/test/**/data/**
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../domain/saved_schedule.dart';
|
||||
import '../domain/schedule_json.dart';
|
||||
|
||||
/// Client-side protocol failure. Server refusals and transport errors are not
|
||||
/// wrapped: [ApiGateway] already surfaces their exact text.
|
||||
class SchedulesRepositoryException implements Exception {
|
||||
const SchedulesRepositoryException(this.message);
|
||||
final String message;
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
/// The saved-schedule commands of the current web client.
|
||||
///
|
||||
/// These are run configurations, not pipeline definitions: this repository
|
||||
/// never submits, validates or publishes a workflow, and it never starts or
|
||||
/// polls a run. Timer execution belongs to the server.
|
||||
class SchedulesRepository {
|
||||
SchedulesRepository(this._gateway);
|
||||
|
||||
final ApiGateway _gateway;
|
||||
|
||||
/// Lists saved schedules, optionally for one pipeline.
|
||||
///
|
||||
/// An explicit empty reply is a valid empty list. A reply without the
|
||||
/// `schedules` type is not: that is an older/unsupported server and must be
|
||||
/// reported rather than shown as "no schedules".
|
||||
Future<List<SavedSchedule>> listSchedules({int? pipelineId}) async {
|
||||
final fields = <String, dynamic>{};
|
||||
if (pipelineId != null) {
|
||||
if (!_isPositiveId(pipelineId)) {
|
||||
throw const SchedulesRepositoryException(
|
||||
'A positive pipeline ID is required.',
|
||||
);
|
||||
}
|
||||
fields['pipeline_id'] = pipelineId;
|
||||
}
|
||||
final reply = await _gateway.call('list_schedules', fields);
|
||||
final schedules = reply['schedules'];
|
||||
if (reply['type'] != 'schedules' ||
|
||||
(schedules != null && schedules is! List)) {
|
||||
throw const SchedulesRepositoryException(
|
||||
'The server returned no schedules response.',
|
||||
);
|
||||
}
|
||||
if (schedules == null) return const [];
|
||||
return [
|
||||
for (final item in schedules as List)
|
||||
if (item is Map)
|
||||
SavedSchedule(Map<String, dynamic>.from(item))
|
||||
else
|
||||
throw const SchedulesRepositoryException(
|
||||
'The server returned an invalid schedule record.',
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
/// Creates or updates one saved schedule.
|
||||
///
|
||||
/// Creation sends the web client's sentinel record (`id` 0, no revision) and
|
||||
/// may carry a stable request key so a lost reply is retried instead of
|
||||
/// creating a duplicate. Updating sends the record read from the server,
|
||||
/// whose `revision` is the compare-and-swap token; the key is omitted, as in
|
||||
/// the web client. A stale revision is refused by the server and propagated
|
||||
/// unchanged, never overwritten locally.
|
||||
Future<SavedSchedule> saveSchedule(
|
||||
JsonMap schedule, {
|
||||
String? requestKey,
|
||||
}) async {
|
||||
if (requestKey != null && requestKey.length > 128) {
|
||||
throw const SchedulesRepositoryException(
|
||||
'Schedule request keys must be strings of at most 128 characters.',
|
||||
);
|
||||
}
|
||||
final fields = <String, dynamic>{'schedule': cloneJsonMap(schedule)};
|
||||
if (requestKey != null && requestKey.isNotEmpty) {
|
||||
fields['request_key'] = requestKey;
|
||||
}
|
||||
final reply = await _gateway.call('save_schedule', fields);
|
||||
final saved = reply['schedule'];
|
||||
if (saved is! Map) {
|
||||
throw const SchedulesRepositoryException(
|
||||
'The server returned no saved schedule.',
|
||||
);
|
||||
}
|
||||
return SavedSchedule(Map<String, dynamic>.from(saved));
|
||||
}
|
||||
|
||||
/// Deletes exactly the revision the caller read.
|
||||
///
|
||||
/// Both identity and revision are required before any request is sent; a
|
||||
/// confirmation for a different schedule is treated as a failed delete.
|
||||
Future<void> deleteSchedule(int id, int revision) async {
|
||||
if (!_isPositiveId(id) || !_isPositiveId(revision)) {
|
||||
throw const SchedulesRepositoryException(
|
||||
'An exact schedule ID and revision are required.',
|
||||
);
|
||||
}
|
||||
final reply = await _gateway.call('delete_schedule', {
|
||||
'schedule_id': id,
|
||||
'expected_revision': revision,
|
||||
});
|
||||
if (reply['type'] != 'schedule_deleted' || reply['schedule_id'] != id) {
|
||||
throw const SchedulesRepositoryException(
|
||||
'The server did not confirm deletion of this schedule.',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// JSON/JavaScript integers are safe up to 2^53-1; the web client checks
|
||||
/// `Number.isSafeInteger` before sending an identity.
|
||||
const _maxSafeInteger = 9007199254740991;
|
||||
|
||||
bool _isPositiveId(int value) => value > 0 && value <= _maxSafeInteger;
|
||||
@@ -0,0 +1,87 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'schedule_json.dart';
|
||||
import 'schedule_rule.dart';
|
||||
|
||||
/// One saved run configuration from `list_schedules` or `save_schedule`.
|
||||
///
|
||||
/// A saved schedule is a complete run request pinned to one pipeline version.
|
||||
/// It is deliberately not a pipeline definition: nothing here is published,
|
||||
/// validated as a graph or treated as the pipeline's current version.
|
||||
///
|
||||
/// [raw] keeps the exact server record, including fields this client does not
|
||||
/// know yet. Typed getters are views; they never rewrite [raw].
|
||||
class SavedSchedule {
|
||||
SavedSchedule(JsonMap raw) : raw = cloneJsonMap(raw);
|
||||
|
||||
final JsonMap raw;
|
||||
|
||||
/// Server identity; null when an older reply omits it. Never defaulted to 0,
|
||||
/// because 0 is the create sentinel rather than a saved identity.
|
||||
int? get id => _integer(raw['id']);
|
||||
|
||||
/// Compare-and-swap token. Updates reuse it and deletes send it as
|
||||
/// `expected_revision`; this client never invents or increments it.
|
||||
int? get revision => _integer(raw['revision']);
|
||||
|
||||
int? get pipelineId => _integer(raw['pipeline_id']);
|
||||
int? get version => _integer(raw['version']);
|
||||
String get name => _text(raw['name']);
|
||||
bool get enabled => raw['enabled'] == true;
|
||||
|
||||
JsonMap get input => _map(raw['input']);
|
||||
String get prompt => _text(input['prompt']);
|
||||
String get workspace => _text(raw['workspace']);
|
||||
ScheduleRule get rule => ScheduleRule(_map(raw['rule']));
|
||||
|
||||
List<String> get writePaths => _texts(raw['write_paths']);
|
||||
bool get allowTools => raw['allow_tools'] == true;
|
||||
String get model => _text(raw['model']);
|
||||
Map<String, String> get stageModels => {
|
||||
for (final entry in _map(raw['stage_models']).entries)
|
||||
if (entry.value is String) entry.key: entry.value as String,
|
||||
};
|
||||
String get notifyMode => _text(raw['notify_mode']);
|
||||
String get title => _text(raw['title']);
|
||||
String get outputFormat => _text(raw['output_format']);
|
||||
|
||||
String get nextDue => _text(raw['next_due']);
|
||||
String get createdAt => _text(raw['created_at']);
|
||||
String get updatedAt => _text(raw['updated_at']);
|
||||
|
||||
/// The record to pass to `save_schedule`, deep-copied so callers cannot
|
||||
/// mutate this snapshot by aliasing.
|
||||
JsonMap toJson() => cloneJsonMap(raw);
|
||||
|
||||
/// Pause/enable copy. Identity, revision and every unknown field are kept so
|
||||
/// the update still targets the revision this record was read at.
|
||||
SavedSchedule withEnabled(bool value) {
|
||||
final copy = toJson();
|
||||
copy['enabled'] = value;
|
||||
return SavedSchedule(copy);
|
||||
}
|
||||
}
|
||||
|
||||
int? _integer(dynamic value) {
|
||||
if (value is int) return value;
|
||||
if (value is num && value.isFinite && value == value.truncateToDouble()) {
|
||||
return value.toInt();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
String _text(dynamic value) => value is String ? value : '';
|
||||
|
||||
JsonMap _map(dynamic value) {
|
||||
if (value is! Map) return <String, dynamic>{};
|
||||
return <String, dynamic>{
|
||||
for (final entry in value.entries)
|
||||
'${entry.key}': cloneJsonValue(entry.value),
|
||||
};
|
||||
}
|
||||
|
||||
List<String> _texts(dynamic value) => value is List
|
||||
? [
|
||||
for (final item in value)
|
||||
if (item is String) item,
|
||||
]
|
||||
: const [];
|
||||
@@ -0,0 +1,22 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
/// Deep copy of a decoded JSON value.
|
||||
///
|
||||
/// Saved schedules travel back to the server unchanged, so unknown fields (and
|
||||
/// unknown nested values) must survive every round trip without sharing state
|
||||
/// with the reply map that produced them.
|
||||
dynamic cloneJsonValue(dynamic value) {
|
||||
if (value is Map) {
|
||||
return <String, dynamic>{
|
||||
for (final entry in value.entries)
|
||||
'${entry.key}': cloneJsonValue(entry.value),
|
||||
};
|
||||
}
|
||||
if (value is List) {
|
||||
return [for (final item in value) cloneJsonValue(item)];
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
JsonMap cloneJsonMap(JsonMap value) =>
|
||||
Map<String, dynamic>.from(cloneJsonValue(value) as Map);
|
||||
@@ -0,0 +1,41 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'schedule_json.dart';
|
||||
|
||||
/// Weekday keys the server accepts for an interval rule.
|
||||
const scheduleDays = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
|
||||
|
||||
/// The timer part of a saved schedule (`rule` on the wire).
|
||||
///
|
||||
/// This is a view over the decoded server record, not a timer implementation:
|
||||
/// it never calculates due times, converts timezones or starts runs. Unknown
|
||||
/// rule fields stay in [raw] and are returned by [toJson].
|
||||
class ScheduleRule {
|
||||
ScheduleRule([JsonMap? raw]) : raw = cloneJsonMap(raw ?? const {});
|
||||
|
||||
final JsonMap raw;
|
||||
|
||||
/// Go-style duration such as `24h` or `1h30m`; empty for a clock rule.
|
||||
String get every => _text(raw['every']);
|
||||
|
||||
/// Distinct 24-hour times such as `09:00`; empty for an interval rule.
|
||||
List<String> get times => _texts(raw['times']);
|
||||
|
||||
/// Empty means every day (written as absent on the wire).
|
||||
List<String> get days => _texts(raw['days']);
|
||||
|
||||
/// Empty or `Local` means the server's timezone.
|
||||
String get timezone => _text(raw['timezone']);
|
||||
|
||||
bool get isClock => times.isNotEmpty;
|
||||
|
||||
JsonMap toJson() => cloneJsonMap(raw);
|
||||
}
|
||||
|
||||
String _text(dynamic value) => value is String ? value : '';
|
||||
|
||||
List<String> _texts(dynamic value) => value is List
|
||||
? [
|
||||
for (final item in value)
|
||||
if (item is String) item,
|
||||
]
|
||||
: const [];
|
||||
@@ -0,0 +1,94 @@
|
||||
# S1a — saved-schedule repository and record
|
||||
|
||||
## What changed
|
||||
|
||||
New, app-only files (no existing feature, shell, transport, `main` or pubspec
|
||||
source edited):
|
||||
|
||||
| File | Lines | Responsibility |
|
||||
| --- | --- | --- |
|
||||
| `lib/features/schedules/data/schedules_repository.dart` | 116 | `list_schedules`, `save_schedule`, `delete_schedule` envelopes and reply checks |
|
||||
| `lib/features/schedules/domain/saved_schedule.dart` | 87 | typed view over one saved run configuration; exact raw record retained |
|
||||
| `lib/features/schedules/domain/schedule_rule.dart` | 41 | interval/clock/timezone/weekday fields of `rule` |
|
||||
| `lib/features/schedules/domain/schedule_json.dart` | 22 | deep JSON copy used by every round trip |
|
||||
| `test/features/schedules/data/schedules_repository_test.dart` | 132 | list/create/update envelopes, unchanged input, CAS revision |
|
||||
| `test/features/schedules/data/schedules_delete_test.dart` | 131 | delete envelope, confirmations, refusals, missing/empty replies |
|
||||
| `test/features/schedules/data/schedules_protocol_bounds_test.dart` | 81 | web-mirrored ID/revision/request-key bounds |
|
||||
| `test/features/schedules/data/saved_schedule_record_test.dart` | 101 | provenance, unknown fields, deep-copy and absent-field behavior |
|
||||
| `test/features/schedules/data/schedule_test_support.dart` | 83 | recording fake gateway and server-shaped fixtures |
|
||||
|
||||
`app/.gitignore` also gained the missing `!/test/**/data/` exception. The root
|
||||
`.gitignore` ignores every `data/` directory, so without it these assigned tests
|
||||
would silently disappear from a fresh checkout. The existing `!/lib/**/data/`
|
||||
exception is for the same reason.
|
||||
|
||||
## Behavior copied from the current web client
|
||||
|
||||
Requests are exactly the ones in `web/src/repository.js`:
|
||||
|
||||
- `list_schedules` with no field, or `pipeline_id` for one pipeline. A positive
|
||||
safe integer is required before sending; `{type:"schedules"}` or
|
||||
`schedules:null` is an empty list, while a reply without `type:"schedules"` is
|
||||
an error, not "no schedules".
|
||||
- `save_schedule` with `schedule` unchanged. A non-empty `request_key` (at most
|
||||
128 characters) is added only for a create retry; updates omit it, as the web
|
||||
editor does. Creation keeps the web sentinel `id: 0` and no revision. Updates
|
||||
send the record read from the server, whose `revision` is the server's
|
||||
compare-and-swap token. The reply is only accepted when it contains
|
||||
`schedule`.
|
||||
- `delete_schedule` with exactly `schedule_id` and `expected_revision`; only
|
||||
`{type:"schedule_deleted", schedule_id:<same id>}` counts as success.
|
||||
|
||||
Server refusals are not wrapped or translated. `ApiGateway` already turns an
|
||||
`error` envelope into `ProtocolError` with the server's text, and the repository
|
||||
lets that object through unchanged (conflict and unknown-command coverage in
|
||||
`server refusals and conflicts propagate verbatim`). The repository has no
|
||||
capability flags, no "not supported" substitution and no local fallback.
|
||||
|
||||
Saved schedules are run configurations, never pipeline definitions. `SavedSchedule`
|
||||
keeps the complete server map, including unknown future nested fields, and
|
||||
exposes pipeline, version, prompt/input, workspace, rule (every/times/days/
|
||||
timezone), enabled, model/stage models, notify mode, write paths/tools, title,
|
||||
output format, due time and timestamps. `toJson()` is a deep copy; `withEnabled`
|
||||
preserves identity, revision and unknowns. Missing identity/revision stays
|
||||
`null` rather than becoming a fabricated `0`. There is no timer execution,
|
||||
polling, rule parsing into due dates or timezone conversion in this slice.
|
||||
|
||||
## Checks actually run
|
||||
|
||||
```
|
||||
flutter pub get
|
||||
dart format lib/features/schedules test/features/schedules # 9 files, 5 changed, then clean
|
||||
flutter test test/features/schedules/data # 18 passed
|
||||
flutter analyze # No issues found! (1.4s)
|
||||
flutter test # 70 passed
|
||||
```
|
||||
|
||||
Focused coverage maps to the requested acceptance:
|
||||
|
||||
- exact `list_schedules`/`save_schedule`/`delete_schedule` bodies recorded by a
|
||||
fake gateway, including `expected_revision` only on delete and no invented
|
||||
create revision/key;
|
||||
- untouched caller record on save; deep equality of returned records with the
|
||||
server reply including unknown top-level/rule/input fields;
|
||||
- update reuses revision 3, accepts server revision 4 and leaves the stale draft
|
||||
at 3; a mismatch is the server's refusal, propagated verbatim;
|
||||
- empty list vs missing/unsupported schedules reply, missing/invalid saved
|
||||
schedule, and delete confirmation for the wrong id/type;
|
||||
- preflight bounds match the web client: pipeline id, schedule id, revision and
|
||||
129-character request keys send nothing; 128 characters is accepted;
|
||||
- no fabricated identity when a reply contains an empty schedule object.
|
||||
|
||||
## Honest limits
|
||||
|
||||
- **No UI or wiring.** There is no schedules screen, editor, pause/delete control
|
||||
or shell registration in this slice; the manager owns later UI integration.
|
||||
No browser interaction or screenshot applies to this nonvisual item.
|
||||
- **No live server used.** All checks use local recording fakes; no production
|
||||
schedule, run or workflow was created, changed or deleted. No polling or
|
||||
scheduler was touched.
|
||||
- **Mobile unverified.** Only web-targeted Flutter tests and analysis ran. No
|
||||
Android/iOS build, emulator, ADB or device was used; the code is pure Dart.
|
||||
- **Not committed.** The stage instruction for this visit forbids commit, push
|
||||
and deploy, so the candidate remains in the `flutter/s1-data` worktree for the
|
||||
manager to inspect and commit. No deployment or preview was performed.
|
||||
@@ -0,0 +1,101 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/schedules/domain/saved_schedule.dart';
|
||||
|
||||
import 'schedule_test_support.dart';
|
||||
|
||||
void main() {
|
||||
test('saved schedule exposes run-configuration provenance', () {
|
||||
final schedule = SavedSchedule(savedRecord());
|
||||
|
||||
expect(schedule.id, 8);
|
||||
expect(schedule.revision, 3);
|
||||
expect(schedule.pipelineId, 4);
|
||||
expect(schedule.version, 2);
|
||||
expect(schedule.name, 'Research batteries');
|
||||
expect(schedule.enabled, isTrue);
|
||||
expect(schedule.prompt, 'Research batteries');
|
||||
expect(schedule.input['custom'], {'nested': 'kept'});
|
||||
expect(schedule.workspace, '/srv/research');
|
||||
expect(schedule.writePaths, ['reports/research.md']);
|
||||
expect(schedule.allowTools, isTrue);
|
||||
expect(schedule.model, 'openai/gpt-5');
|
||||
expect(schedule.stageModels, {'one': 'openai/gpt-5'});
|
||||
expect(schedule.notifyMode, 'off');
|
||||
expect(schedule.title, 'Battery research');
|
||||
expect(schedule.outputFormat, 'markdown');
|
||||
expect(schedule.rule.every, '24h');
|
||||
expect(schedule.rule.days, ['mon', 'wed']);
|
||||
expect(schedule.rule.timezone, 'Europe/London');
|
||||
expect(schedule.rule.isClock, isFalse);
|
||||
expect(schedule.nextDue, '2026-10-22T09:00:00Z');
|
||||
expect(schedule.createdAt, '2026-10-20T09:00:00Z');
|
||||
expect(schedule.updatedAt, '2026-10-21T09:00:00Z');
|
||||
});
|
||||
|
||||
test('unknown fields survive the typed view and pause copy', () {
|
||||
final schedule = SavedSchedule(savedRecord());
|
||||
final paused = schedule.withEnabled(false);
|
||||
|
||||
expect(paused.enabled, isFalse);
|
||||
expect(paused.id, 8);
|
||||
expect(paused.revision, 3);
|
||||
expect(paused.toJson()['future_server_field'], {
|
||||
'nested': [
|
||||
1,
|
||||
2,
|
||||
{'deep': true},
|
||||
],
|
||||
});
|
||||
expect(paused.toJson()['input'], {
|
||||
'prompt': 'Research batteries',
|
||||
'custom': {'nested': 'kept'},
|
||||
});
|
||||
expect(paused.toJson()['rule'], savedRecord()['rule']);
|
||||
|
||||
// The original snapshot is untouched and still enabled.
|
||||
expect(schedule.enabled, isTrue);
|
||||
expect(schedule.revision, 3);
|
||||
});
|
||||
|
||||
test('toJson is a deep copy, not an alias of the server reply', () {
|
||||
final source = savedRecord();
|
||||
final schedule = SavedSchedule(source);
|
||||
|
||||
final first = schedule.toJson();
|
||||
((first['future_server_field'] as Map)['nested'] as List).add('changed');
|
||||
final second = schedule.toJson();
|
||||
expect((second['future_server_field'] as Map)['nested'], [
|
||||
1,
|
||||
2,
|
||||
{'deep': true},
|
||||
]);
|
||||
|
||||
final promptInput = schedule.input;
|
||||
promptInput['custom'] = 'changed';
|
||||
expect(schedule.input['custom'], {'nested': 'kept'});
|
||||
});
|
||||
|
||||
test('missing fields stay absent instead of being fabricated', () {
|
||||
final schedule = SavedSchedule(const {});
|
||||
|
||||
expect(schedule.id, isNull);
|
||||
expect(schedule.revision, isNull);
|
||||
expect(schedule.pipelineId, isNull);
|
||||
expect(schedule.version, isNull);
|
||||
expect(schedule.enabled, isFalse);
|
||||
expect(schedule.prompt, '');
|
||||
expect(schedule.workspace, '');
|
||||
expect(schedule.rule.every, '');
|
||||
expect(schedule.rule.times, isEmpty);
|
||||
expect(schedule.writePaths, isEmpty);
|
||||
expect(schedule.stageModels, isEmpty);
|
||||
expect(schedule.toJson(), isEmpty);
|
||||
});
|
||||
|
||||
test('a fractional revision is not truncated into a false token', () {
|
||||
final schedule = SavedSchedule(const {'id': 8, 'revision': 3.5});
|
||||
|
||||
expect(schedule.id, 8);
|
||||
expect(schedule.revision, isNull);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
|
||||
class RecordedCall {
|
||||
const RecordedCall(this.type, this.fields);
|
||||
final String type;
|
||||
final JsonMap fields;
|
||||
}
|
||||
|
||||
/// Records the exact request built by the repository and replays queued
|
||||
/// replies. Both are deep-copied, so a test can prove the repository neither
|
||||
/// mutated its input nor depended on alias mutation of a reply.
|
||||
class RecordingGateway implements ApiGateway {
|
||||
final calls = <RecordedCall>[];
|
||||
final replies = <JsonMap>[];
|
||||
Object? failure;
|
||||
|
||||
@override
|
||||
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
|
||||
calls.add(RecordedCall(type, deepCopy(fields)));
|
||||
if (failure case final error?) throw error;
|
||||
if (replies.isEmpty) throw StateError('No recorded reply for $type');
|
||||
return deepCopy(replies.removeAt(0));
|
||||
}
|
||||
|
||||
@override
|
||||
Stream<JsonMap> get frames => const Stream.empty();
|
||||
}
|
||||
|
||||
JsonMap deepCopy(JsonMap value) => jsonDecode(jsonEncode(value)) as JsonMap;
|
||||
|
||||
/// A complete server record including fields this client does not interpret
|
||||
/// yet, an unknown nested rule field and unknown input.
|
||||
JsonMap savedRecord() => {
|
||||
'id': 8,
|
||||
'revision': 3,
|
||||
'name': 'Research batteries',
|
||||
'pipeline_id': 4,
|
||||
'version': 2,
|
||||
'enabled': true,
|
||||
'input': {
|
||||
'prompt': 'Research batteries',
|
||||
'custom': {'nested': 'kept'},
|
||||
},
|
||||
'workspace': '/srv/research',
|
||||
'write_paths': ['reports/research.md'],
|
||||
'allow_tools': true,
|
||||
'model': 'openai/gpt-5',
|
||||
'stage_models': {'one': 'openai/gpt-5'},
|
||||
'notify_mode': 'off',
|
||||
'title': 'Battery research',
|
||||
'output_format': 'markdown',
|
||||
'rule': {
|
||||
'every': '24h',
|
||||
'days': ['mon', 'wed'],
|
||||
'timezone': 'Europe/London',
|
||||
'future_rule_field': 'kept',
|
||||
},
|
||||
'next_due': '2026-10-22T09:00:00Z',
|
||||
'created_at': '2026-10-20T09:00:00Z',
|
||||
'updated_at': '2026-10-21T09:00:00Z',
|
||||
'future_server_field': {
|
||||
'nested': [
|
||||
1,
|
||||
2,
|
||||
{'deep': true},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
/// The create form of the record: id 0 is the server's create sentinel and no
|
||||
/// revision has been issued yet.
|
||||
JsonMap createRecord() => {
|
||||
'id': 0,
|
||||
'name': 'Research batteries',
|
||||
'pipeline_id': 4,
|
||||
'version': 2,
|
||||
'enabled': true,
|
||||
'input': {'prompt': 'Research batteries'},
|
||||
'workspace': '/srv/research',
|
||||
'rule': {'every': '24h', 'timezone': 'Europe/London'},
|
||||
};
|
||||
@@ -0,0 +1,131 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/core/transport/connection_state.dart';
|
||||
import 'package:pipelines_app/features/schedules/data/schedules_repository.dart';
|
||||
|
||||
import 'schedule_test_support.dart';
|
||||
|
||||
void main() {
|
||||
test('delete sends the exact ID and expected revision', () async {
|
||||
final gateway = RecordingGateway()
|
||||
..replies.add({'type': 'schedule_deleted', 'schedule_id': 8});
|
||||
final repository = SchedulesRepository(gateway);
|
||||
|
||||
await repository.deleteSchedule(8, 3);
|
||||
|
||||
expect(gateway.calls.single.type, 'delete_schedule');
|
||||
expect(gateway.calls.single.fields, {
|
||||
'schedule_id': 8,
|
||||
'expected_revision': 3,
|
||||
});
|
||||
});
|
||||
|
||||
test('delete refuses a confirmation for anything else', () async {
|
||||
final gateway = RecordingGateway();
|
||||
final repository = SchedulesRepository(gateway);
|
||||
for (final reply in [
|
||||
<String, dynamic>{},
|
||||
{'type': 'pong'},
|
||||
{'type': 'schedule_deleted'},
|
||||
{'type': 'schedule_deleted', 'schedule_id': 9},
|
||||
]) {
|
||||
gateway.replies.add(reply);
|
||||
await expectLater(
|
||||
repository.deleteSchedule(8, 3),
|
||||
throwsA(
|
||||
isA<SchedulesRepositoryException>().having(
|
||||
(error) => error.message,
|
||||
'message',
|
||||
'The server did not confirm deletion of this schedule.',
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('server refusals and conflicts propagate verbatim', () async {
|
||||
final conflict = const ProtocolError(
|
||||
'schedule revision conflict; reload before editing',
|
||||
);
|
||||
final recording = RecordingGateway()..failure = conflict;
|
||||
final conflicting = SchedulesRepository(recording);
|
||||
await expectLater(
|
||||
conflicting.saveSchedule(createRecord()),
|
||||
throwsA(same(conflict)),
|
||||
);
|
||||
await expectLater(
|
||||
conflicting.deleteSchedule(8, 3),
|
||||
throwsA(same(conflict)),
|
||||
);
|
||||
|
||||
final unsupported = const ProtocolError(
|
||||
'unknown message type: list_schedules',
|
||||
);
|
||||
recording.failure = unsupported;
|
||||
await expectLater(
|
||||
conflicting.listSchedules(pipelineId: 4),
|
||||
throwsA(same(unsupported)),
|
||||
);
|
||||
});
|
||||
|
||||
test('missing and empty list replies are different facts', () async {
|
||||
final gateway = RecordingGateway();
|
||||
final repository = SchedulesRepository(gateway);
|
||||
|
||||
gateway.replies.add({'type': 'schedules'});
|
||||
expect(await repository.listSchedules(), isEmpty);
|
||||
|
||||
gateway.replies.add({'type': 'schedules', 'schedules': null});
|
||||
expect(await repository.listSchedules(), isEmpty);
|
||||
|
||||
for (final reply in [
|
||||
<String, dynamic>{},
|
||||
{'type': 'pong'},
|
||||
{'type': 'schedules', 'schedules': <String, dynamic>{}},
|
||||
{
|
||||
'type': 'schedules',
|
||||
'schedules': ['not a record'],
|
||||
},
|
||||
]) {
|
||||
gateway.replies.add(reply);
|
||||
await expectLater(
|
||||
repository.listSchedules(),
|
||||
throwsA(isA<SchedulesRepositoryException>()),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('save requires a saved schedule in the reply', () async {
|
||||
final gateway = RecordingGateway();
|
||||
final repository = SchedulesRepository(gateway);
|
||||
for (final reply in [
|
||||
<String, dynamic>{},
|
||||
{'type': 'schedule'},
|
||||
{'type': 'schedule', 'schedule': null},
|
||||
{'type': 'schedule', 'schedule': 'record'},
|
||||
]) {
|
||||
gateway.replies.add(reply);
|
||||
await expectLater(
|
||||
repository.saveSchedule(createRecord()),
|
||||
throwsA(
|
||||
isA<SchedulesRepositoryException>().having(
|
||||
(error) => error.message,
|
||||
'message',
|
||||
'The server returned no saved schedule.',
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('an empty schedule object is not turned into a fake identity', () async {
|
||||
final gateway = RecordingGateway()
|
||||
..replies.add({'type': 'schedule', 'schedule': <String, dynamic>{}});
|
||||
final repository = SchedulesRepository(gateway);
|
||||
|
||||
final saved = await repository.saveSchedule(createRecord());
|
||||
|
||||
expect(saved.id, isNull);
|
||||
expect(saved.revision, isNull);
|
||||
expect(saved.toJson(), isEmpty);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/schedules/data/schedules_repository.dart';
|
||||
|
||||
import 'schedule_test_support.dart';
|
||||
|
||||
void main() {
|
||||
test(
|
||||
'list rejects non-positive and unsafe pipeline IDs before sending',
|
||||
() async {
|
||||
final gateway = RecordingGateway();
|
||||
final repository = SchedulesRepository(gateway);
|
||||
|
||||
for (final id in [0, -1, 9007199254740992]) {
|
||||
await expectLater(
|
||||
repository.listSchedules(pipelineId: id),
|
||||
throwsA(
|
||||
isA<SchedulesRepositoryException>().having(
|
||||
(error) => error.message,
|
||||
'message',
|
||||
'A positive pipeline ID is required.',
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
expect(gateway.calls, isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'delete rejects an inexact identity or revision before sending',
|
||||
() async {
|
||||
final gateway = RecordingGateway();
|
||||
final repository = SchedulesRepository(gateway);
|
||||
|
||||
for (final pair in [
|
||||
(0, 1),
|
||||
(-1, 1),
|
||||
(8, 0),
|
||||
(8, -1),
|
||||
(8, 9007199254740992),
|
||||
]) {
|
||||
await expectLater(
|
||||
repository.deleteSchedule(pair.$1, pair.$2),
|
||||
throwsA(
|
||||
isA<SchedulesRepositoryException>().having(
|
||||
(error) => error.message,
|
||||
'message',
|
||||
'An exact schedule ID and revision are required.',
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
expect(gateway.calls, isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'request keys are bounded at 128 characters like the web client',
|
||||
() async {
|
||||
final gateway = RecordingGateway();
|
||||
final repository = SchedulesRepository(gateway);
|
||||
|
||||
await expectLater(
|
||||
repository.saveSchedule(createRecord(), requestKey: 'x' * 129),
|
||||
throwsA(
|
||||
isA<SchedulesRepositoryException>().having(
|
||||
(error) => error.message,
|
||||
'message',
|
||||
'Schedule request keys must be strings of at most 128 characters.',
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(gateway.calls, isEmpty);
|
||||
|
||||
final key = 'x' * 128;
|
||||
gateway.replies.add({'type': 'schedule', 'schedule': savedRecord()});
|
||||
await repository.saveSchedule(createRecord(), requestKey: key);
|
||||
expect(gateway.calls.single.fields['request_key'], key);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/schedules/data/schedules_repository.dart';
|
||||
import 'package:pipelines_app/features/schedules/domain/saved_schedule.dart';
|
||||
|
||||
import 'schedule_test_support.dart';
|
||||
|
||||
void main() {
|
||||
test(
|
||||
'lists with the exact web envelope and retains every record field',
|
||||
() async {
|
||||
final record = savedRecord();
|
||||
final gateway = RecordingGateway()
|
||||
..replies.add({
|
||||
'type': 'schedules',
|
||||
'schedules': [record],
|
||||
});
|
||||
final repository = SchedulesRepository(gateway);
|
||||
|
||||
final listed = await repository.listSchedules(pipelineId: 4);
|
||||
|
||||
expect(gateway.calls.single.type, 'list_schedules');
|
||||
expect(gateway.calls.single.fields, {'pipeline_id': 4});
|
||||
expect(listed.single.toJson(), record);
|
||||
expect(listed.single.pipelineId, 4);
|
||||
expect(listed.single.version, 2);
|
||||
expect(listed.single.prompt, 'Research batteries');
|
||||
expect(listed.single.workspace, '/srv/research');
|
||||
expect(listed.single.enabled, isTrue);
|
||||
expect(listed.single.rule.every, '24h');
|
||||
expect(listed.single.rule.days, ['mon', 'wed']);
|
||||
expect(listed.single.rule.timezone, 'Europe/London');
|
||||
expect(listed.single.model, 'openai/gpt-5');
|
||||
expect(listed.single.notifyMode, 'off');
|
||||
expect(listed.single.toJson()['future_server_field'], {
|
||||
'nested': [
|
||||
1,
|
||||
2,
|
||||
{'deep': true},
|
||||
],
|
||||
});
|
||||
|
||||
gateway.replies.add({'type': 'schedules'});
|
||||
await repository.listSchedules();
|
||||
expect(gateway.calls.last.type, 'list_schedules');
|
||||
expect(gateway.calls.last.fields, isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'create sends the web sentinel record without inventing a revision',
|
||||
() async {
|
||||
final create = createRecord();
|
||||
final original = deepCopy(create);
|
||||
final gateway = RecordingGateway()
|
||||
..replies.add({'type': 'schedule', 'schedule': savedRecord()});
|
||||
final repository = SchedulesRepository(gateway);
|
||||
|
||||
final saved = await repository.saveSchedule(create);
|
||||
|
||||
expect(gateway.calls.single.type, 'save_schedule');
|
||||
expect(gateway.calls.single.fields, {'schedule': create});
|
||||
expect(gateway.calls.single.fields.containsKey('request_key'), isFalse);
|
||||
expect(
|
||||
gateway.calls.single.fields.containsKey('expected_revision'),
|
||||
isFalse,
|
||||
);
|
||||
expect(create, original, reason: 'the caller record must be unchanged');
|
||||
expect(saved.id, 8);
|
||||
expect(saved.revision, 3);
|
||||
expect(saved.toJson(), savedRecord());
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'a stable create key is forwarded exactly and blanks are omitted',
|
||||
() async {
|
||||
final create = createRecord();
|
||||
final gateway = RecordingGateway();
|
||||
final repository = SchedulesRepository(gateway);
|
||||
|
||||
gateway.replies.add({'type': 'schedule', 'schedule': savedRecord()});
|
||||
await repository.saveSchedule(
|
||||
create,
|
||||
requestKey: 'schedule:stable-editor-key',
|
||||
);
|
||||
expect(gateway.calls.last.fields, {
|
||||
'schedule': create,
|
||||
'request_key': 'schedule:stable-editor-key',
|
||||
});
|
||||
|
||||
gateway.replies.add({'type': 'schedule', 'schedule': savedRecord()});
|
||||
await repository.saveSchedule(create, requestKey: '');
|
||||
expect(gateway.calls.last.fields, {'schedule': create});
|
||||
},
|
||||
);
|
||||
|
||||
test('update reuses the read revision as the CAS token', () async {
|
||||
final current = SavedSchedule(savedRecord());
|
||||
final paused = current.withEnabled(false);
|
||||
expect(paused.id, 8);
|
||||
expect(paused.revision, 3);
|
||||
expect(paused.toJson()['future_server_field'], isNotNull);
|
||||
|
||||
final gateway = RecordingGateway()
|
||||
..replies.add({
|
||||
'type': 'schedule',
|
||||
'schedule': {...savedRecord(), 'enabled': false, 'revision': 4},
|
||||
});
|
||||
final repository = SchedulesRepository(gateway);
|
||||
|
||||
final updated = await repository.saveSchedule(paused.toJson());
|
||||
|
||||
final body = gateway.calls.single.fields['schedule'] as Map;
|
||||
expect(gateway.calls.single.type, 'save_schedule');
|
||||
expect(gateway.calls.single.fields.containsKey('request_key'), isFalse);
|
||||
expect(
|
||||
gateway.calls.single.fields.containsKey('expected_revision'),
|
||||
isFalse,
|
||||
);
|
||||
expect(body['id'], 8);
|
||||
expect(body['revision'], 3);
|
||||
expect(body['enabled'], isFalse);
|
||||
expect(body['future_server_field'], isNotNull);
|
||||
expect(updated.revision, 4);
|
||||
expect(updated.enabled, isFalse);
|
||||
|
||||
// The stale draft keeps its token: a conflict must not be papered over by
|
||||
// silently adopting the reply revision.
|
||||
expect(current.revision, 3);
|
||||
expect(current.enabled, isTrue);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user