Show server-queued chat prompts from the server, with Remove

The thread reads the session's queued prompts from the chat_subscribe reply
and chat_queue frames: a reload draws them as Queued after the transcript,
a delivered one enters the transcript as Sent, a refused one becomes Not
sent, and Remove sends chat_unqueue. A prompt the server reports queued is
dropped from the device unsent store; the any-frame queued heuristic is
used only with a server that does not report its queue.
This commit is contained in:
2026-11-01 18:42:10 +00:00
parent e42f9cc031
commit 70cdf985c5
9 changed files with 565 additions and 17 deletions
@@ -223,12 +223,19 @@ class ChatComposerController extends ChangeNotifier {
saved = const [];
}
if (_disposed) return;
final intents = [
final read = [
for (final entry in saved)
if (ChatComposerSend.fromJson(entry) case final intent?)
if (!_stored.any((item) => item.operationId == intent.operationId))
intent,
];
// One the server already reports queued is the server's: its device copy
// is dropped rather than restored.
final intents = [
for (final intent in read)
if (!deliveries.serverHolds(intent.operationId)) intent,
];
if (intents.length != read.length) _persistUnsent();
if (intents.isEmpty) return;
_stored.insertAll(0, intents);
deliveries.restore(intents);
@@ -270,14 +277,17 @@ class ChatComposerController extends ChangeNotifier {
attachments: intent.attachments,
);
if (_disposed) return false;
_queued = reply['chat_queued'] == true;
final queued = reply['chat_queued'] == true;
// Accepted (sent or queued) means the server holds it now: the device
// copy is dropped, and a reload reads a queued prompt from the server.
_forgetStored(intent.operationId);
if (_pending?.operationId == intent.operationId) {
_pending = null;
_composerSendsAccepted++;
}
deliveries.accepted(intent, queued: _queued);
onAccepted?.call(intent, _queued);
deliveries.accepted(intent, queued: queued);
_queued = deliveries.isQueued(intent.operationId) || deliveries.ownQueued;
onAccepted?.call(intent, queued);
_settle(null);
// The accepted intent's stored copy is gone before the send completes.
await _writes;
@@ -362,8 +372,41 @@ class ChatComposerController extends ChangeNotifier {
}
}
/// Follows the server's queue report: a prompt it lists is the server's
/// (any stored device copy is dropped) and shows "Queued"; one that left
/// the queue shows what happened to it.
void applyServerQueue(JsonMap frame) {
if (_disposed) return;
final listed = deliveries.applyServerQueue(frame);
for (final operationId in listed) {
_forgetStored(operationId);
}
final queued = deliveries.ownQueued;
if (queued != _queued) {
_queued = queued;
_notify();
}
}
/// Removes one of the server's queued prompts. A refusal (it was already
/// sent) stays visible as the composer's error.
Future<void> unqueue(Future<void> Function() remove) async {
if (_disposed) return;
_error = null;
_notify();
try {
await remove();
} catch (error) {
if (_disposed) return;
_error = '$error';
_notify();
}
}
void _onFrame(JsonMap envelope) {
if (_disposed || !_queued) return;
// A server that reports its queue moves prompts out of "Queued" itself;
// the any-frame heuristic is only for one that does not.
if (_disposed || !_queued || deliveries.serverQueueKnown) return;
if (envelope['type'] != 'chat_event') return;
final body = envelope['chat_event'];
if (body is! Map || body['session_id'] != sessionId) return;
@@ -66,11 +66,21 @@ class ChatDeliveries extends ChangeNotifier {
}
void sending(ChatComposerSend send) {
_own.add(send.operationId);
_unsent.removeWhere((item) => item.operationId == send.operationId);
_set(send, ChatDelivery.sending);
}
void accepted(ChatComposerSend send, {required bool queued}) {
// The server's queue report may already have moved this prompt on (its
// frame and the reply race on the socket); never step it back.
final current = _states[send.operationId];
if (queued &&
_serverQueueKnown &&
!_serverQueued.contains(send.operationId) &&
current == ChatDelivery.sent) {
return;
}
if (!queued) _latestSent = send.operationId;
_set(send, queued ? ChatDelivery.queued : ChatDelivery.sent);
}
@@ -82,8 +92,105 @@ class ChatDeliveries extends ChangeNotifier {
_set(send, ChatDelivery.failed);
}
/// A queued prompt was admitted: the turn it waited behind moved on.
/// The operation ids the server reported holding in its queue, and the
/// prompts themselves (to draw one the harness refused as "Not sent").
final Set<String> _serverQueued = {};
final Map<String, JsonMap> _serverPrompts = {};
/// Operation ids sent from this composer, so its "Queued" notice reflects
/// only its own prompts, not another device's.
final Set<String> _own = {};
/// Set once the server reported its queue: from then on only its reports
/// move a prompt out of "Queued".
bool _serverQueueKnown = false;
/// Whether one of this composer's own prompts waits in the server's queue.
bool get ownQueued => _own.any(_serverQueued.contains);
/// Whether the server reports its queue (so no local heuristic applies).
bool get serverQueueKnown => _serverQueueKnown;
/// Whether the server reported holding [operationId] in its queue.
bool serverHolds(String operationId) => _serverQueued.contains(operationId);
/// Whether [operationId] is currently drawn as "Queued".
bool isQueued(String operationId) =>
_states[operationId] == ChatDelivery.queued;
/// Adopts the server's queue [frame] (`prompts` plus the change it reports).
/// Every listed prompt is "Queued" — including one this device stored but
/// never saw acknowledged, which is the server's now. One that left the
/// queue was sent, unless the frame says it was removed (forgotten) or the
/// harness refused it ("Not sent", re-sendable when it carried no files).
/// Returns the listed operation ids so their stored copies can be dropped.
Set<String> applyServerQueue(JsonMap frame) {
_serverQueueKnown = true;
final listed = <String>{};
for (final prompt in frame['prompts'] as List? ?? const []) {
if (prompt is! Map) continue;
final operation = '${prompt['operation_id'] ?? ''}';
if (operation.isEmpty) continue;
listed.add(operation);
_states[operation] = ChatDelivery.queued;
for (final key in [prompt['native_message_id'], prompt['message_id']]) {
if (key is String && key.isNotEmpty) {
_operationByNative[key] = operation;
}
}
}
_unsent.removeWhere((item) => listed.contains(item.operationId));
_unverified.removeWhere((item) => listed.contains(item.operationId));
final removed = '${frame['removed'] ?? ''}';
final failed = '${frame['failed'] ?? ''}';
for (final operation in _serverQueued.difference(listed)) {
if (operation == removed) {
_states.remove(operation);
} else if (operation == failed) {
_states[operation] = ChatDelivery.failed;
final prompt = _serverPrompts[operation];
if (prompt != null) {
final attachments = [
for (final part in prompt['attachments'] as List? ?? const [])
if (part is Map) {'name': part['name'], 'mime': part['mime']},
];
final send = ChatComposerSend(
sessionId: '${frame['session_id'] ?? ''}',
text: '${prompt['text'] ?? ''}',
operationId: operation,
nativeMessageId: '${prompt['native_message_id'] ?? ''}',
attachments: attachments,
// Only the server held the files; they cannot be sent again from
// here, so such a message can be discarded but not retried.
attachmentsOmitted: attachments.isNotEmpty,
);
_unsent
..removeWhere((item) => item.operationId == operation)
..add(send);
}
} else if (_states[operation] == ChatDelivery.queued) {
_states[operation] = ChatDelivery.sent;
_latestSent = operation;
}
}
_serverQueued
..clear()
..addAll(listed);
_serverPrompts
..clear()
..addAll({
for (final prompt in frame['prompts'] as List? ?? const [])
if (prompt is Map && listed.contains(prompt['operation_id']))
'${prompt['operation_id']}': Map<String, dynamic>.from(prompt),
});
_notify();
return listed;
}
/// A queued prompt was admitted: the turn it waited behind moved on. Only
/// used with a server that does not report its queue.
void admitQueued() {
if (_serverQueueKnown) return;
var changed = false;
for (final entry in _states.entries.toList()) {
if (entry.value != ChatDelivery.queued) continue;
@@ -14,7 +14,8 @@ String chatDeliveryLabel(ChatDelivery state) => switch (state) {
/// A small muted line under the operator's own bubble saying whether the
/// server has the message. "Not sent" takes the error colour and offers the
/// native Retry (same operation id) and Edit (back into the composer) — or
/// Discard when the stored intent can no longer be sent as it was.
/// Discard when the stored intent can no longer be sent as it was. "Queued"
/// offers Remove, which takes the message off the server's queue.
class ChatDeliveryIndicator extends StatelessWidget {
const ChatDeliveryIndicator({
super.key,
@@ -23,6 +24,7 @@ class ChatDeliveryIndicator extends StatelessWidget {
this.onRetry,
this.onEdit,
this.editLabel = 'Edit',
this.onRemove,
});
final ChatDelivery state;
@@ -31,6 +33,9 @@ class ChatDeliveryIndicator extends StatelessWidget {
final VoidCallback? onEdit;
final String editLabel;
/// Takes a "Queued" message back off the server's queue before it is sent.
final VoidCallback? onRemove;
@override
Widget build(BuildContext context) {
final failed = state == ChatDelivery.failed;
@@ -61,6 +66,8 @@ class ChatDeliveryIndicator extends StatelessWidget {
_action('chat-delivery-retry', 'Retry', onRetry!, style),
if (failed && onEdit != null)
_action('chat-delivery-edit', editLabel, onEdit!, style),
if (state == ChatDelivery.queued && onRemove != null)
_action('chat-delivery-remove', 'Remove', onRemove!, style),
],
),
);
@@ -0,0 +1,55 @@
import '../../../core/api_gateway.dart';
/// The prompts the server holds for one session until its harness finishes
/// the turn in flight, in delivery order.
///
/// The server owns them: they survive this device reloading, closing or
/// losing its connection, so a reloaded thread reads them from the
/// `chat_subscribe` reply and every change from `chat_queue` frames instead of
/// from device storage.
class ChatServerQueue {
List<JsonMap> _prompts = const [];
/// The queued prompts, each `{operation_id, message_id, native_message_id,
/// text, client, attachments}` as the server sent it.
List<JsonMap> get prompts => _prompts;
bool get isEmpty => _prompts.isEmpty;
/// Whether [operationId] is still waiting on the server.
bool holds(String operationId) =>
_prompts.any((prompt) => prompt['operation_id'] == operationId);
/// Adopts one queue body (a reply's or a frame's `chat_queue`) for
/// [sessionId]. Returns false for another session's or an unusable body.
bool apply(String sessionId, Object? body) {
if (body is! Map || '${body['session_id'] ?? ''}' != sessionId) {
return false;
}
_prompts = [
for (final prompt in body['prompts'] as List? ?? const [])
if (prompt is Map && '${prompt['operation_id'] ?? ''}'.isNotEmpty)
Map<String, dynamic>.from(prompt),
];
return true;
}
/// The user message a queued [prompt] draws as, shaped like a transcript
/// message so the same bubble renders it.
static JsonMap message(JsonMap prompt) {
final operation = '${prompt['operation_id'] ?? ''}';
final id = '${prompt['message_id'] ?? ''}';
return {
'id': id.isEmpty ? 'queued-$operation' : id,
'role': 'user',
'operation_id': operation,
'native_message_id': prompt['native_message_id'] ?? '',
'client': prompt['client'],
'parts': [
{'type': 'text', 'text': '${prompt['text'] ?? ''}'},
for (final attachment in prompt['attachments'] as List? ?? const [])
if (attachment is Map) Map<String, dynamic>.from(attachment),
],
};
}
}
@@ -6,6 +6,7 @@ import '../../../core/api_gateway.dart';
import '../data/chat_repository.dart';
import '../domain/chat_sessions.dart';
import '../domain/chat_transcript.dart';
import 'chat_server_queue.dart';
import 'chat_thread_cards.dart';
import 'chat_transcript_cache.dart';
@@ -56,6 +57,11 @@ class ChatThreadController extends ChangeNotifier {
);
StreamSubscription<JsonMap>? _subscription;
final _transcriptChanges = ChangeNotifier();
final ChatServerQueue _queue = ChatServerQueue();
/// Told about every queue body the server sends (the subscribe reply's and
/// each `chat_queue` frame), so delivery states follow the server.
void Function(JsonMap queue)? onQueue;
List<JsonMap> _messages = const [];
bool _running = false;
@@ -100,6 +106,31 @@ class ChatThreadController extends ChangeNotifier {
List<JsonMap> get messages => _messages;
/// The prompts the server still holds for this session, in delivery order.
List<JsonMap> get queuedPrompts => _queue.prompts;
/// The queued prompts not already drawn in the transcript (this device's
/// own optimistic bubble and another device's echo are drawn in place).
/// They follow the transcript, since none has reached the harness yet.
List<JsonMap> get queuedOutsideTranscript => [
for (final prompt in _queue.prompts)
if (!_messages.any(
(message) => message['operation_id'] == prompt['operation_id'],
))
prompt,
];
/// Whether [operationId] is still waiting in the server's queue.
bool isQueued(String operationId) => _queue.holds(operationId);
/// Removes one queued prompt on the server. A refusal (it was already sent)
/// is thrown to the caller; the queue itself only changes from the reply.
Future<void> unqueue(String operationId) async {
final reply = await _repository.unqueue(sessionId, operationId);
if (_disposed) return;
_applyQueue(reply['chat_queue']);
}
/// Usage-only snapshots refresh Info, not the expensive transcript tree.
Listenable get transcriptChanges => _transcriptChanges;
bool get running => _running;
@@ -260,10 +291,11 @@ class ChatThreadController extends ChangeNotifier {
Future<void> _attach({bool force = false}) async {
if (_disposed || (_subscribed && !force)) return;
try {
await _repository.subscribe(sessionId);
final reply = await _repository.subscribe(sessionId);
if (_disposed) return;
_subscribed = true;
_subscriptionError = null;
_applyQueue(reply['chat_queue']);
} catch (error) {
// History stays usable, but the UI must report that live updates failed.
if (_disposed) return;
@@ -272,8 +304,32 @@ class ChatThreadController extends ChangeNotifier {
}
}
/// Adopts the server's queue. A prompt the server removed or could not
/// deliver leaves the transcript: it never reached the harness.
void _applyQueue(Object? body) {
if (!_queue.apply(sessionId, body)) return;
final frame = Map<String, dynamic>.from(body as Map);
for (final key in const ['removed', 'failed']) {
final operation = '${frame[key] ?? ''}';
if (operation.isEmpty) continue;
_messages = [
for (final message in _messages)
if (message['operation_id'] != operation) message,
];
if (_awaitingResponseOperation == operation) {
_awaitingResponseOperation = null;
}
}
onQueue?.call(frame);
_notify();
}
void _onFrame(JsonMap envelope) {
if (_disposed) return;
if (envelope['type'] == 'chat_queue') {
_applyQueue(envelope['chat_queue']);
return;
}
if (envelope['type'] == 'chat_permission') {
final permission = envelope['chat_permission'];
if (permission is! Map) return;
@@ -27,6 +27,7 @@ import 'chat_model_control.dart';
import 'chat_models.dart';
import 'chat_row_keys.dart';
import 'chat_scroll.dart';
import 'chat_server_queue.dart';
import 'chat_thread_controller.dart';
import '../../../ui/adaptive/floating_bar_layout.dart';
import '../../../ui/adaptive/segmented_bar_overlay.dart';
@@ -214,6 +215,13 @@ class _ChatThreadViewState extends State<ChatThreadView> {
controller.transcriptChanges.addListener(
() => _reconcileUnsent(controller),
);
// Delivery states follow the server's queue reports. Read the composer
// when the report arrives: it is not built yet while this one is.
controller.onQueue = (queue) {
if (mounted && identical(controller, _controller)) {
_composer.applyServerQueue(queue);
}
};
unawaited(controller.load());
return controller;
}
@@ -871,6 +879,20 @@ class _ChatThreadViewState extends State<ChatThreadView> {
: null,
),
),
// Messages the server holds queued (one sent before
// a reload, or from another device) follow the
// transcript: none has reached the harness yet.
for (final prompt
in _controller.queuedOutsideTranscript)
Padding(
key: ValueKey<String>(
'chat-queued-${prompt['operation_id']}',
),
padding: const EdgeInsets.symmetric(
horizontal: 16,
),
child: _queuedRow(prompt, cupertino),
),
// Messages the server has not accepted follow the
// transcript until they are retried or edited.
for (final send in _composer.deliveries.unsent)
@@ -1062,10 +1084,11 @@ class _ChatThreadViewState extends State<ChatThreadView> {
child: chips.firstOrNull ?? const SizedBox.shrink(),
);
}
final delivery = kind == 'user' && row['message'] is Map
? _composer.deliveries.stateFor(
Map<String, dynamic>.from(row['message'] as Map),
)
final message = kind == 'user' && row['message'] is Map
? Map<String, dynamic>.from(row['message'] as Map)
: null;
final delivery = message != null
? _composer.deliveries.stateFor(message)
: null;
return ChatMessageView(
row: row,
@@ -1077,12 +1100,39 @@ class _ChatThreadViewState extends State<ChatThreadView> {
state: delivery,
cupertino:
chatControlsStyleOf(context) == ChatControlsStyle.cupertino,
onRemove: _removeAction('${message?['operation_id'] ?? ''}'),
),
],
images: _images,
);
}
/// Remove for a message the server still holds queued, or null.
VoidCallback? _removeAction(String operationId) {
if (operationId.isEmpty || !_controller.isQueued(operationId)) return null;
final controller = _controller;
return () =>
unawaited(_composer.unqueue(() => controller.unqueue(operationId)));
}
/// One prompt the server holds queued that the transcript does not show,
/// as the sender's bubble with "Queued" and its Remove.
Widget _queuedRow(JsonMap prompt, bool cupertino) {
final message = ChatServerQueue.message(prompt);
return ChatMessageView(
row: {'kind': 'user', 'key': message['id'], 'message': message},
textBuilder: chatMarkdownText,
images: _images,
footer: [
ChatDeliveryIndicator(
state: ChatDelivery.queued,
cupertino: cupertino,
onRemove: _removeAction('${prompt['operation_id'] ?? ''}'),
),
],
);
}
/// One message the server has not accepted, as the operator's bubble with
/// "Not sent" and its Retry and Edit.
Widget _unsentRow(ChatComposerSend send, bool cupertino) {
@@ -217,6 +217,14 @@ class ChatRepository {
gateway.call('chat_interrupt', {
'chat_query': {'session_id': sessionId},
});
/// Removes one prompt the server still holds in the session's queue. The
/// reply's `chat_queue` is the queue afterwards; a prompt already handed to
/// the harness is refused.
Future<JsonMap> unqueue(String sessionId, String operationId) =>
gateway.call('chat_unqueue', {
'chat_unqueue': {'session_id': sessionId, 'operation_id': operationId},
});
Future<JsonMap> answerForm(
String sessionId,
String formId,
@@ -0,0 +1,213 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/conversation/chat_composer_send.dart';
import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import 'chat_thread_fixtures.dart';
/// A thread gateway whose server holds [queue] for session `s` and answers
/// `chat_unqueue` by removing the named prompt.
class _Gateway extends FakeChatGateway {
List<JsonMap> queue = [];
final unqueued = <String>[];
String? refuseUnqueue;
_Gateway() {
history = (_) async => chatPage([
chatMessage(
'm1',
'assistant',
parts: [
{'type': 'text', 'id': 'm1#t', 'text': 'Working on it'},
],
),
]);
subscribe = () async => {'chat_queue': queueBody()};
}
JsonMap queueBody({String? delivered, String? removed}) => {
'session_id': 's',
'prompts': queue,
'delivered': ?delivered,
'removed': ?removed,
};
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
if (type == 'chat_unqueue') {
calls.add((type: type, fields: fields));
final body = fields['chat_unqueue'] as JsonMap;
final operation = '${body['operation_id']}';
if (refuseUnqueue != null) throw StateError(refuseUnqueue!);
unqueued.add(operation);
queue = [
for (final prompt in queue)
if (prompt['operation_id'] != operation) prompt,
];
return {'chat_queue': queueBody(removed: operation)};
}
return super.call(type, fields);
}
}
JsonMap _prompt(String operation, String text, {String client = 'Phone'}) => {
'operation_id': operation,
'message_id': 'msg_$operation',
'native_message_id': 'msg_$operation',
'text': text,
'client': client,
};
Future<void> _pump(WidgetTester tester) async {
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
await tester.pump();
}
Future<void> _host(
WidgetTester tester,
_Gateway gateway,
MemoryChatDraftStore drafts, {
bool cupertino = false,
}) async {
final thread = ChatThreadView(
gateway: gateway,
sessionId: 's',
onBack: () {},
drafts: drafts,
newOperationId: () => 'op-new',
);
await tester.pumpWidget(
cupertino
? CupertinoApp(home: CupertinoPageScaffold(child: thread))
: MaterialApp(home: Scaffold(body: thread)),
);
await _pump(tester);
}
Finder _state(String name) => find.byKey(Key('chat-delivery-$name'));
void main() {
for (final cupertino in [false, true]) {
testWidgets('a reload draws the server-queued prompts as Queued '
'($cupertino)', (tester) async {
final gateway = _Gateway()
..queue = [_prompt('op-1', 'First queued'), _prompt('op-2', 'Second')];
addTearDown(gateway.close);
await _host(
tester,
gateway,
MemoryChatDraftStore(),
cupertino: cupertino,
);
expect(find.text('First queued'), findsOneWidget);
expect(find.text('Second'), findsOneWidget);
expect(_state('queued'), findsNWidgets(2));
expect(find.byKey(const Key('chat-delivery-remove')), findsNWidgets(2));
// They follow the transcript: nothing queued has reached the harness.
expect(
tester.getTopLeft(find.text('First queued')).dy,
greaterThan(tester.getTopLeft(find.text('Working on it')).dy),
);
});
}
testWidgets('a delivered queued prompt enters the transcript as Sent', (
tester,
) async {
final gateway = _Gateway()..queue = [_prompt('op-1', 'Do this next')];
addTearDown(gateway.close);
await _host(tester, gateway, MemoryChatDraftStore());
expect(_state('queued'), findsOneWidget);
// The server re-publishes the user turn as it hands it to the harness,
// then reports the queue without it.
gateway.emitEvent({
'session_id': 's',
'kind': 'user',
'message_id': 'msg_op-1',
'operation_id': 'op-1',
'client': 'Phone',
'part': {'type': 'text', 'id': 'usr', 'text': 'Do this next'},
});
gateway.queue = [];
gateway.emitRaw({
'type': 'chat_queue',
'chat_queue': gateway.queueBody(delivered: 'op-1'),
});
await _pump(tester);
expect(find.text('Do this next'), findsOneWidget);
expect(_state('queued'), findsNothing);
expect(_state('sent'), findsOneWidget);
expect(find.byKey(const Key('chat-delivery-remove')), findsNothing);
});
testWidgets('Remove takes a queued prompt off the server queue', (
tester,
) async {
final gateway = _Gateway()
..queue = [_prompt('op-1', 'Keep me'), _prompt('op-2', 'Drop me')];
addTearDown(gateway.close);
await _host(tester, gateway, MemoryChatDraftStore());
final dropRow = find.byKey(const ValueKey<String>('chat-queued-op-2'));
await tester.tap(
find.descendant(
of: dropRow,
matching: find.byKey(const Key('chat-delivery-remove')),
),
);
await _pump(tester);
expect(gateway.unqueued, ['op-2']);
expect(find.text('Drop me'), findsNothing);
expect(find.text('Keep me'), findsOneWidget);
expect(_state('queued'), findsOneWidget);
});
testWidgets('a Remove the server refuses stays visible', (tester) async {
final gateway = _Gateway()
..queue = [_prompt('op-1', 'Too late')]
..refuseUnqueue = 'that message is no longer queued; it was already sent';
addTearDown(gateway.close);
await _host(tester, gateway, MemoryChatDraftStore());
await tester.tap(find.byKey(const Key('chat-delivery-remove')));
await _pump(tester);
expect(find.textContaining('already sent'), findsOneWidget);
expect(find.text('Too late'), findsOneWidget);
});
testWidgets('an own send the server queued is not kept on the device', (
tester,
) async {
final gateway = _Gateway();
addTearDown(gateway.close);
// A previous visit stored the intent but never saw its acknowledgement;
// the server's queue says it holds it.
final stored = const ChatComposerSend(
sessionId: 's',
text: 'Sent before reload',
operationId: 'op-old',
nativeMessageId: 'msg_op-old',
);
final drafts = MemoryChatDraftStore(
unsent: {
's': [stored.toJson()],
},
);
gateway.queue = [_prompt('op-old', 'Sent before reload')];
await _host(tester, gateway, drafts);
await _pump(tester);
expect(find.text('Sent before reload'), findsOneWidget);
expect(_state('queued'), findsOneWidget);
expect(_state('failed'), findsNothing);
expect(drafts.unsentEntries['s'], isNull);
});
}
+14 -5
View File
@@ -5,6 +5,7 @@ import (
"net/http/httptest"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
"time"
@@ -55,12 +56,20 @@ func (s *queueServer) stop() {
func openQueueStore(t *testing.T, path string) *pipeline.Store {
t.Helper()
store, err := pipeline.Open(path)
if err != nil {
t.Fatal(err)
// A just-stopped server's background workers may still be finishing a
// write when the database is reopened; wait out that brief lock.
deadline := time.Now().Add(5 * time.Second)
for {
store, err := pipeline.Open(path)
if err == nil {
t.Cleanup(func() { store.Close() })
return store
}
if !strings.Contains(err.Error(), "SQLITE_BUSY") || time.Now().After(deadline) {
t.Fatal(err)
}
time.Sleep(20 * time.Millisecond)
}
t.Cleanup(func() { store.Close() })
return store
}
func queuedOps(t *testing.T, store *pipeline.Store) []string {