merge(app): land native chat draft and send state controller
This commit is contained in:
@@ -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,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,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, '');
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user