Merge branch 'main' into flutter/schedule-form

This commit is contained in:
2026-10-21 21:54:31 +01:00
9 changed files with 965 additions and 12 deletions
@@ -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, '');
});
}