The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Phone: a sent message never sticks at Sending…, and Send never waits (Dee) (#2471)
0xken153d6d67c5c130
diff --git a/mobile/lib/swarm/swarm_conversation.dart b/mobile/lib/swarm/swarm_conversation.dartindex cd4709441..1eb7f8695 100644--- a/mobile/lib/swarm/swarm_conversation.dart+++ b/mobile/lib/swarm/swarm_conversation.dart@@ -6,6 +6,7 @@ import 'package:flutter/foundation.dart';import 'model.dart';import 'prompt_alerts.dart';import 'swarm_chat_cache.dart';+import 'swarm_outbox.dart';import 'swarm_outgoing_files.dart';import 'swarm_reader.dart';import 'swarm_request.dart';@@ -33,6 +34,7 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {this.reader,this.id, {this.uploadTimeout = const Duration(minutes: 2),+ this.sendTimeout = SwarmOutbox.defaultTimeout,this._shown = true,this._heldAt,}) {@@ -56,6 +58,9 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {/// How long an upload may go without a byte moving before the send gives up.final Duration uploadTimeout;+ /// How long a post waits for its answer before it says Not sent.+ final Duration sendTimeout;+/// The files waiting to go with the next post. They stay in memory — a/// large one on disk, in the app's temporary folder — and go when the chat/// closes: only what the person typed is kept, and only while@@ -177,7 +182,7 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {String? error;/// A post is on its way.- bool sending = false;+ bool get sending => _outbox.sending;/// Tells the composer what changed in it — the draft, the message it/// answers, a post leaving it — while this notifier itself tells the@@ -223,18 +228,40 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {/// names them: an agent's is a recipient, a person's a tag.final _mentions = <String, String>{};- /// The post on its way, then — while its answer never came — retried under- /// the same operation id, so the backend runs it once.- Map<String, dynamic>? _pending;+ /// The person's posts on their way, each sent on its own and — while its+ /// answer never came — retried under its own operation id, so the backend+ /// runs it once.+ late final SwarmOutbox _outbox = SwarmOutbox(+ request: reader.request,+ path: '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}/commands',+ timeout: sendTimeout,+ onChanged: () {+ if (!_disposed) _tell();+ },+ onTaken: (post) {+ if (_disposed) return;+ _uploads.forget(post.files);+ if (error != null && error == _postError && _outbox.unconfirmed == null) {+ error = null;+ }+ unawaited(reader.refresh());+ // Shown as sent until the read that brings it back.+ unawaited(loadFromNow());+ },+ onRefused: (post) {+ if (_disposed) return;+ // A refusal of the files themselves sends them up once more; one of+ // the post (a mention, a recipient) leaves them uploaded.+ if (post.refusedBy?.code.contains('ATTACHMENT') ?? false) {+ _uploads.forget(post.files);+ }+ _restore(post);+ error = post.error;+ },+ );- /// What the draft was when [_pending] left it: a refusal puts it back.- ({- String draft,- Map<String, String> mentions,- SuperTabMessage? replyTo,- List<SwarmOutgoingFile> files,- })?- _sent;+ /// The [error] a post's lost answer set: its later answer takes it back.+ String? _postError;SuperTabMessage? _replyingTo;@@ -258,28 +285,19 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {? SwarmChatState.locating: SwarmChatState.loading;- /// A post was sent and not confirmed: [send] retries it.- bool get unconfirmed => _pending != null && !sending;-- /// The post on its way or not confirmed, out of the draft: drawn at the- /// foot of the chat, "Sending…" and then [unconfirmed], until it is read- /// back.- ({String text, String? replyTo, List<SwarmOutgoingFile> files})? get pending {- final command = _pending?['command'] as Map?;- if (command == null) return null;- return (- text: command['text'] as String,- replyTo: command['replyTo'] as String?,- files: _sent?.files ?? const [],- );- }+ /// A post was sent and not confirmed: [send] with nothing typed, or+ /// [retry], sends it again.+ bool get unconfirmed => _outbox.unconfirmed != null;++ /// The posts on their way, taken or not confirmed, oldest first: drawn at+ /// the foot of the chat, each "Sending…", as sent, or "Not sent · Retry",+ /// until a read brings it back.+ List<SwarmPost> get outgoing => _outbox.posts;- /// The composer may post now: there is text or a file, and no post or- /// upload is under way.+ /// The composer may post now: there is text or a file, and no upload is+ /// under way. A post on its way never holds the next one back.bool get canSend =>canPost &&- _pending == null &&- !sending &&!uploading &&(_draft.trim().isNotEmpty || files.files.isNotEmpty);@@ -470,7 +488,7 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {messages.isNotEmpty ||_read ||_draft.isNotEmpty ||- _pending != null ||+ !_outbox.isEmpty ||_replyingTo != null ||error != null;_refused = true;@@ -483,8 +501,7 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {}_threadFiles.clear();_mentions.clear();- _pending = null;- _sent = null;+ _outbox.clear();_replyingTo = null;_reacting.clear();error = null;@@ -510,6 +527,14 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {return locating == null ? reading : Future.wait([locating, reading]);}+ /// What came after the newest shown, read from now on: a read under way+ /// may have been asked before what calls this happened (a post taken), so+ /// a new one follows it.+ Future<void> loadFromNow() async {+ if (_reading case final reading?) await reading;+ return load();+ }+/// The page before the oldest shown.Future<void> loadOlder() => _older(tell: true);@@ -626,6 +651,8 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {byId.values.toList()..sort(superTabMessageOrder),);}+ // A post read back shows as its message, once, whatever its answer.+ changed |= _outbox.settle(messages);if (older || !_read || latest) {final before = SuperTabPage.read(answer['next']);changed |=@@ -667,83 +694,74 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {}/// Posts the draft and its [files], to the agents mentioned in it and as a- /// reply to [replyingTo] — or, while a post is [unconfirmed], sends that one- /// again. The files go up first, one by one, the draft and the files staying- /// in the composer meanwhile; then the post leaves the draft at once, with- /// the files, and shows as [pending] until it is read back. True once the- /// backend took it.+ /// reply to [replyingTo] — or, with nothing typed while a post is+ /// [unconfirmed], sends that one again. The files go up first, one by one,+ /// the draft and the files staying in the composer meanwhile; then the post+ /// leaves the draft at once, with the files, and shows in [outgoing] until+ /// it is read back. A post on its way never holds this one back. True once+ /// the backend took it.Future<bool> send() async {- if (sending || uploading || _disposed || !canPost) return false;- var pending = _pending;- if (pending == null) {- final outgoing = files.files;- if ((_draft.trim().isEmpty && outgoing.isEmpty) || conversation == null) {- return false;- }- final ids = await _uploadAll(outgoing);- if (ids == null || _disposed) return false;- pending = _compose(ids);- if (pending == null) return false;- _sent = (- draft: _draft,- mentions: Map.of(_mentions),- replyTo: _replyingTo,- files: outgoing,- );- _draft = '';- _mentions.clear();- _replyingTo = null;- // Only what goes with this post: more may have been added meanwhile.- for (final file in outgoing) {- files.remove(file);- }+ if (uploading || _disposed || !canPost) return false;+ final outgoing = files.files;+ if (_draft.trim().isEmpty && outgoing.isEmpty) {+ final again = _outbox.unconfirmed;+ return again != null && await retry(again);+ }+ if (conversation == null) return false;+ final ids = await _uploadAll(outgoing);+ if (ids == null || _disposed) return false;+ final body = _compose(ids);+ if (body == null) return false;+ final post = SwarmPost(+ body: body,+ messageId: superTabMessageId(+ tabId: reader.tabId,+ accountId: reader.accountId,+ operationId: body['operationId'] as String,+ ),+ files: outgoing,+ held: (draft: _draft, mentions: Map.of(_mentions), replyTo: _replyingTo),+ );+ _draft = '';+ _mentions.clear();+ _replyingTo = null;+ // Only what goes with this post: more may have been added meanwhile.+ for (final file in outgoing) {+ files.remove(file);}- _pending = pending;- sending = true;error = null;- _tell();- try {- await reader.request(- 'POST',- '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}/commands',- body: pending,- );- } on SuperTabFailure catch (failure) {- // Closed meanwhile (access lost, New message gone): its draft and files- // went with it, and nobody waits on the answer.- if (_disposed) return false;- // A definitive refusal made no change: the text goes back to the draft- // to correct. A lost answer keeps its receipt, so a retry is the same- // post.- final status = failure.statusCode;- if (status >= 400 && status < 500 && status != 408 && status != 429) {- // A refusal of the files themselves sends them up once more; one of- // the post (a mention, a recipient) leaves them uploaded.- if (failure.code.contains('ATTACHMENT')) {- _uploads.forget(_sent?.files ?? const []);- }- _pending = null;- _restore();- }- error = failure.message;- return false;- } catch (_) {- error = 'Your message was not sent. Retry to check it.';+ return _answered(post, await _outbox.add(post));+ }++ /// Sends [post], not confirmed, again under its own operation id: the+ /// backend posts it once however often it goes.+ Future<bool> retry(SwarmPost post) async {+ if (_disposed ||+ !canPost ||+ post.state != SwarmPostState.unconfirmed ||+ !_outbox.posts.contains(post)) {return false;- } finally {- sending = false;- if (!_disposed) _tell();}- if (_disposed) return true;- _uploads.forget(_sent?.files ?? const []);- unawaited(reader.refresh());- // Shown as on its way until the read that brings it back.- await load();- if (_disposed || !identical(_pending, pending)) return true;- _pending = null;- _sent = null;+ error = null;+ return _answered(post, await _outbox.deliver(post));+ }++ /// What [post]'s try came to, said: a refusal puts its text back in the+ /// draft, a lost answer says Not sent.+ bool _answered(SwarmPost post, SwarmPostOutcome outcome) {+ if (_disposed) return outcome == SwarmPostOutcome.taken;+ switch (outcome) {+ case SwarmPostOutcome.taken:+ return true;+ case SwarmPostOutcome.gone:+ // Put back and said by [SwarmOutbox.onRefused].+ case SwarmPostOutcome.refused:+ return false;+ case SwarmPostOutcome.lost:+ error = _postError = post.error;+ }_tell();- return true;+ return false;}/// Uploads each of [outgoing] that has not gone up yet and returns their@@ -1049,18 +1067,24 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {}/// A refused post's text back in the draft, before anything typed since.- void _restore() {- final sent = _sent;- _sent = null;- if (sent == null) return;+ void _restore(SwarmPost post) {+ final sent = post.held;+ if (sent+ is! ({+ String draft,+ Map<String, String> mentions,+ SuperTabMessage? replyTo,+ })) {+ return;+ }_draft = _draft.trim().isEmpty ? sent.draft : '${sent.draft}\n$_draft';_mentions.addAll(sent.mentions);_replyingTo ??= sent.replyTo;- if (sent.files.isNotEmpty) {+ if (post.files.isNotEmpty) {final since = files.files;files..clear()- ..add([...sent.files, ...since]);+ ..add([...post.files, ...since]);}}@@ -1098,6 +1122,7 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {void dispose() {_disposed = true;_uploads.close();+ _outbox.close();for (final box in _threadFiles.values) {box.clear();}diff --git a/mobile/lib/swarm/swarm_conversation_page.dart b/mobile/lib/swarm/swarm_conversation_page.dartindex 500a205e1..c18b8a589 100644--- a/mobile/lib/swarm/swarm_conversation_page.dart+++ b/mobile/lib/swarm/swarm_conversation_page.dart@@ -20,6 +20,7 @@ import 'identity.dart';import 'model.dart';import 'prompt_alerts.dart';import 'swarm_code_block.dart';+import 'swarm_outbox.dart';import 'swarm_post_line.dart';import 'swarm_attach.dart';import 'swarm_buddy.dart';@@ -803,6 +804,15 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>}}+ /// Sends [post], not confirmed, again from where it shows; taken, the+ /// keyboard goes down as after Send.+ Future<void> _retry(SwarmConversation c, SwarmPost post) async {+ final sent = await c.retry(post);+ if (sent && mounted && _conversation == c && c.draft.isEmpty) {+ _focus.unfocus();+ }+ }+void _reply(SwarmConversation c, SuperTabMessage message) {c.replyingTo = message;setState(() => _acting = null);@@ -833,7 +843,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>acting: acting,onTap: onTap,),- pending: (t, text) => _threadPending(c, t, text),+ pending: (t, post) => _threadPending(c, t, post),),),listensForItself: true,@@ -892,25 +902,25 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>);}- /// The person's reply on its way in thread [t].- Widget _threadPending(SwarmConversation c, SwarmThread t, String text) {+ /// The person's reply [post] on its way in thread [t].+ Widget _threadPending(SwarmConversation c, SwarmThread t, SwarmPost post) {final mine = t.messages.reversed.where((m) => !m.fromAgent && m.authorId == c.reader.accountId).firstOrNull;return KeyedSubtree(- key: const ValueKey('swarm-thread-pending'),+ key: ValueKey('swarm-thread-pending-${post.operationId}'),child: _Pending(+ key: const ValueKey('swarm-thread-pending'),name: mine == null ? 'You' : _nameOf(c, mine),look:c.reader.snapshot?.personLook(c.reader.accountId) ??(picture: null, status: null),- text: text,- files: t.pendingFiles,+ text: post.text,+ files: post.files,mentions: _view.value?.mentions ?? SwarmMentions(const []),- // Taken by the backend and not read back yet: still on its way.- sending: t.sending || t.confirmed,+ state: post.state,quote: null,- onSendAgain: () => unawaited(t.send()),+ onSendAgain: () => unawaited(t.retry(post)),),);}@@ -1418,7 +1428,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>) {final state = c.state;if (state == SwarmChatState.lost) return _said(c.error ?? _notOpen);- if (c.stream.isEmpty && c.pending == null) {+ if (c.stream.isEmpty && c.outgoing.isEmpty) {if (state != SwarmChatState.loaded) {// A first read that failed: said under the chat once it is known,// here until then.@@ -1486,14 +1496,15 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>}final entries = _shown;final byId = _byId;- final pending = c.pending;+ // Newest at the foot: the list runs bottom up.+ final pending = c.outgoing.reversed.toList();// A page shorter than the screen never scrolls: look once it is drawn.if (c.hasOlder && !_loadingOlder && !_olderFailed) {WidgetsBinding.instance.addPostFrameCallback((_) {if (mounted) _nearTop();});}- final lead = pending == null ? 0 : 1;+ final lead = pending.length;final latestOwn = c.latestOwn;Widget entry(_Entry entry) {@@ -1702,7 +1713,12 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>// places.findChildIndexCallback: (key) {if (key is! ValueKey<String>) return null;- if (key.value == _pendingKey) return lead == 1 ? 0 : null;+ if (key.value.startsWith(_pendingKey)) {+ final at = pending.indexWhere(+ (p) => '$_pendingKey-${p.operationId}' == key.value,+ );+ return at < 0 ? null : at;+ }if (key.value == _olderKey) {return c.hasOlder ? lead + entries.length : null;}@@ -1711,27 +1727,28 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>},itemBuilder: (context, index) {if (index < lead) {- final reply = pending!.replyTo == null ? null : byId[pending.replyTo];+ final post = pending[index];+ final reply = post.replyTo == null ? null : byId[post.replyTo];final mine = c.messages.reversed.where((m) => !m.fromAgent && m.authorId == c.reader.accountId).firstOrNull;return _Pending(- key: const ValueKey(_pendingKey),+ key: ValueKey('$_pendingKey-${post.operationId}'),name: mine == null ? 'You' : _nameOf(c, mine),look:c.reader.snapshot?.personLook(c.reader.accountId) ??(picture: null, status: null),- text: pending.text,- files: pending.files,+ text: post.text,+ files: post.files,mentions: view.mentions,- sending: c.sending,- quote: pending.replyTo == null+ state: post.state,+ quote: post.replyTo == null? null: SwarmQuote(author: reply == null ? null : _quoted(c, reply),text: reply?.text,),- onSendAgain: () => unawaited(_post(c)),+ onSendAgain: () => unawaited(_retry(c, post)),);}if (index - lead < entries.length) {@@ -1819,8 +1836,8 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>final snapshot = c.reader.snapshot;final query = c.mentionQuery;final replying = c.replyingTo;- // One post at a time: one not confirmed is sent again from where it shows.- // Files alone are a post too.+ // A post on its way never holds the next back; one not confirmed is sent+ // again from where it shows. Files alone are a post too.final canSend = c.canSend;return Container(decoration: BoxDecoration(@@ -2606,7 +2623,8 @@ class _JumpPill extends StatelessWidget {}/// The person's post on its way, with [SwarmPostLine] under it: "Sending…",-/// then — its answer lost — "Not sent · Retry", until it is read back.+/// then — its answer lost — "Not sent · Retry", until it is read back. One the+/// backend took shows as sent, with no line, until the read that brings it.class _Pending extends StatelessWidget {const _Pending({super.key,@@ -2614,7 +2632,7 @@ class _Pending extends StatelessWidget {required this.text,required this.files,required this.mentions,- required this.sending,+ required this.state,required this.quote,required this.onSendAgain,required this.look,@@ -2629,12 +2647,13 @@ class _Pending extends StatelessWidget {/// The person's own face.final SwarmLook look;final SwarmMentions mentions;- final bool sending;+ final SwarmPostState state;final Widget? quote;final VoidCallback onSendAgain;@overrideWidget build(BuildContext context) {+ final sending = state == SwarmPostState.sending;return Padding(key: const ValueKey('swarm-pending'),padding: SwarmMessageFrame.padding(),@@ -2680,10 +2699,11 @@ class _Pending extends StatelessWidget {}),link: null,),- Padding(- padding: const EdgeInsets.only(top: AppSpace.xs),- child: SwarmPostLine(sending: sending, onRetry: onSendAgain),- ),+ if (state != SwarmPostState.confirmed)+ Padding(+ padding: const EdgeInsets.only(top: AppSpace.xs),+ child: SwarmPostLine(sending: sending, onRetry: onSendAgain),+ ),],),);diff --git a/mobile/lib/swarm/swarm_outbox.dart b/mobile/lib/swarm/swarm_outbox.dartnew file mode 100644index 000000000..c04564cbb--- /dev/null+++ b/mobile/lib/swarm/swarm_outbox.dart@@ -0,0 +1,301 @@+import 'dart:async';+import 'dart:convert';++import 'package:cryptography/dart.dart' show DartSha256;++import 'model.dart';+import 'swarm_outgoing_files.dart';+import 'swarm_request.dart';++/// The id the backend gives the message a person sends with receipt+/// [operationId]: `stableId(state.id, actorKey(actor), operationId)`, the+/// first 24 hex of sha256 over the JSON of those parts (backend+/// superTabs/commands.ts `message.send`, model.ts `stableId`).+String superTabMessageId({+ required String tabId,+ required String accountId,+ required String operationId,+}) => const DartSha256()+ .hashSync(+ utf8.encode(jsonEncode([tabId, 'person:$accountId', operationId])),+ )+ .bytes+ .map((b) => b.toRadixString(16).padLeft(2, '0'))+ .join()+ .substring(0, 24);++/// Where one of the person's posts stands until a read brings it back.+enum SwarmPostState {+ /// On its way: "Sending…".+ sending,++ /// Taken by the backend, not read back yet: drawn as sent, with no line.+ confirmed,++ /// Sent with no answer, or none in time: it may or may not have arrived.+ /// "Not sent · Retry" sends it again under the same receipt, so the+ /// backend posts it once.+ unconfirmed,+}++/// One post of the person's on its way, with what the composer held for it.+class SwarmPost {+ SwarmPost({+ required this.body,+ required this.messageId,+ this.files = const [],+ this.held,+ });++ /// `{operationId, command}`: sent as it is on every try.+ final Map<String, dynamic> body;++ /// The message the backend writes for it: its answer's, else worked out+ /// from the receipt, so a read that brings it before the answer finds it.+ String messageId;++ /// The files that went with it, already uploaded.+ final List<SwarmOutgoingFile> files;++ /// What the composer held when it left (draft, mentions, reply): a refusal+ /// puts it back.+ final Object? held;++ SwarmPostState state = SwarmPostState.sending;++ /// Why its last try did not go through.+ String? error;++ /// The backend's refusal, once it refused it.+ SuperTabFailure? refusedBy;++ int _tries = 0;+ Timer? _timer;++ /// A read brought it back.+ bool _arrived = false;++ /// [SwarmOutbox.onTaken] was told.+ bool _told = false;++ String get operationId => body['operationId'] as String;+ Map<String, dynamic> get command => body['command'] as Map<String, dynamic>;+ String get text => command['text'] as String;+ String? get replyTo => command['replyTo'] as String?;+}++/// What became of one try of [SwarmOutbox.deliver].+enum SwarmPostOutcome {+ /// The backend took it, or a read brought it back.+ taken,++ /// The backend refused it: nothing was posted, and it left the outbox.+ refused,++ /// No answer, or none in time: [SwarmPostState.unconfirmed].+ lost,++ /// The outbox was closed or cleared meanwhile: nobody waits on it.+ gone,+}++/// The person's posts on their way in one chat or thread, oldest first (the+/// desktop's outgoing rows). Each is sent on its own: a second post never+/// waits on the first, as in Slack. A post leaves once a read brings back+/// the backend's copy of it ([settle]), even while its answer is still on+/// its way, so it shows once.+class SwarmOutbox {+ SwarmOutbox({+ required this.request,+ required this.path,+ required this.onChanged,+ required this.onTaken,+ required this.onRefused,+ this.timeout = defaultTimeout,+ });++ /// A send through the account's computers can take 30 seconds a computer+ /// (`AppNotifier.swarmRequest`): past this one, the post says Not sent and+ /// may be sent again, while its first answer may still land.+ static const defaultTimeout = Duration(seconds: 40);++ final SwarmRequest request;++ /// Where commands go.+ final String path;++ /// A post was added, changed state or left.+ final void Function() onChanged;++ /// The backend took [post] (on any try, also after its timeout).+ final void Function(SwarmPost post) onTaken;++ /// The backend refused [post] ([SwarmPost.refusedBy]), whenever its answer+ /// came — also after it said Not sent: its text goes back to the box.+ final void Function(SwarmPost post) onRefused;+ final Duration timeout;++ final _posts = <SwarmPost>[];+ bool _closed = false;++ List<SwarmPost> get posts => List.unmodifiable(_posts);++ bool get isEmpty => _posts.isEmpty;++ /// One is on its way.+ bool get sending => _posts.any((p) => p.state == SwarmPostState.sending);++ /// The oldest post that may not have arrived, which Retry sends again.+ SwarmPost? get unconfirmed =>+ _posts.where((p) => p.state == SwarmPostState.unconfirmed).firstOrNull;++ bool _here(SwarmPost post) => !_closed && _posts.contains(post);++ /// Adds [post] and sends it.+ Future<SwarmPostOutcome> add(SwarmPost post) {+ if (_closed) return Future.value(SwarmPostOutcome.gone);+ _posts.add(post);+ return deliver(post);+ }++ /// Sends [post] — again, when it is [SwarmPostState.unconfirmed] — under+ /// its own receipt, so the backend posts it once however often it goes.+ Future<SwarmPostOutcome> deliver(SwarmPost post) {+ if (!_here(post) || post.state == SwarmPostState.confirmed) {+ return Future.value(+ _here(post) ? SwarmPostOutcome.taken : SwarmPostOutcome.gone,+ );+ }+ if (post.state == SwarmPostState.sending && post._tries > 0) {+ return Future.value(SwarmPostOutcome.lost);+ }+ final tries = ++post._tries;+ post+ ..state = SwarmPostState.sending+ ..error = null;+ onChanged();+ final outcome = Completer<SwarmPostOutcome>();+ void end(SwarmPostOutcome value) {+ if (!outcome.isCompleted) outcome.complete(value);+ }++ bool latest() => _here(post) && post._tries == tries;+ post._timer?.cancel();+ post._timer = Timer(timeout, () {+ if (latest() && post.state == SwarmPostState.sending) {+ post+ ..state = SwarmPostState.unconfirmed+ ..error = 'Your message was not sent. Retry to check it.';+ onChanged();+ }+ end(_here(post) ? SwarmPostOutcome.lost : SwarmPostOutcome.gone);+ });+ request('POST', path, body: post.body).then(+ (answer) {+ if (!_here(post)) {+ // A read brought it back meanwhile, or the chat closed.+ if (post._arrived && !_closed) _taken(post);+ end(post._arrived ? SwarmPostOutcome.taken : SwarmPostOutcome.gone);+ return;+ }+ // Any try's answer is the same command's: it is taken.+ post._timer?.cancel();+ if (_idOf(answer) case final id?) post.messageId = id;+ post+ ..state = SwarmPostState.confirmed+ ..error = null;+ _taken(post);+ onChanged();+ end(SwarmPostOutcome.taken);+ },+ onError: (Object failure) {+ if (!_here(post)) {+ end(post._arrived ? SwarmPostOutcome.taken : SwarmPostOutcome.gone);+ return;+ }+ // One taken stays taken, and a later try speaks for the post.+ if (post.state == SwarmPostState.confirmed) {+ end(SwarmPostOutcome.taken);+ return;+ }+ if (!latest()) {+ end(SwarmPostOutcome.lost);+ return;+ }+ post._timer?.cancel();+ // A definitive refusal made no change; a lost answer keeps its+ // receipt, so a retry is the same post.+ if (failure is SuperTabFailure && refusal(failure)) {+ post+ ..error = failure.message+ ..refusedBy = failure;+ _posts.remove(post);+ onRefused(post);+ onChanged();+ end(SwarmPostOutcome.refused);+ return;+ }+ post+ ..state = SwarmPostState.unconfirmed+ ..error = failure is SuperTabFailure+ ? failure.message+ : 'Your message was not sent. Retry to check it.';+ onChanged();+ end(SwarmPostOutcome.lost);+ },+ );+ return outcome.future;+ }++ /// [onTaken], once for [post].+ void _taken(SwarmPost post) {+ if (post._told) return;+ post._told = true;+ onTaken(post);+ }++ /// A refusal that made no change: the backend said no for good.+ static bool refusal(SuperTabFailure failure) {+ final status = failure.statusCode;+ return status >= 400 && status < 500 && status != 408 && status != 429;+ }++ /// The posts that [messages] hold leave, whatever their state: the+ /// backend's copy shows in their place, once. True when one left.+ bool settle(Iterable<SuperTabMessage> messages) {+ if (_posts.isEmpty) return false;+ final ids = {for (final m in messages) m.id};+ var left = false;+ _posts.removeWhere((post) {+ if (!ids.contains(post.messageId)) return false;+ post+ .._arrived = true+ .._timer?.cancel();+ left = true;+ return true;+ });+ return left;+ }++ /// Every post goes, and no answer is waited on: access lost, chat left.+ void clear() {+ for (final post in _posts) {+ post._timer?.cancel();+ }+ _posts.clear();+ }++ void close() {+ clear();+ _closed = true;+ }++ /// The message id in a send's answer (`{result: {messageId}}`).+ static String? _idOf(Object? answer) {+ if (answer is! Map) return null;+ final result = answer['result'];+ if (result is! Map) return null;+ final id = result['messageId'];+ return id is String && id.isNotEmpty ? id : null;+ }+}diff --git a/mobile/lib/swarm/swarm_thread.dart b/mobile/lib/swarm/swarm_thread.dartindex 0cd270853..b40f3cc67 100644--- a/mobile/lib/swarm/swarm_thread.dart+++ b/mobile/lib/swarm/swarm_thread.dart@@ -4,6 +4,7 @@ import 'package:flutter/foundation.dart';import 'model.dart';import 'swarm_conversation.dart';+import 'swarm_outbox.dart';import 'swarm_outgoing_files.dart';import 'swarm_reader.dart';import 'swarm_request.dart';@@ -193,36 +194,56 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {}/// A reply is on its way.- bool sending = false;-- /// The reply on its way, then — while its answer never came — retried- /// under the same operation id, so the backend runs it once.- Map<String, dynamic>? _pending;-- /// What the box held when [_pending] left it: a refusal puts it back.- ({String draft, bool alsoSend, List<SwarmOutgoingFile> files})? _sent;-- /// The reply on its way or not confirmed: drawn under the replies,- /// "Sending…" and then [unconfirmed], until it is read back.- String? get pending => (_pending?['command'] as Map?)?['text'] as String?;+ bool get sending => _outbox.sending;++ /// The person's replies on their way, each sent on its own and — while its+ /// answer never came — retried under its own operation id, so the backend+ /// runs it once.+ late final SwarmOutbox _outbox = SwarmOutbox(+ request: reader.request,+ path: '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}/commands',+ timeout: chat.sendTimeout,+ onChanged: () {+ if (!_disposed) _tell();+ },+ onTaken: (post) {+ if (_disposed) return;+ _uploads.forget(post.files);+ if (error != null && error == _postError && _outbox.unconfirmed == null) {+ error = null;+ }+ unawaited(reader.refresh());+ // Shown as sent until a read brings it back: the chat's, or this one.+ unawaited(chat.loadFromNow());+ },+ onRefused: (post) {+ if (_disposed) return;+ final failure = post.refusedBy!;+ if (_refusedChat(failure)) return;+ // A refusal of the files themselves sends them up once more; one of+ // the reply leaves them uploaded.+ if (failure.code.contains('ATTACHMENT')) _uploads.forget(post.files);+ _restore(post);+ error = post.error;+ },+ );- /// The files that went with [pending].- List<SwarmOutgoingFile> get pendingFiles => _sent?.files ?? const [];+ /// The [error] a reply's lost answer set: its later answer takes it back.+ String? _postError;- /// The backend took the reply on its way, which no read has brought back- /// yet: it stays on its way, and is not sent again.- bool get confirmed => _confirmed;- bool _confirmed = false;+ /// The replies on their way, taken or not confirmed, oldest first: drawn+ /// under the replies, each "Sending…", as sent, or "Not sent · Retry",+ /// until a read brings it back.+ List<SwarmPost> get outgoing => _outbox.posts;- /// A reply was sent and not confirmed: [send] retries it.- bool get unconfirmed => _pending != null && !sending && !_confirmed;+ /// A reply was sent and not confirmed: [send] with nothing typed, or+ /// [retry], sends it again.+ bool get unconfirmed => _outbox.unconfirmed != null;- /// The box may send now: there is text or a file, and no reply or upload- /// is under way.+ /// The box may send now: there is text or a file, and no upload is under+ /// way. A reply on its way never holds the next one back.bool get canSend =>canPost &&- _pending == null &&- !sending &&!uploading &&(_draft.trim().isNotEmpty || files.files.isNotEmpty);@@ -273,7 +294,7 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {_draft.isNotEmpty ||files.files.isNotEmpty ||uploading ||- _pending != null ||+ !_outbox.isEmpty ||error != null;_refused = true;_forget();@@ -282,9 +303,7 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {files.clear();_draft = '';_alsoSend = false;- _pending = null;- _sent = null;- _confirmed = false;+ _outbox.clear();error = null;if (held) _tell();}@@ -299,15 +318,10 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {return true;}- /// A confirmed reply read back shows as its row, no longer on its way.+ /// A reply read back shows as its row, once, no longer on its way —+ /// whatever its answer, which may still be coming.void _settle() {- if (!_confirmed) return;- final id = _pending?['operationId'];- if (!messages.any((m) => m.id == id)) return;- _pending = null;- _sent = null;- _confirmed = false;- _composer.changed();+ if (_outbox.settle(messages)) _composer.changed();}/// Reads the thread: from its newest reply back through [pagesOnOpen]@@ -460,49 +474,48 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {}/// Sends the draft to the thread's root, also to the chat with [alsoSend]- /// — or, while a reply is [unconfirmed], sends that one again. The reply- /// leaves the box at once and shows as [pending] until it is read back.- /// True once the backend took it.+ /// — or, with nothing typed while a reply is [unconfirmed], sends that one+ /// again. The reply leaves the box at once and shows in [outgoing] until it+ /// is read back; one on its way never holds this one back. True once the+ /// backend took it.Future<bool> send() async {- if (sending || uploading || _confirmed || _disposed || !canPost) {- return false;- }+ if (uploading || _disposed || !canPost) return false;// An answer that comes back after the thread closed, or after what it- // held was dropped, changes nothing: no text or files back in a box, no- // read.+ // held was dropped, changes nothing: no text or files back in a box.final epoch = _epoch;bool current() => !_disposed && epoch == _epoch;- var pending = _pending;- if (pending == null) {- final outgoing = files.files;- if ((_draft.trim().isEmpty && outgoing.isEmpty) ||- chat.conversation == null) {- return false;- }- // The files go up first, the draft and the files staying in the box- // meanwhile, as the chat's do.- var ids = const <String>[];- if (outgoing.isNotEmpty) {- error = null;- final up = await _uploads.upload(outgoing);- if (!current()) return false;- if (up.failure case final failure?) {- if (failure is SuperTabFailure && _refusedChat(failure)) {- return false;- }- error = swarmUploadError(failure, outgoing.length);- _tell();+ final outgoing = files.files;+ if (_draft.trim().isEmpty && outgoing.isEmpty) {+ final again = _outbox.unconfirmed;+ return again != null && await retry(again);+ }+ if (chat.conversation == null) return false;+ // The files go up first, the draft and the files staying in the box+ // meanwhile, as the chat's do.+ var ids = const <String>[];+ if (outgoing.isNotEmpty) {+ error = null;+ final up = await _uploads.upload(outgoing);+ if (!current()) return false;+ if (up.failure case final failure?) {+ if (failure is SuperTabFailure && _refusedChat(failure)) {return false;}- ids = up.ids ?? const [];- if (up.ids == null) return false;- }- final text = _draft.trim();- if ((text.isEmpty && ids.isEmpty) || chat.conversation == null) {+ error = swarmUploadError(failure, outgoing.length);+ _tell();return false;}- pending = {- 'operationId': superTabOperationId(),+ ids = up.ids ?? const [];+ if (up.ids == null) return false;+ }+ final text = _draft.trim();+ if ((text.isEmpty && ids.isEmpty) || chat.conversation == null) {+ return false;+ }+ final operationId = superTabOperationId();+ final post = SwarmPost(+ body: {+ 'operationId': operationId,'command': {'type': 'message.send','conversationId': chat.id,@@ -512,74 +525,78 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {if (_alsoSend) 'alsoSend': true,if (ids.isNotEmpty) 'attachmentIds': ids,},- };- _sent = (draft: _draft, alsoSend: _alsoSend, files: outgoing);- _draft = '';- chat.setThreadDraft(root, '');- _alsoSend = false;- // Only what goes with this reply: more may have been added meanwhile.- for (final file in outgoing) {- files.remove(file);- }+ },+ messageId: superTabMessageId(+ tabId: reader.tabId,+ accountId: reader.accountId,+ operationId: operationId,+ ),+ files: outgoing,+ held: (draft: _draft, alsoSend: _alsoSend),+ );+ _draft = '';+ chat.setThreadDraft(root, '');+ _alsoSend = false;+ // Only what goes with this reply: more may have been added meanwhile.+ for (final file in outgoing) {+ files.remove(file);}- _pending = pending;- sending = true;error = null;- _tell();- try {- await reader.request(- 'POST',- '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}/commands',- body: pending,- );- if (current()) _confirmed = true;- } on SuperTabFailure catch (failure) {- if (!current() || _refusedChat(failure)) return false;- // A definitive refusal made no change: the text goes back to the box- // to correct. A lost answer keeps its receipt, so a retry is the same- // reply.- final status = failure.statusCode;- if (status >= 400 && status < 500 && status != 408 && status != 429) {- // A refusal of the files themselves sends them up once more; one of- // the reply leaves them uploaded.- if (failure.code.contains('ATTACHMENT')) _uploads.forget(pendingFiles);- _pending = null;- _restore();- }- error = failure.message;- return false;- } catch (_) {- if (!current()) return false;- error = 'Your reply was not sent. Retry to check it.';+ return _answered(post, await _outbox.add(post), current);+ }++ /// Sends [post], not confirmed, again under its own operation id: the+ /// backend posts it once however often it goes.+ Future<bool> retry(SwarmPost post) async {+ if (_disposed ||+ !canPost ||+ post.state != SwarmPostState.unconfirmed ||+ !_outbox.posts.contains(post)) {return false;- } finally {- sending = false;- if (!_disposed) _tell();}- if (!current()) return true;- _uploads.forget(pendingFiles);- unawaited(reader.refresh());- // On its way until a read brings it back: this one, or the chat's next.- await chat.load();- if (!current() || !identical(_pending, pending)) return true;- _settle();+ final epoch = _epoch;+ error = null;+ return _answered(+ post,+ await _outbox.deliver(post),+ () => !_disposed && epoch == _epoch,+ );+ }++ /// What [post]'s try came to, said: a refusal puts its text back in the+ /// box, a lost answer says Not sent.+ bool _answered(+ SwarmPost post,+ SwarmPostOutcome outcome,+ bool Function() current,+ ) {+ if (!current()) return outcome == SwarmPostOutcome.taken;+ switch (outcome) {+ case SwarmPostOutcome.taken:+ return true;+ case SwarmPostOutcome.gone:+ // Put back and said by [SwarmOutbox.onRefused].+ case SwarmPostOutcome.refused:+ return false;+ case SwarmPostOutcome.lost:+ error = _postError = post.error;+ }_tell();- return true;+ return false;}/// A refused reply's text and files back in the box, before anything/// typed or added since.- void _restore() {- final sent = _sent;- _sent = null;- if (sent == null) return;+ void _restore(SwarmPost post) {+ final sent = post.held;+ if (sent is! ({String draft, bool alsoSend})) return;draft = _draft.trim().isEmpty ? sent.draft : '${sent.draft}\n$_draft';_alsoSend = _alsoSend || sent.alsoSend;- if (sent.files.isNotEmpty) {+ if (post.files.isNotEmpty) {final since = files.files;files..clear()- ..add([...sent.files, ...since]);+ ..add([...post.files, ...since]);}}@@ -595,6 +612,7 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {_epoch++;// An upload on its way stops; the files wait in the chat's box._uploads.close();+ _outbox.close();files.removeListener(_filesChanged);chat.releaseThreadFiles(root, files);chat.removeListener(_chatChanged);diff --git a/mobile/lib/swarm/swarm_thread_page.dart b/mobile/lib/swarm/swarm_thread_page.dartindex 1950283e3..1922a0443 100644--- a/mobile/lib/swarm/swarm_thread_page.dart+++ b/mobile/lib/swarm/swarm_thread_page.dart@@ -16,6 +16,7 @@ import 'swarm_choices.dart';import 'swarm_conversation.dart';import 'swarm_conversation_page.dart';import 'swarm_message_row.dart';+import 'swarm_outbox.dart';import 'swarm_paste.dart';import 'swarm_session.dart';import 'swarm_thread.dart';@@ -31,7 +32,10 @@ typedef SwarmThreadRow = Widget Function(});/// Draws the person's reply on its way: "Sending…", then "Not sent · Retry"-typedef SwarmThreadPending = Widget Function(SwarmThread thread, String text);+typedef SwarmThreadPending = Widget Function(+ SwarmThread thread,+ SwarmPost post,+);/// One thread of a chat, full screen as Slack Mobile opens one: its root at/// the top, "N replies", its replies, and a reply box at the foot with Also@@ -366,7 +370,7 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {}final replies = t.replies;final count = t.count;- final pending = t.pending;+ final pending = t.outgoing;Widget row(SuperTabMessage m, {required bool grouped}) {final built = widget.row(t,@@ -447,7 +451,7 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {replies[index - 1].authorId == reply.authorId &&replies[index - 1].fromAgent == reply.fromAgent,),- if (pending != null) widget.pending(t, pending),+ for (final post in pending) widget.pending(t, post),],);}@@ -464,7 +468,7 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {// The first read's failure is said in the body, with Try again.if (error != null &&error != t.readError &&- (t.rootMessage != null || t.pending != null))+ (t.rootMessage != null || t.outgoing.isNotEmpty))Padding(padding: const EdgeInsets.fromLTRB(AppSpace.screenInset,@@ -499,9 +503,8 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {/// what is typed, then Also send, the + and a round Send (the desktop's/// thread composer).Widget _box(SwarmThread t, Tty tty) {+ // A reply on its way never holds the box: the next is typed meanwhile.final canSend = t.canSend;- // A reply not confirmed is sent again from where it shows.- final writable = !t.sending && t.pending == null;final canAttach = !t.uploading && t.files.room > 0;return Container(key: const ValueKey('swarm-thread-box'),@@ -555,7 +558,7 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {child: _AlsoSend(label: t.alsoSendLabel,value: t.alsoSend,- onChanged: writable ? (on) => t.alsoSend = on : null,+ onChanged: (on) => t.alsoSend = on,),),if (swarmSendsFiles)diff --git a/mobile/test/swarm/desktop_parity_test.dart b/mobile/test/swarm/desktop_parity_test.dartindex f3e947a04..b01e834ba 100644--- a/mobile/test/swarm/desktop_parity_test.dart+++ b/mobile/test/swarm/desktop_parity_test.dart@@ -71,6 +71,20 @@ void main() {},);+ test('the phone names a sent message as the desktop does', () {+ // The phone matches a post to its row by this id (swarm_outbox.dart); a+ // drift shows a second copy that never leaves (Dee, 11-01).+ final function = RegExp(+ r'String superTabMessageId\(\{[\s\S]*?\.substring\(0, 24\);',+ );+ String of(String path) =>+ function.firstMatch(File(path).readAsStringSync())!.group(0)!;+ expect(+ of('lib/swarm/swarm_outbox.dart'),+ of('../desktop/lib/super_tabs/controller.dart'),+ );+ });+for (final MapEntry(key: phone, value: desktop) in _copies.entries) {test("$phone matches the desktop's $desktop", () {final source = File('../desktop/$desktop');diff --git a/mobile/test/swarm/swarm_chat_test.dart b/mobile/test/swarm/swarm_chat_test.dartindex adabdb3dd..ceb39b480 100644--- a/mobile/test/swarm/swarm_chat_test.dart+++ b/mobile/test/swarm/swarm_chat_test.dart@@ -1037,7 +1037,11 @@ void main() {'sent once read back', (tester) async {final fake = backend([message('m1', 1)]);final taken = Completer<Object?>();- fake.routes[commands] = (_) => taken.future;+ String? receipt;+ fake.routes[commands] = (body) {+ receipt = body!['operationId'] as String;+ return taken.future;+ };await pump(tester, fake);await tester.enterText(find.byType(TextField), 'On it');@@ -1058,16 +1062,129 @@ void main() {greaterThan(tester.getBottomLeft(find.text('On it')).dy),);+ final id = sentId(receipt!);fake.routes['$messages?after=1'] = (_) => {- 'messages': [message('m2', 2, author: me, text: 'On it', minute: 5)],+ 'messages': [message(id, 2, author: me, text: 'On it', minute: 5)],'next': null,};taken.complete({'result': <String, dynamic>{}});await tester.pumpAndSettle();expect(key('swarm-pending'), findsNothing);- expect(key('swarm-message-m2'), findsOneWidget);+ expect(key('swarm-message-$id'), findsOneWidget);+ expect(find.text('On it'), findsOneWidget);+ });++ bool sendable(WidgetTester tester) =>+ tester.widget<SwarmRoundButton>(key('swarm-send')).onTap != null;++ List<String> receipts(FakeSwarm fake) => [+ for (final call in fake.calls)+ if (call.method == 'POST' && call.path == commands)+ call.body!['operationId'] as String,+ ];++ testWidgets('a post read back while its answer is still on its way shows '+ 'once, and Send is free for the next (Dee, 11-01)', (tester) async {+ final fake = backend([message('m1', 1)]);+ final taken = Completer<Object?>();+ fake.routes[commands] = (_) => taken.future;+ final host = await pump(tester, fake);++ await tester.enterText(find.byType(TextField), 'On it');+ await tester.pump();+ await tester.tap(key('swarm-send'));+ await tester.pump();+ expect(find.text('Sending…'), findsOneWidget);++ // The computer passing it on is slow to answer; the Swarm's next read+ // already has it.+ final id = sentId(receipts(fake).single);+ fake.routes['$messages?after=1'] = (_) => {+ 'messages': [message(id, 2, author: me, text: 'On it', minute: 5)],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(+ cursor: 'c3',+ lastChangedAt: 200,+ derived: {'decisionsWaiting': 0},+ groups: [+ part(+ 'g1',+ 9,+ groupData(+ 'g1',+ title: 'Fix login',+ agentIds: ['agent-lead', 'agent-builder'],+ status: 'working',+ lastMessageSequence: 2,+ ),+ ),+ ],+ );+ await host.session!.inbox.reader(tab)!.refresh();+ for (var i = 0; i < 5; i++) {+ await tester.pump();+ }++ expect(key('swarm-message-$id'), findsOneWidget);+ expect(find.text('On it'), findsOneWidget, reason: 'no second copy');+ expect(key('swarm-pending'), findsNothing);+ await tester.enterText(find.byType(TextField), 'And another');+ await tester.pump();+ expect(sendable(tester), isTrue);++ taken.complete({+ 'result': {'messageId': id},+ });+ await tester.pumpAndSettle();expect(find.text('On it'), findsOneWidget);+ expect(key('swarm-pending'), findsNothing);+ });++ testWidgets('a second post goes while the first is still on its way; one '+ 'with no answer in time says Not sent, and Retry sends it under the '+ 'same receipt, so the backend posts it once', (tester) async {+ final fake = backend([message('m1', 1)]);+ final answers = <String, Completer<Object?>>{};+ fake.routes[commands] = (body) =>+ (answers[body!['operationId'] as String] ??= Completer()).future;+ await pump(tester, fake);++ await tester.enterText(find.byType(TextField), 'One');+ await tester.pump();+ await tester.tap(key('swarm-send'));+ await tester.pump();+ await tester.enterText(find.byType(TextField), 'Two');+ await tester.pump();++ expect(sendable(tester), isTrue, reason: 'never waits on the first');+ await tester.tap(key('swarm-send'));+ await tester.pump();++ expect(find.text('Sending…'), findsNWidgets(2));+ final [one, two] = receipts(fake);+ expect(one, isNot(two));++ // Two is taken; One's answer never comes.+ answers[two]!.complete({+ 'result': {'messageId': sentId(two)},+ });+ await tester.pump();+ await tester.pump(const Duration(seconds: 41));+ await tester.pump();++ expect(find.text('Not sent'), findsOneWidget);+ expect(find.text('Sending…'), findsNothing);++ await tester.tap(key('swarm-resend-post'));+ await tester.pump();+ answers[one]!.complete({'result': <String, dynamic>{}});+ await tester.pumpAndSettle();++ expect(receipts(fake), [one, two, one]);+ expect(answers.keys, [one, two], reason: 'one post per receipt');+ expect(find.text('Not sent'), findsNothing);});testWidgets('a post lost to an unknown failure says to Retry, the word '@@ -1998,8 +2115,9 @@ void main() {/// River's question with two replies in its thread, Nova's only there/// and Nova's also sent to the chat; then a message of Nova's own. A- /// reply sent comes back in the page under its operation id, as the- /// backend writes it, and on the line; in both when also sent.+ /// reply sent comes back in the page under the id the backend gives it+ /// (a hash of its receipt, never the receipt), and on the line; in both+ /// when also sent.FakeSwarm threaded({List<Map<String, dynamic>>? members}) {final page = [message('m1', 1, author: 'agent-lead', text: root, thread: 'm1'),@@ -2041,7 +2159,7 @@ void main() {final command = body!['command'] as Map<String, dynamic>;page.add(message(- body['operationId'] as String,+ sentId(body['operationId'] as String),5,author: me,text: command['text'] as String,@@ -2337,7 +2455,89 @@ void main() {.lastWhere((call) => call.path == commands).body!['operationId'];expect(find.text('Ship it as drawn.'), findsOneWidget);- expect(key('swarm-replied-in-thread-$sent'), findsOneWidget);+ expect(key('swarm-replied-in-thread-${sentId(sent)}'), findsOneWidget);+ });++ bool sendable(WidgetTester tester, String button) =>+ tester.widget<SwarmRoundButton>(key(button)).onTap != null;++ testWidgets('a reply read back under the id the backend gives it shows '+ 'once, and Send works for the next reply (Dee, 11-01)', (tester) async {+ final fake = threaded();+ await pump(tester, fake);+ await tester.tap(key('swarm-thread-line-m1'));+ await tester.pumpAndSettle();++ const first = 'why do we need the 13mm floor?';+ await tester.enterText(key('swarm-thread-field'), first);+ await tester.pump();+ await tester.tap(key('swarm-thread-send'));+ await tester.pumpAndSettle();++ expect(inThread(first), findsOneWidget, reason: 'no second copy');+ expect(key('swarm-thread-pending'), findsNothing);+ expect(find.text('Sending…'), findsNothing);++ await tester.enterText(key('swarm-thread-field'), 'and the 2mm lip?');+ await tester.pump();+ expect(sendable(tester, 'swarm-thread-send'), isTrue);+ await tester.tap(key('swarm-thread-send'));+ await tester.pumpAndSettle();++ expect(fake.commands, hasLength(2));+ expect(inThread('and the 2mm lip?'), findsOneWidget);+ expect(key('swarm-thread-pending'), findsNothing);+ });++ testWidgets('a second reply goes while the first is still on its way, '+ 'each with its own Sending…, and each shows once when taken', (+ tester,+ ) async {+ final fake = threaded();+ final write = fake.routes[commands]!;+ final answers = <Completer<void>>[];+ fake.routes[commands] = (body) {+ final answer = Completer<void>();+ answers.add(answer);+ return answer.future.then((_) => write(body));+ };+ await pump(tester, fake);+ await tester.tap(key('swarm-thread-line-m1'));+ await tester.pumpAndSettle();++ await tester.enterText(key('swarm-thread-field'), 'One');+ await tester.pump();+ await tester.tap(key('swarm-thread-send'));+ await tester.pump();+ await tester.enterText(key('swarm-thread-field'), 'Two');+ await tester.pump();++ expect(sendable(tester, 'swarm-thread-send'), isTrue);+ await tester.tap(key('swarm-thread-send'));+ await tester.pump();++ expect(answers, hasLength(2));+ expect(+ find.descendant(+ of: key('swarm-thread-messages'),+ matching: find.text('Sending…'),+ ),+ findsNWidgets(2),+ );+ final receipts = {+ for (final call in fake.calls)+ if (call.path == commands) call.body!['operationId'],+ };+ expect(receipts, hasLength(2), reason: 'two posts, two receipts');++ for (final answer in answers) {+ answer.complete();+ }+ await tester.pumpAndSettle();++ expect(inThread('One'), findsOneWidget);+ expect(inThread('Two'), findsOneWidget);+ expect(key('swarm-thread-pending'), findsNothing);});testWidgets('a notification of a reply only in its thread opens the 'diff --git a/mobile/test/swarm/swarm_conversation_files_test.dart b/mobile/test/swarm/swarm_conversation_files_test.dartindex c9464dc72..ec4f64b63 100644--- a/mobile/test/swarm/swarm_conversation_files_test.dart+++ b/mobile/test/swarm/swarm_conversation_files_test.dart@@ -123,7 +123,11 @@ void main() {'read back', () async {final r = rig();final taken = Completer<Object?>();- r.swarm.routes[commands] = (_) => taken.future;+ String? receipt;+ r.swarm.routes[commands] = (body) {+ receipt = body!['operationId'] as String;+ return taken.future;+ };final c = await open(r.reader);c.files.add([file('a.jpg')]);@@ -131,10 +135,24 @@ void main() {await settle();expect(c.files.files, isEmpty);- expect([for (final f in c.pending!.files) f.name], ['a.jpg']);+ expect([for (final f in c.outgoing.single.files) f.name], ['a.jpg']);+ r.swarm.routes[messages] = (_) => {+ 'messages': [+ {+ 'id': sentId(receipt!),+ 'conversationId': 'g1',+ 'text': '',+ 'sequence': 1,+ 'author': {'kind': 'person', 'id': me, 'name': 'Me'},+ 'createdAt': '2026-10-27T01:00:00.000Z',+ },+ ],+ 'next': null,+ };taken.complete({'result': <String, dynamic>{}});expect(await sending, isTrue);- expect(c.pending, isNull);+ await settle();+ expect(c.outgoing, isEmpty);});test('a failed upload keeps the draft and the files, sends nothing, and '@@ -156,7 +174,7 @@ void main() {expect([for (final f in c.files.files) f.name], ['a.jpg', 'b.jpg']);expect(r.swarm.commands, isEmpty);expect(c.uploading, isFalse);- expect(c.pending, isNull);+ expect(c.outgoing, isEmpty);});test('an upload that fails for any other reason says so plainly', () async {@@ -384,7 +402,7 @@ void main() {final sending = c.send();await settle();- expect(c.pending, isNotNull, reason: 'the post is out');+ expect(c.outgoing, isNotEmpty, reason: 'the post is out');c.dispose();answer.completeError(const SuperTabFailure('FORBIDDEN', 'No access.', statusCode: 403),@@ -433,7 +451,7 @@ void main() {expect(going.cancel.isCancelled, isTrue);expect(await sending, isFalse);expect(r.swarm.commands, isEmpty);- expect(c.pending, isNull);+ expect(c.outgoing, isEmpty);expect(c.files.files, isEmpty);});diff --git a/mobile/test/swarm/swarm_conversation_test.dart b/mobile/test/swarm/swarm_conversation_test.dartindex 08a7c8085..e1e19e2b5 100644--- a/mobile/test/swarm/swarm_conversation_test.dart+++ b/mobile/test/swarm/swarm_conversation_test.dart@@ -3,6 +3,7 @@ import 'dart:async';import 'package:flutter_test/flutter_test.dart';import 'package:harness_mobile/swarm/model.dart';import 'package:harness_mobile/swarm/swarm_conversation.dart';+import 'package:harness_mobile/swarm/swarm_outbox.dart';import 'package:harness_mobile/swarm/swarm_read_marks.dart';import 'package:harness_mobile/swarm/swarm_reader.dart';import 'package:harness_mobile/swarm/swarm_request.dart';@@ -343,7 +344,11 @@ void main() {final r = rig();r.swarm.routes[messages] = (_) => {'messages': <Object>[], 'next': null};final taken = Completer<Object?>();- r.swarm.routes['/api/super-tabs/$tab/commands'] = (_) => taken.future;+ String? receipt;+ r.swarm.routes['/api/super-tabs/$tab/commands'] = (body) {+ receipt = body!['operationId'] as String;+ return taken.future;+ };final c = await open(r.reader);c.draft = 'On my way';@@ -351,19 +356,26 @@ void main() {await settle();expect(c.draft, isEmpty, reason: 'the field is free at once');- expect(c.pending?.text, 'On my way');+ expect(c.outgoing.firstOrNull?.text, 'On my way');expect(c.sending, isTrue);r.swarm.routes[messages] = (_) => {'messages': [- message('m9', 3, text: 'On my way', authorId: me, fromAgent: false),+ message(+ sentId(receipt!),+ 3,+ text: 'On my way',+ authorId: me,+ fromAgent: false,+ ),],'next': null,};taken.complete({'result': <String, dynamic>{}});expect(await sent, isTrue);+ await settle();- expect(c.pending, isNull);+ expect(c.outgoing, isEmpty);expect([for (final m in c.messages) m.text], ['On my way']);});@@ -378,7 +390,7 @@ void main() {c.draft = 'hi';expect(await c.send(), isFalse);- expect(c.pending?.text, 'hi');+ expect(c.outgoing.firstOrNull?.text, 'hi');expect(c.sending, isFalse);expect(c.unconfirmed, isTrue);expect(c.draft, isEmpty);@@ -406,7 +418,7 @@ void main() {expect(await c.send(), isFalse);- expect(c.pending, isNull);+ expect(c.outgoing, isEmpty);expect(c.draft, '@Nova please');expect(c.replyingTo?.id, 'm1');expect(c.error, 'This message is too long.');@@ -1542,4 +1554,267 @@ void main() {expect(r.swarm.paths.where((p) => p.endsWith('/read')), isEmpty);});});++ group('posts on their way (Dee, 11-01)', () {+ const commands = '/api/super-tabs/$tab/commands';++ /// Chat g1, read, with nothing in it; its posts wait [timeout] for an+ /// answer.+ Future<({FakeSwarm swarm, SwarmReader reader, SwarmConversation c})> chat({+ Duration timeout = SwarmOutbox.defaultTimeout,+ }) async {+ final r = rig();+ r.swarm.routes[messages] = (_) => {'messages': <Object>[], 'next': null};+ await r.reader.refresh();+ final c = SwarmConversation(r.reader, 'g1', sendTimeout: timeout);+ addTearDown(c.dispose);+ await c.load();+ return (swarm: r.swarm, reader: r.reader, c: c);+ }++ /// The bodies [swarm] was sent, by receipt, each answered by hand.+ Map<String, Completer<Object?>> held(FakeSwarm swarm) {+ final answers = <String, Completer<Object?>>{};+ swarm.routes[commands] = (body) =>+ (answers[body!['operationId'] as String] ??= Completer()).future;+ return answers;+ }++ Map<String, dynamic> mine(String id, int sequence, String text) =>+ message(id, sequence, text: text, authorId: me, fromAgent: false);++ test(+ 'a read that brings the post back under the id the backend gives it '+ 'takes its copy away at once, though its answer is still coming',+ () async {+ final r = await chat();+ final answers = held(r.swarm);+ r.c.draft = 'On it';+ final sending = r.c.send();+ await settle();+ final receipt = answers.keys.single;+ expect(r.c.outgoing.single.messageId, sentId(receipt));++ r.swarm.routes[messages] = (_) => {+ 'messages': [mine(sentId(receipt), 3, 'On it')],+ 'next': null,+ };+ await r.c.load();++ expect(r.c.outgoing, isEmpty, reason: 'shown once, as its message');+ expect(r.c.sending, isFalse);+ answers[receipt]!.complete({'result': <String, dynamic>{}});+ expect(await sending, isTrue);+ expect(r.c.outgoing, isEmpty);+ expect(r.c.error, isNull);+ },+ );++ test('the id in the answer is the one looked for', () async {+ final r = await chat();+ r.swarm.routes[commands] = (_) => {+ 'result': {'messageId': 'server-m7'},+ };+ r.c.draft = 'On it';++ expect(await r.c.send(), isTrue);+ expect(r.c.outgoing.single.messageId, 'server-m7');+ expect(r.c.outgoing.single.state, SwarmPostState.confirmed);++ r.swarm.routes[messages] = (_) => {+ 'messages': [mine('server-m7', 3, 'On it')],+ 'next': null,+ };+ await r.c.load();+ expect(r.c.outgoing, isEmpty);+ });++ test('a second post goes while the first is on its way, under its own '+ 'receipt, and each leaves when it is read back', () async {+ final r = await chat();+ final answers = held(r.swarm);+ r.c.draft = 'One';+ final one = r.c.send();+ await settle();+ r.c.draft = 'Two';+ expect(r.c.canSend, isTrue, reason: 'never waits on the first');+ final two = r.c.send();+ await settle();++ final [first, second] = answers.keys.toList();+ expect(first, isNot(second));+ expect([for (final p in r.c.outgoing) p.text], ['One', 'Two']);+ expect(+ r.c.outgoing.every((p) => p.state == SwarmPostState.sending),+ isTrue,+ );++ r.swarm.routes[messages] = (_) => {+ 'messages': [mine(sentId(second), 3, 'Two')],+ 'next': null,+ };+ answers[second]!.complete({'result': <String, dynamic>{}});+ expect(await two, isTrue);+ await settle();+ expect([for (final p in r.c.outgoing) p.text], ['One']);++ r.swarm.routes[messages] = (_) => {+ 'messages': [+ mine(sentId(second), 3, 'Two'),+ mine(sentId(first), 4, 'One'),+ ],+ 'next': null,+ };+ answers[first]!.complete({'result': <String, dynamic>{}});+ expect(await one, isTrue);+ await settle();+ expect(r.c.outgoing, isEmpty);+ });++ test('no answer in time says Not sent; Retry sends the same receipt, and '+ 'the first answer landing late still counts', () async {+ final r = await chat(timeout: const Duration(milliseconds: 20));+ final answers = held(r.swarm);+ r.c.draft = 'Once only';++ expect(await r.c.send(), isFalse);+ final post = r.c.outgoing.single;+ expect(post.state, SwarmPostState.unconfirmed);+ expect(r.c.unconfirmed, isTrue);+ expect(r.c.error, contains('not sent'));+ expect(r.c.canSend, isFalse, reason: 'the field is empty');+ r.c.draft = 'Meanwhile';+ expect(r.c.canSend, isTrue, reason: 'a lost post holds nothing back');+ r.c.draft = '';++ final again = r.c.retry(post);+ await settle();+ final posts = [+ for (final call in r.swarm.calls)+ if (call.path == commands) call.body!['operationId'],+ ];+ expect(posts, hasLength(2));+ expect(posts.toSet(), hasLength(1), reason: 'one post, one receipt');+ // Both tries are one command: its one answer answers both.+ answers.values.single.complete({'result': <String, dynamic>{}});+ expect(await again, isTrue);+ expect(post.state, SwarmPostState.confirmed);+ expect(r.c.error, isNull);+ });++ test(+ 'a refusal that lands after Not sent still puts the text back',+ () async {+ final r = await chat(timeout: const Duration(milliseconds: 20));+ final answers = held(r.swarm);+ r.c.draft = 'Too long';++ expect(await r.c.send(), isFalse);+ expect(r.c.outgoing.single.state, SwarmPostState.unconfirmed);+ expect(r.c.draft, isEmpty);++ answers.values.single.completeError(+ const SuperTabFailure('TOO_LONG', 'Too long.', statusCode: 400),+ );+ await settle();+ expect(r.c.outgoing, isEmpty);+ expect(r.c.draft, 'Too long');+ expect(r.c.error, 'Too long.');+ },+ );++ test('a refused post goes back to the draft while another stays on its '+ 'way', () async {+ final r = await chat();+ final answers = held(r.swarm);+ r.c.draft = 'Too long';+ final refused = r.c.send();+ await settle();+ r.c.draft = 'Fine';+ final fine = r.c.send();+ await settle();++ final [first, _] = answers.keys.toList();+ answers[first]!.completeError(+ const SuperTabFailure('TOO_LONG', 'Too long.', statusCode: 400),+ );+ expect(await refused, isFalse);++ expect(r.c.draft, 'Too long');+ expect(r.c.error, 'Too long.');+ expect([for (final p in r.c.outgoing) p.text], ['Fine']);+ answers.values.last.complete({'result': <String, dynamic>{}});+ expect(await fine, isTrue);+ });++ test('access lost while posts are on their way drops them, and their '+ 'answers change nothing', () async {+ final r = await chat();+ final answers = held(r.swarm);+ r.c.draft = 'Secret plan';+ final sending = r.c.send();+ await settle();+ expect(+ await r.c.retry(r.c.outgoing.single),+ isFalse,+ reason: 'one on its way is not sent again',+ );+ expect(r.c.error, isNull);++ r.reader.revoke();+ await settle();+ expect(r.c.outgoing, isEmpty);+ expect(r.c.draft, isEmpty);++ answers.values.single.completeError(+ const SuperTabFailure('TOO_LONG', 'Too long.', statusCode: 400),+ );+ expect(await sending, isFalse);+ expect(r.c.draft, isEmpty, reason: 'nothing put back');+ expect(r.c.outgoing, isEmpty);+ expect(r.c.error, isNull);+ });++ test('an answer after the chat closed changes nothing', () async {+ final r = await chat();+ final answers = held(r.swarm);+ final c = SwarmConversation(r.reader, 'g1');+ await c.load();+ c.draft = 'Bye';+ final sending = c.send();+ await settle();++ c.dispose();+ answers.values.single.complete({'result': <String, dynamic>{}});+ expect(await sending, isFalse);+ });++ test('a first read that failed and later recovered still sends and '+ 'settles', () async {+ final r = rig();+ var fail = true;+ final rows = <Map<String, dynamic>>[];+ r.swarm.routes[messages] = (_) => fail+ ? throw StateError('offline')+ : {'messages': rows.reversed.toList(), 'next': null};+ r.swarm.routes[commands] = (body) {+ rows.add(mine(sentId(body!['operationId'] as String), 3, 'Hello'));+ return {'result': <String, dynamic>{}};+ };+ await r.reader.refresh();+ final c = SwarmConversation(r.reader, 'g1');+ addTearDown(c.dispose);+ await c.load();+ expect(c.error, isNotNull);++ fail = false;+ c.draft = 'Hello';+ expect(c.canSend, isTrue);+ expect(await c.send(), isTrue);+ await settle();++ expect(c.outgoing, isEmpty);+ expect([for (final m in c.messages) m.text], ['Hello']);+ });+ });}diff --git a/mobile/test/swarm/swarm_fixture.dart b/mobile/test/swarm/swarm_fixture.dartindex de546e6d5..c1670a2f7 100644--- a/mobile/test/swarm/swarm_fixture.dart+++ b/mobile/test/swarm/swarm_fixture.dart@@ -7,6 +7,7 @@ import 'package:flutter/widgets.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness_mobile/swarm/swarm_home_cache.dart';+import 'package:harness_mobile/swarm/swarm_outbox.dart' show superTabMessageId;import 'package:harness_mobile/swarm/swarm_request.dart';import 'package:harness_mobile/swarm/swarm_outgoing_files.dart';@@ -15,6 +16,11 @@ import 'package:harness_mobile/swarm/swarm_outgoing_files.dart';const me = 'person-me';const tab = 'tab-1';++/// The id the backend gives the message [me] sends in [tab] with receipt+/// [operationId] (commands.ts `message.send`): never the receipt itself.+String sentId(String operationId) =>+ superTabMessageId(tabId: tab, accountId: me, operationId: operationId);const project = 'project-1';const leadChat = 'group-lead';diff --git a/mobile/test/swarm/swarm_outbox_test.dart b/mobile/test/swarm/swarm_outbox_test.dartnew file mode 100644index 000000000..dbdecd84c--- /dev/null+++ b/mobile/test/swarm/swarm_outbox_test.dart@@ -0,0 +1,127 @@+import 'dart:async';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/model.dart';+import 'package:harness_mobile/swarm/swarm_outbox.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';++/// The person's posts on their way, each on its own (Dee, 11-01: a second+/// post never waits on the first, as in Slack).+void main() {+ test('names a sent message as the backend does', () {+ // Worked out with the backend's stableId (model.ts): sha256 over+ // JSON ["tab-1","person:acct-1","op-1"], first 24 hex.+ expect(+ superTabMessageId(+ tabId: 'tab-1',+ accountId: 'acct-1',+ operationId: 'op-1',+ ),+ '6834802bed07d0983ab744fd',+ );+ });++ SuperTabMessage row(String id) => SuperTabMessage.fromJson({+ 'id': id,+ 'conversationId': 'g1',+ 'text': 'hi',+ 'sequence': 1,+ 'author': {'kind': 'person', 'id': 'acct-1', 'name': 'me'},+ 'createdAt': '2026-11-01T04:12:00.000Z',+ });++ ({SwarmOutbox box, List<Completer<Object?>> answers, List<SwarmPost> taken})+ rig({Duration timeout = SwarmOutbox.defaultTimeout}) {+ final answers = <Completer<Object?>>[];+ final taken = <SwarmPost>[];+ final box = SwarmOutbox(+ request: (method, path, {body}) {+ final answer = Completer<Object?>();+ answers.add(answer);+ return answer.future;+ },+ path: '/commands',+ timeout: timeout,+ onChanged: () {},+ onTaken: taken.add,+ onRefused: (_) {},+ );+ addTearDown(box.close);+ return (box: box, answers: answers, taken: taken);+ }++ SwarmPost post(String operationId) => SwarmPost(+ body: {+ 'operationId': operationId,+ 'command': {'type': 'message.send', 'text': 'hi'},+ },+ messageId: 'id-$operationId',+ );++ test('a late failure of an earlier try never undoes the retry under way, '+ 'and the post is told taken once', () async {+ final r = rig(timeout: const Duration(milliseconds: 10));+ final p = post('op-1');+ expect(await r.box.add(p), SwarmPostOutcome.lost);+ final again = r.box.deliver(p);+ expect(p.state, SwarmPostState.sending);++ r.answers[0].completeError(StateError('reset'));+ await Future<void>.delayed(Duration.zero);+ expect(p.state, SwarmPostState.sending, reason: 'the retry speaks now');++ r.answers[1].complete({'result': <String, dynamic>{}});+ expect(await again, SwarmPostOutcome.taken);+ expect(p.state, SwarmPostState.confirmed);+ expect(r.taken, [p]);+ });++ test('read back before its answer, it leaves, and its answer still tells '+ 'it taken once', () async {+ final r = rig();+ final p = post('op-1');+ final going = r.box.add(p);++ expect(r.box.settle([row('id-op-1')]), isTrue);+ expect(r.box.posts, isEmpty);+ r.answers.single.complete({'result': <String, dynamic>{}});++ expect(await going, SwarmPostOutcome.taken);+ expect(r.taken, [p]);+ });++ test(+ 'cleared (access lost) while on its way, its answer tells no one',+ () async {+ final r = rig();+ final p = post('op-1');+ final going = r.box.add(p);++ r.box.clear();+ r.answers.single.complete({'result': <String, dynamic>{}});++ expect(await going, SwarmPostOutcome.gone);+ expect(r.taken, isEmpty);+ expect(r.box.posts, isEmpty);+ },+ );++ test('a refusal takes it out; a rate limit leaves it to retry', () async {+ final r = rig();+ final refused = post('op-1'), limited = post('op-2');+ final a = r.box.add(refused), b = r.box.add(limited);++ r.answers[0].completeError(+ const SuperTabFailure('ARCHIVED', 'Archived.', statusCode: 409),+ );+ r.answers[1].completeError(+ const SuperTabFailure('RATE_LIMITED', 'Slow down.', statusCode: 429),+ );++ expect(await a, SwarmPostOutcome.refused);+ expect(refused.refusedBy?.code, 'ARCHIVED');+ expect(await b, SwarmPostOutcome.lost);+ expect(r.box.posts, [limited]);+ expect(r.box.unconfirmed, limited);+ });+}diff --git a/mobile/test/swarm/swarm_thread_test.dart b/mobile/test/swarm/swarm_thread_test.dartindex 521b2da80..b88aa4783 100644--- a/mobile/test/swarm/swarm_thread_test.dart+++ b/mobile/test/swarm/swarm_thread_test.dart@@ -4,6 +4,7 @@ import 'dart:typed_data';import 'package:flutter_test/flutter_test.dart';import 'package:harness_mobile/swarm/model.dart';import 'package:harness_mobile/swarm/swarm_conversation.dart';+import 'package:harness_mobile/swarm/swarm_outbox.dart';import 'package:harness_mobile/swarm/swarm_outgoing_files.dart';import 'package:harness_mobile/swarm/swarm_read_marks.dart';import 'package:harness_mobile/swarm/swarm_reader.dart';@@ -103,7 +104,7 @@ void main() {final rows = [message('m1', 1), message('m2', 2, root: 'm1')];swarm.routes[commands] = (body) {if (lost?.call() ?? false) throw StateError('connection reset');- final id = body!['operationId'] as String;+ final id = sentId(body!['operationId'] as String);rows.add(message(id, rows.length + 1, root: 'm1'));return {'ok': true};};@@ -350,7 +351,7 @@ void main() {]);expect(t.draft, isEmpty);expect(t.alsoSend, isFalse, reason: 'each reply asks again');- expect(t.pending, isNull);+ expect(t.outgoing, isEmpty);expect(r.chat.threadDraft('m1'), isEmpty);});@@ -367,7 +368,7 @@ void main() {return answer.future;};r.swarm.routes['$messages?after=2'] = (_) => {- 'messages': [message(sent!, 3, root: 'm1')],+ 'messages': [message(sentId(sent!), 3, root: 'm1')],'next': null,};final t = open(r.chat);@@ -376,36 +377,36 @@ void main() {final sending = t.send();await settle();- expect(t.pending, 'On it');+ expect(t.outgoing.firstOrNull?.text, 'On it');expect(t.sending, isTrue);expect(t.draft, isEmpty);answer.complete({'ok': true});await sending;- expect(t.pending, isNull);- expect([for (final m in t.replies) m.id], ['m2', sent]);+ expect(t.outgoing, isEmpty);+ expect([for (final m in t.replies) m.id], ['m2', sentId(sent!)]);});- test('taken by the backend and not read back yet, it stays on its way '- 'until a read brings it', () async {+ test('taken by the backend and not read back yet, it shows as sent until '+ 'a read brings it, and never holds the next reply', () async {final r = await rig();r.swarm.routes[thread] = (_) => {'messages': [message('m1', 1)],'next': null,};- String? sent;+ final sent = <String>[];r.swarm.routes[commands] = (body) {- sent = body!['operationId'] as String;+ sent.add(body!['operationId'] as String);return {'ok': true};};var reads = 0;r.swarm.routes['$messages?after=2'] = (_) => switch (reads++) {- // The read after the post fails; the next one has not got it yet.- 0 => throw StateError('offline'),- 1 => {'messages': <Object>[], 'next': null},+ // The reads after the posts fail; the next one has not got them yet.+ 0 || 1 => throw StateError('offline'),+ 2 => {'messages': <Object>[], 'next': null},_ => {- 'messages': [message(sent!, 3, root: 'm1')],+ 'messages': [message(sentId(sent.first), 3, root: 'm1')],'next': null,},};@@ -415,22 +416,22 @@ void main() {expect(await t.send(), isTrue, reason: 'the backend took it');- expect(t.pending, 'On it');- expect(t.confirmed, isTrue);+ expect(t.outgoing.single.text, 'On it');+ expect(t.outgoing.single.state, SwarmPostState.confirmed);expect(t.unconfirmed, isFalse, reason: 'not to be sent again');t.draft = 'And another';- expect(t.canSend, isFalse);- expect(await t.send(), isFalse);- expect(r.swarm.commands, hasLength(1));+ expect(t.canSend, isTrue, reason: 'Send never waits on an echo');+ expect(await t.send(), isTrue);+ expect(r.swarm.commands, hasLength(2));+ expect(sent.toSet(), hasLength(2), reason: 'two posts, two receipts');+ expect([for (final p in t.outgoing) p.text], ['On it', 'And another']);await r.chat.load();- expect(t.pending, 'On it');+ expect(t.outgoing, hasLength(2));await r.chat.load();- expect(t.pending, isNull);- expect(t.confirmed, isFalse);- expect([for (final m in t.replies) m.id], ['m2', sent]);- expect(t.canSend, isTrue);+ expect([for (final p in t.outgoing) p.text], ['And another']);+ expect([for (final m in t.replies) m.id], ['m2', sentId(sent.first)]);});test('refused goes back to the box, with Also send as it was', () async {@@ -453,7 +454,7 @@ void main() {expect(t.draft, 'Too late');expect(t.alsoSend, isTrue);- expect(t.pending, isNull);+ expect(t.outgoing, isEmpty);expect(t.error, 'This chat is archived.');expect(r.chat.threadDraft('m1'), 'Too late');});@@ -472,7 +473,7 @@ void main() {expect(await t.send(), isFalse);expect(t.unconfirmed, isTrue);- expect(t.pending, 'Once only');+ expect(t.outgoing.firstOrNull?.text, 'Once only');expect(t.error, contains('not sent'));lost = false;@@ -484,7 +485,7 @@ void main() {];expect(posts, hasLength(2));expect(posts.toSet(), hasLength(1));- expect(t.pending, isNull);+ expect(t.outgoing, isEmpty);});test('a viewer cannot reply', () async {@@ -551,8 +552,7 @@ void main() {},]);expect(t.files.files, isEmpty);- expect(t.pending, isNull, reason: 'read back');- expect(t.pendingFiles, isEmpty);+ expect(t.outgoing, isEmpty, reason: 'read back');expect(r.chat.files.files, isEmpty, reason: 'the chat\'s own box');});@@ -596,8 +596,8 @@ void main() {uploads.asked.single.answer.complete(FakeUploads.attachment('f1'));await settle();expect(t.uploading, isFalse);- expect(t.pending, 'look');- expect(names(t.pendingFiles), ['a.jpg']);+ expect(t.outgoing.firstOrNull?.text, 'look');+ expect(names(t.outgoing.single.files), ['a.jpg']);expect(t.files.files, isEmpty);answer.complete({'ok': true});@@ -639,7 +639,7 @@ void main() {expect(names(t.files.files), ['a.jpg', 'b.jpg']);expect(r.swarm.commands, isEmpty);expect(t.uploading, isFalse);- expect(t.pending, isNull);+ expect(t.outgoing, isEmpty);expect(t.canSend, isTrue, reason: 'not stuck: Send tries again');});@@ -705,7 +705,7 @@ void main() {expect(await t.send(), isFalse);expect(t.draft, 'look');expect(names(t.files.files), ['a.jpg']);- expect(t.pending, isNull);+ expect(t.outgoing, isEmpty);expect(t.error, 'That file is no longer there. Attach it again.');refusal = const SuperTabFailure(@@ -915,7 +915,7 @@ void main() {expect(t.messages, isEmpty);expect(t.draft, isEmpty, reason: 'not put back in the box');expect(t.alsoSend, isFalse);- expect(t.pending, isNull);+ expect(t.outgoing, isEmpty);expect(t.error, isNull, reason: 'the page says it is not open');expect(r.chat.threadDraft('m1'), isEmpty);expect(@@ -1118,4 +1118,251 @@ void main() {expect(t.hasEarlier, isTrue);});});++ group('replies on their way (Dee, 11-01)', () {+ /// The bodies [swarm] was sent, by receipt, each answered by hand.+ Map<String, Completer<Object?>> held(FakeSwarm swarm) {+ final answers = <String, Completer<Object?>>{};+ swarm.routes[commands] = (body) =>+ (answers[body!['operationId'] as String] ??= Completer()).future;+ return answers;+ }++ Future<SwarmThread> opened(+ ({FakeSwarm swarm, SwarmReader reader, SwarmConversation chat}) r,+ ) async {+ r.swarm.routes[thread] = (_) => {+ 'messages': [message('m1', 1)],+ 'next': null,+ };+ final t = open(r.chat);+ await t.load();+ return t;+ }++ test('a reply the chat reads back under the id the backend gives it '+ 'leaves at once, though its answer is still coming, and Send is free '+ 'all along', () async {+ final r = await rig();+ final answers = held(r.swarm);+ final t = await opened(r);+ t.draft = 'why do we need the 13mm floor?';+ final sending = t.send();+ await settle();+ final receipt = answers.keys.single;+ t.draft = 'and the lip?';+ expect(t.canSend, isTrue);++ r.swarm.routes['$messages?after=2'] = (_) => {+ 'messages': [message(sentId(receipt), 3, root: 'm1')],+ 'next': null,+ };+ await r.chat.load();+ expect(t.outgoing, isEmpty, reason: 'shown once, as its reply');++ answers[receipt]!.complete({'result': <String, dynamic>{}});+ expect(await sending, isTrue);+ expect(t.outgoing, isEmpty);+ expect([for (final m in t.replies) m.id], ['m2', sentId(receipt)]);+ });++ test('its own read brings it back too, and the answer\'s id wins over '+ 'the one worked out', () async {+ final r = await rig();+ r.swarm.routes[commands] = (_) => {+ 'result': {'messageId': 'server-r9'},+ };+ final t = await opened(r);+ t.draft = 'On it';++ expect(await t.send(), isTrue);+ expect(t.outgoing.single.messageId, 'server-r9');++ r.swarm.routes[thread] = (_) => {+ 'messages': [message('m1', 1), message('server-r9', 3, root: 'm1')],+ 'next': null,+ };+ await t.load();+ expect(t.outgoing, isEmpty);+ });++ test('its id in another chat settles nothing', () async {+ final r = await rig();+ final answers = held(r.swarm);+ final t = await opened(r);+ t.draft = 'On it';+ unawaited(t.send());+ await settle();+ final receipt = answers.keys.single;++ r.swarm.routes[thread] = (_) => {+ 'messages': [+ message('m1', 1),+ message(sentId(receipt), 3, root: 'm1', conversationId: 'g2'),+ ],+ 'next': null,+ };+ await t.load();+ expect(t.outgoing.single.text, 'On it');+ answers[receipt]!.complete({'result': <String, dynamic>{}});+ await settle();+ });++ test('no answer in time says Not sent; Retry reuses the receipt and the '+ 'late answer counts', () async {+ final r = await rig();+ final answers = held(r.swarm);+ final chat = SwarmConversation(+ r.reader,+ 'g1',+ sendTimeout: const Duration(milliseconds: 20),+ );+ addTearDown(chat.dispose);+ await chat.load();+ r.swarm.routes[thread] = (_) => {+ 'messages': [message('m1', 1)],+ 'next': null,+ };+ final t = open(chat);+ await t.load();+ t.draft = 'Once only';++ expect(await t.send(), isFalse);+ final post = t.outgoing.single;+ expect(post.state, SwarmPostState.unconfirmed);+ expect(t.error, contains('not sent'));++ final again = t.retry(post);+ await settle();+ final posts = [+ for (final call in r.swarm.calls)+ if (call.path == commands) call.body!['operationId'],+ ];+ expect(posts, hasLength(2));+ expect(posts.toSet(), hasLength(1), reason: 'one reply, one receipt');+ answers.values.single.complete({'result': <String, dynamic>{}});+ expect(await again, isTrue);+ expect(post.state, SwarmPostState.confirmed);+ expect(t.error, isNull);+ });++ test(+ 'a refusal that lands after Not sent still puts the reply back',+ () async {+ final r = await rig();+ final answers = held(r.swarm);+ final chat = SwarmConversation(+ r.reader,+ 'g1',+ sendTimeout: const Duration(milliseconds: 20),+ );+ addTearDown(chat.dispose);+ await chat.load();+ r.swarm.routes[thread] = (_) => {+ 'messages': [message('m1', 1)],+ 'next': null,+ };+ final t = open(chat);+ await t.load();+ t.draft = 'Too long';++ expect(await t.send(), isFalse);+ expect(t.draft, isEmpty);+ answers.values.single.completeError(+ const SuperTabFailure('TOO_LONG', 'Too long.', statusCode: 400),+ );+ await settle();+ expect(t.outgoing, isEmpty);+ expect(t.draft, 'Too long');+ expect(t.error, 'Too long.');+ },+ );++ test('a refused reply goes back to the box while another stays on its '+ 'way', () async {+ final r = await rig();+ final answers = held(r.swarm);+ final t = await opened(r);+ t.draft = 'Too long';+ t.alsoSend = true;+ final refused = t.send();+ await settle();+ t.draft = 'Fine';+ final fine = t.send();+ await settle();++ answers.values.first.completeError(+ const SuperTabFailure('TOO_LONG', 'Too long.', statusCode: 400),+ );+ expect(await refused, isFalse);+ expect(t.draft, 'Too long');+ expect(t.alsoSend, isTrue);+ expect([for (final p in t.outgoing) p.text], ['Fine']);+ answers.values.last.complete({'result': <String, dynamic>{}});+ expect(await fine, isTrue);+ });++ test('access lost while a reply is on its way drops it, and its answer '+ 'changes nothing', () async {+ final r = await rig();+ final answers = held(r.swarm);+ final t = await opened(r);+ t.draft = 'Secret plan';+ final sending = t.send();+ await settle();++ r.reader.revoke();+ await settle();+ expect(t.outgoing, isEmpty);++ answers.values.single.completeError(+ const SuperTabFailure('TOO_LONG', 'Too long.', statusCode: 400),+ );+ expect(await sending, isFalse);+ expect(t.draft, isEmpty, reason: 'nothing put back');+ expect(t.outgoing, isEmpty);+ expect(t.error, isNull);+ });++ test('an answer after the thread closed changes nothing', () async {+ final r = await rig();+ final answers = held(r.swarm);+ r.swarm.routes[thread] = (_) => {+ 'messages': [message('m1', 1)],+ 'next': null,+ };+ final t = SwarmThread(r.chat, 'm1');+ await t.load();+ t.draft = 'Bye';+ final sending = t.send();+ await settle();++ t.dispose();+ answers.values.single.complete({'result': <String, dynamic>{}});+ expect(await sending, isFalse);+ expect(r.chat.threadDraft('m1'), isEmpty);+ });++ test('a first read that failed and later recovered still sends and '+ 'settles', () async {+ final r = await rig();+ r.swarm.routes[thread] = (_) => throw StateError('offline');+ final t = open(r.chat);+ await t.load();+ expect(t.readError, isNotNull);+ readsBack(r.swarm);+ t.draft = 'Hello';++ expect(t.canSend, isTrue);+ expect(await t.send(), isTrue);+ await settle();+ expect(t.outgoing, isEmpty);+ final receipt =+ r.swarm.calls+ .lastWhere((call) => call.path == commands)+ .body!['operationId']+ as String;+ expect(t.replies.last.id, sentId(receipt));+ });+ });}