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,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;
}
}