Skip to content

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.

Desktop Swarm chat: Reply and tags keep the keyboard; messages show at once while sending (#1946)

0xken1583faecea94aa
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index e53bc3ed5..b6ff1830c 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -42,6 +42,49 @@ class SuperTabFailure implements Exception {
String toString() => message;
}
+/// Where a message the reader sent stands while the transcript does not
+/// show it yet.
+enum SuperTabOutgoingState {
+ /// On its way, or accepted and not read back yet.
+ sending,
+
+ /// Sent with no answer: it may or may not have arrived. Retry checks and
+ /// sends it once.
+ unconfirmed,
+
+ /// The backend refused it; nothing was posted.
+ refused,
+}
+
+/// A message the backend refused, with the tags it was sent with.
+typedef _Refused = ({
+ String operationId,
+ Map<String, dynamic> command,
+ Map<String, String> mentions,
+ String error,
+});
+
+/// A message the reader sent that the transcript does not hold yet.
+class SuperTabOutgoing {
+ const SuperTabOutgoing({
+ required this.conversationId,
+ required this.text,
+ required this.state,
+ this.operationId,
+ this.replyTo,
+ this.error,
+ });
+ final String conversationId, text;
+
+ /// The send's receipt id, while it is not confirmed.
+ final String? operationId;
+ final String? replyTo;
+ final SuperTabOutgoingState state;
+
+ /// Why it was refused, as the backend said it.
+ final String? error;
+}
+
/// Personal navigation/drafts live on this client. Membership, work and messages
/// live on the backend; refreshing never selects another person's conversation.
class SuperTabController extends ChangeNotifier {
@@ -106,6 +149,30 @@ class SuperTabController extends ChangeNotifier {
}
}
}
+ final refused = initial['refused'];
+ if (refused is Map) {
+ for (final MapEntry(:key, :value) in refused.entries) {
+ if (key is! String || value is! List) continue;
+ final kept = [
+ for (final row in value)
+ if (row is Map &&
+ row['operationId'] is String &&
+ row['command'] is Map &&
+ row['error'] is String)
+ (
+ operationId: row['operationId'] as String,
+ command: superTabMap(row['command']),
+ mentions: {
+ for (final MapEntry(key: agent, value: token)
+ in superTabMap(row['mentions']).entries)
+ if (token is String) agent: token,
+ },
+ error: row['error'] as String,
+ ),
+ ];
+ if (kept.isNotEmpty) _refused[key] = kept;
+ }
+ }
if (initial['pending'] is Map) {
final value = superTabMap(initial['pending']);
if (value['operationId'] is String && value['command'] is Map) {
@@ -245,6 +312,17 @@ class SuperTabController extends ChangeNotifier {
int stateReads = 0;
Future<void> _persisting = Future.value();
Map<String, dynamic>? _pending;
+
+ /// Sends the backend took, by message id, until the transcript holds them.
+ final _sent = <String, Map<String, dynamic>>{};
+
+ /// The tags of each message on its way, by operation id, for a refusal to
+ /// give back.
+ final _sendingMentions = <String, Map<String, String>>{};
+
+ /// Per conversation, oldest first, the messages the backend refused, each
+ /// kept until it is sent again or deleted.
+ final _refused = <String, List<_Refused>>{};
final _drafts = <String, String>{};
final _terminals = <String, String>{};
final _mentions = <String, Map<String, String>>{};
@@ -448,7 +526,10 @@ class SuperTabController extends ChangeNotifier {
/// Reads [projectId]'s GitHub access, at most every 5 minutes; [refresh]: a person checks again (the server asks
/// GitHub at once, at most every 15 seconds per repository). An older server has no such read: nothing is shown.
- Future<void> readGitHubAccess(String projectId, {bool refresh = false}) async {
+ Future<void> readGitHubAccess(
+ String projectId, {
+ bool refresh = false,
+ }) async {
final asked = _githubAsked[projectId];
if (_disposed ||
accessRevoked ||
@@ -718,6 +799,7 @@ class SuperTabController extends ChangeNotifier {
saved.conversation(id as String) != null &&
messages.every((m) => m.conversationId == id)) {
_messages[id] = messages..sort(superTabMessageOrder);
+ _dropShownSends(id);
_keepRows(id, rows);
_before[id] = SuperTabPage.read(view['next']);
}
@@ -772,6 +854,8 @@ class SuperTabController extends ChangeNotifier {
_messages.clear();
_quoted.clear();
_quoting.clear();
+ _sent.clear();
+ _refused.clear();
_poll?.cancel();
_changed();
}
@@ -795,6 +879,19 @@ class SuperTabController extends ChangeNotifier {
},
'readAt': Map<String, int>.of(_readAt),
if (_pending != null) 'pending': _pending,
+ if (_refused.isNotEmpty)
+ 'refused': {
+ for (final MapEntry(:key, :value) in _refused.entries)
+ key: [
+ for (final refused in value)
+ {
+ 'operationId': refused.operationId,
+ 'command': refused.command,
+ 'mentions': refused.mentions,
+ 'error': refused.error,
+ },
+ ],
+ },
};
Future<void> _persist() {
@@ -839,6 +936,95 @@ class SuperTabController extends ChangeNotifier {
}
}
+ /// What the reader sent to conversation [id] that its transcript does not
+ /// hold yet, oldest first.
+ List<SuperTabOutgoing> outgoing(String id) {
+ final held = {for (final m in _messages[id] ?? const []) m.id};
+ SuperTabOutgoing of(
+ Map<String, dynamic> command,
+ SuperTabOutgoingState state, {
+ String? operationId,
+ String? error,
+ }) => SuperTabOutgoing(
+ conversationId: id,
+ text: command['text'] as String? ?? '',
+ replyTo: command['replyTo'] as String?,
+ state: state,
+ operationId: operationId,
+ error: error,
+ );
+ final pending = _pending,
+ command = pending == null
+ ? const <String, dynamic>{}
+ : superTabMap(pending['command']);
+ return [
+ for (final refused in _refused[id] ?? const <_Refused>[])
+ of(
+ refused.command,
+ SuperTabOutgoingState.refused,
+ operationId: refused.operationId,
+ error: refused.error,
+ ),
+ for (final MapEntry(key: messageId, value: sent) in _sent.entries)
+ if (sent['conversationId'] == id && !held.contains(messageId))
+ of(sent, SuperTabOutgoingState.sending),
+ // The backend names a person's message by its send's operation id, so
+ // one read back while its answer was lost is not shown twice.
+ if (command['type'] == 'message.send' &&
+ command['conversationId'] == id &&
+ !held.contains(pending!['operationId']))
+ of(
+ command,
+ saving
+ ? SuperTabOutgoingState.sending
+ : SuperTabOutgoingState.unconfirmed,
+ operationId: pending['operationId'] as String?,
+ ),
+ ];
+ }
+
+ /// Sends failed [message] again: one with no answer under its own receipt
+ /// id, so it is posted once; a refused one as it was, tags and reply too.
+ Future<Map<String, dynamic>?> retryOutgoing(SuperTabOutgoing message) async {
+ if (message.state == SuperTabOutgoingState.unconfirmed) {
+ return _pending?['operationId'] == message.operationId ? retry() : null;
+ }
+ if (saving || _pending != null) return null;
+ final refused = _takeRefused(message);
+ if (refused == null) return null;
+ _sendingMentions[refused.operationId] = refused.mentions;
+ _pending = {'operationId': refused.operationId, 'command': refused.command};
+ return retry();
+ }
+
+ /// Removes failed [message] from its chat: a refused one, or one sent
+ /// without an answer. The second may have arrived after all; then the next
+ /// read shows it, once.
+ void discardOutgoing(SuperTabOutgoing message) {
+ final command = _pending == null
+ ? const <String, dynamic>{}
+ : superTabMap(_pending!['command']);
+ final unconfirmed =
+ message.state == SuperTabOutgoingState.unconfirmed &&
+ !saving &&
+ command['type'] == 'message.send' &&
+ _pending!['operationId'] == message.operationId;
+ if (!unconfirmed && _takeRefused(message) == null) return;
+ if (unconfirmed) {
+ _sendingMentions.remove(_pending!['operationId']);
+ _pending = null;
+ }
+ operationError = null;
+ operationErrorCode = null;
+ unawaited(
+ _persist().catchError((Object _) {
+ error = 'Could not save this change on this computer.';
+ _changed();
+ }),
+ );
+ _changed();
+ }
+
Map<String, String> mentions(String conversationId) =>
Map.unmodifiable(_mentions[conversationId] ?? const {});
@@ -1142,6 +1328,7 @@ class SuperTabController extends ChangeNotifier {
..._terminals.keys,
..._mentions.keys,
..._readAt.keys,
+ ..._refused.keys,
].any(removed.contains) ||
expandedProjects.any(
(id) => !next.projects.any((project) => project.id == id),
@@ -1158,6 +1345,10 @@ class SuperTabController extends ChangeNotifier {
});
_terminals.removeWhere((id, _) => removed.contains(id));
_mentions.removeWhere((id, _) => removed.contains(id));
+ _sent.removeWhere(
+ (_, sent) => !allowed.contains(sent['conversationId']),
+ );
+ _refused.removeWhere((id, _) => removed.contains(id));
_before.removeWhere((id, _) => !allowed.contains(id));
_readAt.removeWhere((id, _) => removed.contains(id));
expandedProjects.removeWhere(
@@ -1679,6 +1870,7 @@ class SuperTabController extends ChangeNotifier {
// An adapting read that found nothing new changes nothing on screen.
final same = _policy.adapts && _sameMessages(_messages[id], next);
_messages[id] = next;
+ _dropShownSends(id);
if (reactionSeq is int) _reactionSeq[id] = reactionSeq;
if (older || replacing || !_before.containsKey(id)) {
_before[id] = SuperTabPage.read(answer['next']);
@@ -1745,6 +1937,12 @@ class SuperTabController extends ChangeNotifier {
operationNotice = notice is String && notice.isNotEmpty ? notice : null;
if (command['type'] == 'message.send') {
final id = command['conversationId'] as String;
+ _sendingMentions.remove(pending['operationId']);
+ // Shown as sending until the transcript holds it, so it never leaves
+ // the chat between the answer and the read that brings it.
+ _sent[result['messageId'] as String? ??
+ pending['operationId'] as String] =
+ command;
if (_drafts[id]?.trim() == command['text']) {
_drafts.remove(id);
_mentions.remove(id);
@@ -1782,6 +1980,7 @@ class SuperTabController extends ChangeNotifier {
operationError = updateMessage;
operationErrorCode = 'UPDATE_REQUIRED';
// Refused by the backend: nothing was done, nothing to retry.
+ _refuse(pending, operationError!);
_pending = null;
try {
await _persist();
@@ -1797,8 +1996,9 @@ class SuperTabController extends ChangeNotifier {
failure.statusCode >= 400 &&
failure.statusCode < 500 &&
!const {408, 429}.contains(failure.statusCode)) {
- // A definitive rejection made no change. Preserve the draft and let
- // the person correct it; a lost reply retains its exact receipt ID.
+ // A definitive rejection made no change. Keep the message for the
+ // person to correct; a lost reply retains its exact receipt ID.
+ _refuse(pending, operationError!);
_pending = null;
try {
await _persist();
@@ -1822,6 +2022,37 @@ class SuperTabController extends ChangeNotifier {
}
}
+ /// Keeps a refused [pending] message, with its tags, for Retry.
+ void _refuse(Map<String, dynamic> pending, String error) {
+ final command = superTabMap(pending['command']);
+ final mentions = _sendingMentions.remove(pending['operationId']);
+ if (command['type'] != 'message.send') return;
+ (_refused[command['conversationId'] as String] ??= []).add((
+ operationId: pending['operationId'] as String,
+ command: command,
+ mentions: mentions ?? const {},
+ error: error,
+ ));
+ }
+
+ /// Removes refused [message] from what is kept, and returns it.
+ _Refused? _takeRefused(SuperTabOutgoing message) {
+ if (message.state != SuperTabOutgoingState.refused) return null;
+ final kept = _refused[message.conversationId];
+ final i =
+ kept?.indexWhere((r) => r.operationId == message.operationId) ?? -1;
+ if (i < 0) return null;
+ final refused = kept!.removeAt(i);
+ if (kept.isEmpty) _refused.remove(message.conversationId);
+ return refused;
+ }
+
+ /// Drops the sends the transcript of [id] holds now.
+ void _dropShownSends(String id) {
+ final held = {for (final m in _messages[id] ?? const []) m.id};
+ _sent.removeWhere((messageId, _) => held.contains(messageId));
+ }
+
bool _maySend(Map<String, dynamic> command) =>
canWrite ||
(!accessRevoked &&
@@ -1829,9 +2060,12 @@ class SuperTabController extends ChangeNotifier {
command['type'] == 'member.remove' &&
command['userId'] == accountId);
+ /// Sends the selected conversation's draft. [onSending] is told when the
+ /// message is on its way and shows in [outgoing].
Future<Map<String, dynamic>?> send({
String? replyTo,
List<String> recipients = const [],
+ VoidCallback? onSending,
}) async {
final text = draft(selectedId).trim();
final files = attachments(selectedId).files;
@@ -1858,7 +2092,9 @@ class SuperTabController extends ChangeNotifier {
final conversationId = selectedId;
final ids = await _uploadAll(conversationId, files);
if (ids == null) return null;
- final result = await command({
+ final before = _pending;
+ final tags = Map<String, String>.of(_mentions[conversationId] ?? const {});
+ final sending = command({
'type': 'message.send',
'conversationId': conversationId,
'text': text,
@@ -1866,6 +2102,18 @@ class SuperTabController extends ChangeNotifier {
'recipientIds': addressed,
if (ids.isNotEmpty) 'attachmentIds': ids,
});
+ // On its way: the message shows in the chat, and the draft is free for
+ // the next one. Both are in the save made before the request.
+ if (_pending case final pending? when !identical(pending, before)) {
+ _sendingMentions[pending['operationId'] as String] = tags;
+ if (_drafts[conversationId]?.trim() == text) {
+ _drafts.remove(conversationId);
+ _mentions.remove(conversationId);
+ }
+ onSending?.call();
+ _changed();
+ }
+ final result = await sending;
// A refusal of the files themselves sends them up once more; one of the
// message (a mention, a recipient) leaves them uploaded.
if (result == null &&
diff --git a/desktop/lib/super_tabs/message_receipt.dart b/desktop/lib/super_tabs/message_receipt.dart
index efbcc8d97..64c9cb4bf 100644
--- a/desktop/lib/super_tabs/message_receipt.dart
+++ b/desktop/lib/super_tabs/message_receipt.dart
@@ -218,10 +218,7 @@ class _SuperTabMessageReceiptState extends State<SuperTabMessageReceipt>
sending = true;
}
_clock(fresh || working || (delivery?.pending == true && offline));
- final style = DesktopChrome.metadata(color: color).copyWith(
- fontSize: 12,
- fontFeatures: const [FontFeature.tabularFigures()],
- );
+ final style = superTabReceiptStyle(color);
final motion = !MediaQuery.disableAnimationsOf(context);
final parts = <Widget>[
if (sending && motion)
@@ -267,20 +264,83 @@ class _SuperTabMessageReceiptState extends State<SuperTabMessageReceipt>
],
for (final (label, action) in actions) ...[
Text('·', style: style),
- TextButton(
- onPressed: action,
- style: TextButton.styleFrom(
- foregroundColor: DesktopChrome.accent,
- padding: const EdgeInsets.symmetric(horizontal: 2),
- minimumSize: const Size(0, 32),
- tapTargetSize: MaterialTapTargetSize.shrinkWrap,
- textStyle: style,
- ),
- child: Text(label),
- ),
+ _receiptAction(label, action, style),
],
];
- return Padding(
+ return _receiptLine(
+ parts,
+ below: [
+ if (note != null)
+ Padding(
+ padding: const EdgeInsets.only(top: 4),
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ color: color.withValues(alpha: .09),
+ borderRadius: BorderRadius.circular(6),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
+ child: Text(
+ note,
+ style: DesktopChrome.metadata().copyWith(
+ fontSize: 12,
+ height: 1.45,
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+}
+
+/// A receipt line's text: small metadata in [color], with figures that keep
+/// their width as a clock counts.
+TextStyle superTabReceiptStyle(Color color) => DesktopChrome.metadata(
+ color: color,
+).copyWith(fontSize: 12, fontFeatures: const [FontFeature.tabularFigures()]);
+
+/// An action on a receipt line, read as a link in the line's text; a
+/// destructive one passes the error [color].
+Widget _receiptAction(
+ String label,
+ VoidCallback? onPressed,
+ TextStyle style, {
+ Color? color,
+}) => TextButton(
+ onPressed: onPressed,
+ // Quiet, as inline controls are: no fill or rim at rest, the shared hover
+ // wash, and the focus ring for the keyboard. Every receipt action (Retry,
+ // Delete, Add a Lead, Open terminal, Send again, It arrived) is drawn here.
+ style:
+ TextButton.styleFrom(
+ foregroundColor: color ?? DesktopChrome.accent,
+ backgroundColor: Colors.transparent,
+ // Given a foreground, styleFrom tints hover with it; quiet controls
+ // share the neutral wash the theme's buttons and rows use.
+ overlayColor: grid.AppSurface.hoverFill,
+ padding: const EdgeInsets.symmetric(horizontal: 2),
+ minimumSize: const Size(0, 32),
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ textStyle: style,
+ ).copyWith(
+ side: WidgetStateProperty.resolveWith(
+ (states) => BorderSide(
+ width: grid.AppDesktop.focusWidth,
+ color: states.contains(WidgetState.focused)
+ ? DesktopChrome.focusRing
+ : Colors.transparent,
+ ),
+ ),
+ ),
+ child: Text(label),
+);
+
+/// The line under a message: [parts] in a row that wraps, announced as it
+/// changes, with [below] under it.
+Widget _receiptLine(List<Widget> parts, {List<Widget> below = const []}) =>
+ Padding(
padding: const EdgeInsets.only(top: 6),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -294,31 +354,59 @@ class _SuperTabMessageReceiptState extends State<SuperTabMessageReceipt>
children: parts,
),
),
- if (note != null)
- Padding(
- padding: const EdgeInsets.only(top: 4),
- child: DecoratedBox(
- decoration: BoxDecoration(
- color: color.withValues(alpha: .09),
- borderRadius: BorderRadius.circular(6),
- ),
- child: Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 8,
- vertical: 6,
- ),
- child: Text(
- note,
- style: DesktopChrome.metadata().copyWith(
- fontSize: 12,
- height: 1.45,
- ),
- ),
- ),
- ),
- ),
+ ...below,
],
),
);
+
+/// The line under a message the transcript does not hold yet: Sending…, or
+/// Not sent with what can be done about it (design: Ken, 10-28).
+class SuperTabOutgoingReceipt extends StatelessWidget {
+ const SuperTabOutgoingReceipt({
+ super.key,
+ required this.message,
+ required this.onDelete,
+ this.onRetry,
+ });
+ final SuperTabOutgoing message;
+
+ /// Null while it cannot be done now, as during another send.
+ final VoidCallback? onRetry;
+ final VoidCallback onDelete;
+
+ @override
+ Widget build(BuildContext context) {
+ if (message.state == SuperTabOutgoingState.sending) {
+ final style = superTabReceiptStyle(DesktopChrome.muted);
+ return _receiptLine([
+ if (MediaQuery.disableAnimationsOf(context))
+ Icon(AppIcons.loaderCircle, size: 14, color: DesktopChrome.muted)
+ else
+ SizedBox(
+ width: 12,
+ height: 12,
+ child: CircularProgressIndicator(
+ strokeWidth: 1.5,
+ color: DesktopChrome.muted,
+ ),
+ ),
+ Text('Sending…', style: style),
+ ]);
+ }
+ final color = Theme.of(context).colorScheme.error;
+ final style = superTabReceiptStyle(color);
+ final refused = message.state == SuperTabOutgoingState.refused;
+ return _receiptLine([
+ Icon(AppIcons.triangleAlert, size: 14, color: color),
+ Text('Not sent', style: style),
+ if (refused && message.error != null) ...[
+ Text('·', style: style),
+ Text(message.error!, style: style),
+ ],
+ Text('·', style: style),
+ _receiptAction('Retry', onRetry, style),
+ Text('·', style: style),
+ _receiptAction('Delete', onDelete, style, color: color),
+ ]);
}
}
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index e9c88cd48..47ef7122b 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -122,6 +122,9 @@ class _SuperTabViewState extends State<SuperTabView>
// Rows to keep in place once their conversation is on screen again.
final _anchors = <String, ({String messageId, double top})>{};
int _mentionIndex = 0;
+ late final _tagBackspace = _TagBackspace(
+ () => c.mentions(c.selectedId).values,
+ );
String? _dismissedMention;
String? _completionPrefix;
@@ -407,12 +410,18 @@ class _SuperTabViewState extends State<SuperTabView>
// From here a zip still running belongs to neither this message, which
// took its files already, nor the next.
final dropped = _droppedFolders.remove(id);
- final result = await c.send(replyTo: _replies[id]?.id);
+ final result = await c.send(
+ replyTo: _replies[id]?.id,
+ // The reply goes with the message, which shows at the end at once.
+ onSending: () {
+ if (!mounted) return;
+ setState(() => _replies.remove(id));
+ _followEnd(id);
+ },
+ );
if (!mounted) return;
setState(() {
- if (result != null) {
- _replies.remove(id);
- } else if (dropped != null) {
+ if (result == null && dropped != null) {
// Not sent: its paths are still offered as zips, in a new record
// so the zip that was running is still let go.
final now = _droppedFolders.putIfAbsent(id, () => []);
@@ -1721,6 +1730,68 @@ class _SuperTabViewState extends State<SuperTabView>
?.showSnackBar(SnackBar(content: Text(failure)));
}
+ /// [sent], drawn as the reader's own message will be once the transcript
+ /// holds it, with where it stands under it.
+ Widget _outgoingRow(
+ SuperTabOutgoing sent,
+ List<SuperTabMessage> messages,
+ Map<String, SuperTabMessage> byId,
+ ) {
+ final id = sent.conversationId;
+ final person = c.snapshot?.people
+ .where((p) => p.id == c.accountId)
+ .firstOrNull;
+ final message = SuperTabMessage.fromJson({
+ 'id': 'outgoing',
+ 'conversationId': id,
+ 'text': sent.text,
+ 'replyTo': sent.replyTo,
+ 'sequence': 0,
+ 'createdAt': DateTime.now().toUtc().toIso8601String(),
+ 'author': {
+ 'kind': 'person',
+ 'id': c.accountId,
+ 'name': person?.email ?? '',
+ },
+ });
+ final reply = byId[sent.replyTo];
+ return KeyedSubtree(
+ key: const ValueKey('super-outgoing'),
+ child: SuperTabMessageRow(
+ message: message,
+ author: _shownAuthor(c, message),
+ person: person,
+ grouped: SuperTabMessageRow.groupsWith(message, messages.lastOrNull),
+ reply: reply,
+ replyAuthor: reply == null ? null : _shownAuthor(c, reply),
+ onReturnToComposer: _focus.requestFocus,
+ readerId: c.accountId,
+ receipts: [
+ SuperTabOutgoingReceipt(
+ message: sent,
+ // A refused message goes again only when nothing else is on
+ // its way.
+ onRetry:
+ c.saving ||
+ (sent.state == SuperTabOutgoingState.refused &&
+ c.hasPendingAction)
+ ? null
+ : () {
+ unawaited(c.retryOutgoing(sent));
+ _focus.requestFocus();
+ },
+ // The click lands in the transcript; typing goes on in the
+ // composer, as after Reply.
+ onDelete: () {
+ c.discardOutgoing(sent);
+ _focus.requestFocus();
+ },
+ ),
+ ],
+ ),
+ );
+ }
+
Widget _message(
SuperTabMessage message,
bool grouped,
@@ -1944,6 +2015,15 @@ class _SuperTabViewState extends State<SuperTabView>
? 0
: messages.where((message) => message.sequence > newAfter).length;
final reply = _replies[c.selectedId];
+ final outgoing = c.outgoing(c.selectedId);
+ // A failed message says so in its own row, with what can be done.
+ final errorInRow = outgoing.any(
+ (sent) => switch (sent.state) {
+ SuperTabOutgoingState.sending => false,
+ SuperTabOutgoingState.unconfirmed => c.hasPendingAction,
+ SuperTabOutgoingState.refused => sent.error == c.operationError,
+ },
+ );
final finding = _finding?.conversationId == c.selectedId ? _finding : null;
final back = finding == null && _back?.conversationId == c.selectedId;
final choices = _completionChoices;
@@ -1980,7 +2060,7 @@ class _SuperTabViewState extends State<SuperTabView>
? const Center(child: CircularProgressIndicator())
: unread && c.error != null
? _firstReadFailed(c.error!)
- : messages.isEmpty
+ : messages.isEmpty && outgoing.isEmpty
? Center(
child: Text(
c.accessRevoked
@@ -2031,8 +2111,15 @@ class _SuperTabViewState extends State<SuperTabView>
'super-messages-${c.tabId}-${c.selectedId}',
),
padding: const EdgeInsets.symmetric(vertical: 8),
- itemCount: entries.length + 1,
+ itemCount: entries.length + 1 + outgoing.length,
itemBuilder: (context, index) {
+ if (index > entries.length) {
+ return _outgoingRow(
+ outgoing[index - 1 - entries.length],
+ messages,
+ byId,
+ );
+ }
if (index == 0) {
final id = c.selectedId;
if (!c.hasOlder(id)) {
@@ -2210,7 +2297,7 @@ class _SuperTabViewState extends State<SuperTabView>
],
),
),
- if (c.operationError != null)
+ if (c.operationError != null && !errorInRow)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Row(
@@ -2362,6 +2449,12 @@ class _SuperTabViewState extends State<SuperTabView>
)
else
Padding(
+ // Keyed: the lines that come and go above it (a reply, mention
+ // choices, an error) are Paddings too, and would otherwise take
+ // over this element and remount the field. A remounted field
+ // keeps focus but loses its text input connection, so typing,
+ // Backspace included, would go nowhere.
+ key: const ValueKey('super-message-composer-row'),
padding: EdgeInsets.fromLTRB(
24,
12,
@@ -2489,6 +2582,7 @@ class _SuperTabViewState extends State<SuperTabView>
? 3
: 8,
maxLength: 32000,
+ inputFormatters: [_tagBackspace],
keyboardType: TextInputType.multiline,
textAlignVertical:
TextAlignVertical.center,
@@ -2765,6 +2859,51 @@ class _SuperTabViewState extends State<SuperTabView>
);
}
+/// Backspace right after a tag takes the whole tag, as in Slack: deleting the
+/// character before the caret, where one of [tags] ends, removes that tag.
+/// The draft then no longer holds it, so its agent is no longer addressed.
+class _TagBackspace extends TextInputFormatter {
+ _TagBackspace(this.tags);
+
+ final Iterable<String> Function() tags;
+
+ @override
+ TextEditingValue formatEditUpdate(
+ TextEditingValue oldValue,
+ TextEditingValue newValue,
+ ) {
+ final caret = oldValue.selection;
+ if (!caret.isValid ||
+ !caret.isCollapsed ||
+ caret.baseOffset == 0 ||
+ (newValue.composing.isValid && !newValue.composing.isCollapsed)) {
+ return newValue;
+ }
+ final end = caret.baseOffset;
+ if (newValue.selection != TextSelection.collapsed(offset: end - 1) ||
+ newValue.text != oldValue.text.replaceRange(end - 1, end, '')) {
+ return newValue;
+ }
+ final before = oldValue.text.substring(0, end);
+ final after = oldValue.text.substring(end);
+ if (after.isNotEmpty && !after.startsWith(RegExp(r'[\s.,!?;:]'))) {
+ return newValue;
+ }
+ for (final tag in tags()) {
+ final start = end - tag.length;
+ if (!before.endsWith(tag) ||
+ (start > 0 && !before[start - 1].contains(RegExp(r'\s')))) {
+ continue;
+ }
+ return TextEditingValue(
+ text: oldValue.text.replaceRange(start, end, ''),
+ selection: TextSelection.collapsed(offset: start),
+ );
+ }
+ return newValue;
+ }
+}
+
/// Records its row's context while built, so [_SuperTabViewState] can find
/// the row a message is shown in.
class _BuiltRow extends StatefulWidget {
diff --git a/desktop/test/super_tab_composer_flow_test.dart b/desktop/test/super_tab_composer_flow_test.dart
new file mode 100644
index 000000000..ec6c782da
--- /dev/null
+++ b/desktop/test/super_tab_composer_flow_test.dart
@@ -0,0 +1,350 @@
+import 'dart:async';
+
+import 'package:flutter/gestures.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/message_row.dart';
+import 'package:harness/super_tabs/view.dart';
+
+import 'support/super_tab_fixture.dart';
+
+void main() {
+ Future<SuperTabController> show(
+ WidgetTester tester,
+ ConversationServer server,
+ ) async {
+ final c = server.controller();
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ addTearDown(c.dispose);
+ return c;
+ }
+
+ final composer = find.byKey(const ValueKey('super-message-composer'));
+ FocusNode composerFocus(WidgetTester tester) =>
+ tester.widget<TextField>(composer).focusNode!;
+ String composerText(WidgetTester tester) =>
+ tester.widget<TextField>(composer).controller!.text;
+
+ for (final chat in ['a workgroup', 'the chat with the PM']) {
+ testWidgets(
+ 'Reply in $chat puts the cursor in the composer, reply attached',
+ (tester) async {
+ final server = ConversationServer();
+ if (chat == 'the chat with the PM') {
+ // The reader's own chat: its audience is the reader alone.
+ final pm = (server.state['conversations'] as List)[1] as Map;
+ pm['audience'] = {
+ 'people': [
+ {'id': 'owner', 'generation': 'fixture'},
+ ],
+ };
+ server.append(
+ 'Which build should I test?',
+ conversationId: pm['id'] as String,
+ );
+ } else {
+ server.append('Which build should I test?');
+ }
+ final c = await show(tester, server);
+ if (chat == 'the chat with the PM') {
+ c.select('offline');
+ await tester.pumpAndSettle();
+ expect(c.pmChat(c.selected!.projectId)?.id, 'offline');
+ }
+ // Reading the transcript first: the composer has given up focus.
+ FocusManager.instance.primaryFocus?.unfocus();
+ await tester.pumpAndSettle();
+ expect(composerFocus(tester).hasFocus, isFalse);
+
+ // Ken's path: the mouse rests on the message, its toolbar shows, and
+ // the reply arrow is clicked.
+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
+ await mouse.addPointer(location: Offset.zero);
+ addTearDown(mouse.removePointer);
+ await mouse.moveTo(
+ tester.getCenter(find.text('Which build should I test?')),
+ );
+ await tester.pumpAndSettle();
+ final reply = tester.getCenter(find.byTooltip('Reply'));
+ await mouse.moveTo(reply);
+ await tester.pumpAndSettle();
+ await mouse.down(reply);
+ await tester.pump(const Duration(milliseconds: 40));
+ await mouse.up();
+ await tester.pump();
+ void typesInComposer() {
+ expect(find.byType(SuperTabReplyPreview), findsOneWidget);
+ expect(composerFocus(tester).hasPrimaryFocus, isTrue);
+ // Focus alone is not typing: the keyboard reaches the field only
+ // over its text input connection.
+ expect(tester.testTextInput.hasAnyClients, isTrue);
+ }
+
+ typesInComposer();
+ await tester.pumpAndSettle();
+ typesInComposer();
+ // The pointer leaves the message and its toolbar goes.
+ await mouse.moveTo(tester.getCenter(composer));
+ await tester.pumpAndSettle();
+ typesInComposer();
+ tester.testTextInput.updateEditingValue(
+ const TextEditingValue(
+ text: 'The arm64 one',
+ selection: TextSelection.collapsed(offset: 13),
+ ),
+ );
+ await tester.pump();
+ expect(composerText(tester), 'The arm64 one');
+ await tester.pump(const Duration(seconds: 1));
+ },
+ variant: TargetPlatformVariant.only(TargetPlatform.macOS),
+ );
+ }
+
+ ConversationServer withBuilder() {
+ final server = ConversationServer();
+ server.state['agents'] = [
+ {
+ 'id': 'builder',
+ 'name': 'Builder',
+ 'machineId': 'host',
+ 'harnessId': 'session',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'codex'},
+ },
+ ];
+ for (final group in server.state['conversations'] as List) {
+ (group as Map)['agentIds'] = ['builder'];
+ }
+ return server;
+ }
+
+ Future<void> tagBuilder(WidgetTester tester, String before) async {
+ await tester.tap(composer);
+ await tester.enterText(composer, '$before@Bu');
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ }
+
+ testWidgets(
+ 'Backspace right after a tag removes the whole tag and its agent',
+ (tester) async {
+ final c = await show(tester, withBuilder());
+ await tagBuilder(tester, 'Please check ');
+ expect(composerText(tester), 'Please check @Builder ');
+ expect(c.mentions(c.selectedId), {'builder': '@Builder'});
+ // The list of agents came and went above the field; the keyboard still
+ // reaches it.
+ expect(tester.testTextInput.hasAnyClients, isTrue);
+
+ // The space the tag brought goes first, as any character does.
+ await tester.sendKeyEvent(LogicalKeyboardKey.backspace);
+ await tester.pumpAndSettle();
+ expect(composerText(tester), 'Please check @Builder');
+ expect(c.mentions(c.selectedId), {'builder': '@Builder'});
+
+ await tester.sendKeyEvent(LogicalKeyboardKey.backspace);
+ await tester.pumpAndSettle();
+ expect(composerText(tester), 'Please check ');
+ expect(
+ tester.widget<TextField>(composer).controller!.selection,
+ const TextSelection.collapsed(offset: 13),
+ );
+ expect(c.mentions(c.selectedId), isEmpty);
+ // No list of agents springs up in its place.
+ expect(
+ find.byKey(const ValueKey('super-composer-completions')),
+ findsNothing,
+ );
+ await tester.pump(const Duration(seconds: 1));
+ },
+ variant: TargetPlatformVariant.only(TargetPlatform.macOS),
+ );
+
+ Future<void> send(WidgetTester tester, String text) async {
+ await tester.tap(composer);
+ await tester.enterText(composer, text);
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ }
+
+ Finder outgoingRow(String text) => find.ancestor(
+ of: find.text(text),
+ matching: find.byKey(const ValueKey('super-outgoing')),
+ );
+
+ void composerKeepsKeyboard(WidgetTester tester) {
+ expect(composerText(tester), isEmpty);
+ expect(composerFocus(tester).hasPrimaryFocus, isTrue);
+ expect(tester.testTextInput.hasAnyClients, isTrue);
+ }
+
+ testWidgets('Enter shows the message at once as sending, in place, and '
+ 'once when the server confirms it', (tester) async {
+ final server = _HeldServer()..append('Which build?');
+ await show(tester, server);
+ final post = server.holdPosts = Completer<void>();
+ await send(tester, 'The arm64 one');
+
+ expect(outgoingRow('The arm64 one'), findsOneWidget);
+ expect(find.text('Sending…'), findsOneWidget);
+ composerKeepsKeyboard(tester);
+
+ post.complete();
+ await tester.pumpAndSettle();
+ expect(find.text('The arm64 one'), findsOneWidget);
+ expect(outgoingRow('The arm64 one'), findsNothing);
+ expect(find.text('Sending…'), findsNothing);
+ composerKeepsKeyboard(tester);
+ await tester.pump(const Duration(seconds: 1));
+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
+
+ testWidgets('a send with no answer reads Not sent with Retry, which shows '
+ 'it once', (tester) async {
+ final server = ConversationServer()..loseReply = true;
+ await show(tester, server);
+ await send(tester, 'Did this arrive?');
+ await tester.pumpAndSettle();
+
+ expect(outgoingRow('Did this arrive?'), findsOneWidget);
+ expect(find.text('Not sent'), findsOneWidget);
+ // The row says it; the line under the chat does not repeat it.
+ expect(
+ find.text('The action is not confirmed. Retry to check it.'),
+ findsNothing,
+ );
+ composerKeepsKeyboard(tester);
+
+ await tester.tap(find.text('Retry'));
+ await tester.pumpAndSettle();
+ expect(server.messages, hasLength(1));
+ expect(find.text('Did this arrive?'), findsOneWidget);
+ expect(outgoingRow('Did this arrive?'), findsNothing);
+ expect(find.text('Not sent'), findsNothing);
+ await tester.pump(const Duration(seconds: 1));
+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
+
+ testWidgets('a refused send reads Not sent with its reason; Retry sends '
+ 'it once, with its reply', (tester) async {
+ final server = ConversationServer()..append('Which build?');
+ await show(tester, server);
+ await tester.tap(find.byTooltip('Reply'));
+ await tester.pumpAndSettle();
+ server.reject = true;
+ await send(tester, 'The arm64 one');
+ await tester.pumpAndSettle();
+
+ expect(outgoingRow('The arm64 one'), findsOneWidget);
+ expect(find.text('Not sent'), findsOneWidget);
+ expect(find.text('Choose an agent in this conversation.'), findsOneWidget);
+ expect(find.text('Edit'), findsNothing);
+ // The reply went with the message: the composer holds none.
+ expect(find.byTooltip('Cancel reply'), findsNothing);
+
+ server.reject = false;
+ await tester.tap(find.text('Retry'));
+ await tester.pumpAndSettle();
+ expect(outgoingRow('The arm64 one'), findsNothing);
+ expect(find.text('Not sent'), findsNothing);
+ expect(server.messages.where((m) => m['text'] == 'The arm64 one'), [
+ containsPair('replyTo', 'message-1'),
+ ]);
+ composerKeepsKeyboard(tester);
+ await tester.pump(const Duration(seconds: 1));
+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
+
+ for (final failure in ['refused', 'unanswered']) {
+ testWidgets('Delete removes a $failure message from the chat', (
+ tester,
+ ) async {
+ final server = ConversationServer();
+ await show(tester, server);
+ if (failure == 'refused') {
+ server.reject = true;
+ } else {
+ server.loseReply = true;
+ }
+ await send(tester, 'Never mind');
+ await tester.pumpAndSettle();
+ expect(outgoingRow('Never mind'), findsOneWidget);
+ // A destructive action reads in the error colour.
+ final delete = tester.element(find.text('Delete'));
+ expect(
+ DefaultTextStyle.of(delete).style.color,
+ Theme.of(delete).colorScheme.error,
+ );
+ // Actions read as links in the line: no fill or rim at rest, a focus
+ // ring when the keyboard is on them.
+ for (final label in ['Retry', 'Delete']) {
+ final button = find.ancestor(
+ of: find.text(label),
+ matching: find.byType(TextButton),
+ );
+ final fill = tester
+ .widget<Material>(
+ find.descendant(of: button, matching: find.byType(Material)),
+ )
+ .color;
+ expect(fill?.a ?? 0, 0, reason: '$label has a fill at rest');
+ final side = tester.widget<TextButton>(button).style!.side!;
+ expect(side.resolve({})!.color.a, 0, reason: '$label has a rim');
+ expect(side.resolve({WidgetState.focused})!.color.a, greaterThan(0));
+ // Hover is the shared neutral wash, never a tint of the label.
+ final quiet = Theme.of(tester.element(button))
+ .textButtonTheme
+ .style!
+ .overlayColor!;
+ final overlay = tester.widget<TextButton>(button).style!.overlayColor;
+ for (final state in [WidgetState.hovered, WidgetState.pressed]) {
+ expect(
+ overlay?.resolve({state}),
+ quiet.resolve({state}),
+ reason: '$label ${state.name}',
+ );
+ }
+ }
+
+ await tester.tap(find.text('Delete'));
+ await tester.pumpAndSettle();
+ expect(outgoingRow('Never mind'), findsNothing);
+ expect(find.text('Not sent'), findsNothing);
+ composerKeepsKeyboard(tester);
+ await tester.pump(const Duration(seconds: 1));
+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
+ }
+}
+
+/// A server whose commands wait for [holdPosts] while it is set.
+class _HeldServer extends ConversationServer {
+ Completer<void>? holdPosts;
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String method,
+ String path, {
+ Map<String, dynamic>? body,
+ }) async {
+ if (method == 'POST') await holdPosts?.future;
+ return super.request(method, path, body: body);
+ }
+}
diff --git a/desktop/test/super_tab_controller_test.dart b/desktop/test/super_tab_controller_test.dart
index 79969c4f9..b6fdae4c8 100644
--- a/desktop/test/super_tab_controller_test.dart
+++ b/desktop/test/super_tab_controller_test.dart
@@ -267,7 +267,12 @@ void main() {
expect(await first.send(), isNull);
expect(server.messages, hasLength(1));
expect(first.hasPendingAction, isTrue);
- expect(first.draft('lead'), 'Build the agreed plan.');
+ // The message waits in the chat for Retry; the draft is free.
+ expect(first.draft('lead'), isEmpty);
+ expect(
+ first.outgoing('lead').single.state,
+ SuperTabOutgoingState.unconfirmed,
+ );
await first.flush();
first.dispose();
final reopened = server.controller(initial: server.saved);
@@ -324,10 +329,14 @@ void main() {
server.reject = true;
await controller.retry();
expect(controller.hasPendingAction, isFalse);
- expect(controller.draft('lead'), 'Hold this draft');
+ expect(
+ controller.outgoing('lead').single.state,
+ SuperTabOutgoingState.refused,
+ );
server.reject = false;
- await controller.send();
- expect(server.messages, hasLength(1));
+ await controller.retryOutgoing(controller.outgoing('lead').single);
+ expect(server.messages.single['text'], 'Hold this draft');
+ expect(controller.outgoing('lead'), isEmpty);
});
test(
diff --git a/desktop/test/super_tab_folder_drop_test.dart b/desktop/test/super_tab_folder_drop_test.dart
index 094063c35..d9d4d16a5 100644
--- a/desktop/test/super_tab_folder_drop_test.dart
+++ b/desktop/test/super_tab_folder_drop_test.dart
@@ -91,15 +91,19 @@ void main() {
);
/// Lets files be read and the zip's isolate answer, a frame at a time,
- /// until [done].
- Future<void> settle(WidgetTester tester, bool Function() done) async {
+ /// until [done]. While a message is [sending] its spinner never settles.
+ Future<void> settle(
+ WidgetTester tester,
+ bool Function() done, {
+ bool sending = false,
+ }) async {
for (var i = 0; i < 200 && !done(); i++) {
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 20)),
);
await tester.pump();
}
- await tester.pumpAndSettle();
+ if (!sending) await tester.pumpAndSettle();
}
/// Drops on the composer: [method] and [arguments] as the platform sends
@@ -360,7 +364,7 @@ void main() {
await tester.tap(find.byTooltip('Send message'));
await tester.pump();
// The zip has its answer while the send still waits on the server.
- await settle(tester, () => names(controller).isNotEmpty);
+ await settle(tester, () => names(controller).isNotEmpty, sending: true);
server.holdReads!.complete();
server.holdReads = null;
await tester.pumpAndSettle();
@@ -373,8 +377,8 @@ void main() {
await close(tester, controller);
});
- testWidgets('a message that fails to send keeps offering its folder as a '
- 'zip', (tester) async {
+ testWidgets('a refused message keeps its folder path, and Retry sends '
+ 'it', (tester) async {
final controller = await open(tester, machineId: 'studio');
await drop(tester, [
folder('src').path,
@@ -383,11 +387,14 @@ void main() {
server.refuse = {'code': 'CONFLICT', 'message': 'Try again.'};
await tester.tap(find.byTooltip('Send message'));
await tester.pumpAndSettle();
+ // The refused message waits in the chat with its path.
+ server.refuse = null;
+ await tester.tap(find.text('Retry'));
+ await tester.pumpAndSettle();
- expect(hint, findsOneWidget);
expect(
- find.descendant(of: hint, matching: find.text('Attach as zip')),
- findsOneWidget,
+ (server.messages.single['text'] as String),
+ contains(folder('src').path),
);
await close(tester, controller);
});
diff --git a/desktop/test/super_tab_outgoing_shots_test.dart b/desktop/test/super_tab_outgoing_shots_test.dart
new file mode 100644
index 000000000..4d8914bc8
--- /dev/null
+++ b/desktop/test/super_tab_outgoing_shots_test.dart
@@ -0,0 +1,111 @@
+import 'dart:async';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/view.dart';
+
+import 'box_render_preview_test.dart' show loadPreviewFonts;
+import 'support/super_tab_fixture.dart';
+
+/// Set to a folder to write the PR's screenshots there.
+final shots = Platform.environment['SUPER_TAB_OUTGOING_SHOTS'];
+
+/// A sent message as the PR shows it: sending, sent with no answer, and
+/// refused, in both appearances.
+void main() {
+ setUpAll(() async {
+ if (shots != null) await loadPreviewFonts();
+ });
+
+ for (final brightness in Brightness.values) {
+ testWidgets('screenshots for review (${brightness.name})', (tester) async {
+ final picture = GlobalKey();
+ final server = _HeldServer()..append('Which build should I test first?');
+ // A chat with a Lead, so the earlier message reads as sent.
+ ((server.state['conversations'] as List)[0] as Map)['leadId'] = 'pm';
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.light);
+ await tester.binding.setSurfaceSize(const Size(900, 560));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) =>
+ RepaintBoundary(key: picture, child: child),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Mac Studio',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ Future<void> shot(String name) => tester.runAsync(() async {
+ final boundary =
+ picture.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary;
+ final image = await boundary.toImage(pixelRatio: 1.5);
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(shots!).create(recursive: true);
+ await File('$shots/outgoing-$name-${brightness.name}.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+
+ final composer = find.byKey(const ValueKey('super-message-composer'));
+ Future<void> send(String text) async {
+ await tester.tap(composer);
+ await tester.enterText(composer, text);
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ }
+
+ final post = server.holdPosts = Completer<void>();
+ await send('The arm64 one, please');
+ await tester.pump(const Duration(milliseconds: 300));
+ await shot('sending');
+ server.loseReply = true;
+ post.complete();
+ await tester.pumpAndSettle();
+ await shot('not-sent');
+ await tester.tap(find.text('Delete'));
+ await tester.pumpAndSettle();
+
+ server.reject = true;
+ await send('@Builder check the arm64 build');
+ await tester.pumpAndSettle();
+ await shot('refused');
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ }, skip: shots == null);
+ }
+}
+
+/// A server whose commands wait for [holdPosts] while it is set.
+class _HeldServer extends ConversationServer {
+ Completer<void>? holdPosts;
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String method,
+ String path, {
+ Map<String, dynamic>? body,
+ }) async {
+ if (method == 'POST') await holdPosts?.future;
+ return super.request(method, path, body: body);
+ }
+}
diff --git a/desktop/test/super_tab_outgoing_test.dart b/desktop/test/super_tab_outgoing_test.dart
new file mode 100644
index 000000000..9e9c90b89
--- /dev/null
+++ b/desktop/test/super_tab_outgoing_test.dart
@@ -0,0 +1,246 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/controller.dart';
+
+import 'support/super_tab_fixture.dart';
+
+void main() {
+ /// A controller whose sends wait for [hold] while it is set.
+ ({SuperTabController controller, ConversationServer server}) open({
+ Completer<void>? Function()? hold,
+ Map<String, dynamic>? initial,
+ ConversationServer? server,
+ }) {
+ final s = server ?? ConversationServer();
+ final controller = SuperTabController(
+ tabId: 'tab',
+ accountId: 'owner',
+ save: s.save,
+ initial: initial ?? const {},
+ pollInterval: Duration.zero,
+ request: (method, path, {body}) async {
+ if (method == 'POST') await hold?.call()?.future;
+ return s.request(method, path, body: body);
+ },
+ );
+ addTearDown(() async {
+ await controller.flush();
+ controller.dispose();
+ });
+ return (controller: controller, server: s);
+ }
+
+ List<(String, SuperTabOutgoingState)> outgoing(SuperTabController c) => [
+ for (final m in c.outgoing('lead')) (m.text, m.state),
+ ];
+
+ test('a message is outgoing from the moment it is sent until the transcript '
+ 'holds it, and the draft is free at once', () async {
+ final post = Completer<void>();
+ final (:controller, :server) = open(hold: () => post);
+ await controller.refresh();
+ controller.setDraft('lead', 'Please check the arm64 build');
+
+ final sending = controller.send();
+ await Future<void>.delayed(Duration.zero);
+ expect(controller.draft('lead'), isEmpty);
+ expect(outgoing(controller), [
+ ('Please check the arm64 build', SuperTabOutgoingState.sending),
+ ]);
+
+ post.complete();
+ await sending;
+ expect(outgoing(controller), isEmpty);
+ expect(controller.messages('lead').map((m) => m.text), [
+ 'Please check the arm64 build',
+ ]);
+ });
+
+ test('a confirmed message the transcript does not hold yet stays outgoing, '
+ 'once, and leaves when a read brings it', () async {
+ final (:controller, :server) = open();
+ await controller.refresh();
+ controller.setDraft('lead', 'Ship it');
+ // The send lands; the read after it does not.
+ server.failReads = true;
+ await controller.send();
+ expect(outgoing(controller), [('Ship it', SuperTabOutgoingState.sending)]);
+ expect(controller.messages('lead'), isEmpty);
+
+ server.failReads = false;
+ await controller.refresh();
+ expect(outgoing(controller), isEmpty);
+ expect(controller.messages('lead').map((m) => m.text), ['Ship it']);
+ });
+
+ test(
+ 'a send whose answer is lost is unconfirmed; Retry sends it once',
+ () async {
+ final (:controller, :server) = open(
+ server: ConversationServer()..loseReply = true,
+ );
+ await controller.refresh();
+ controller.setDraft('lead', 'Build the agreed plan.');
+ expect(await controller.send(), isNull);
+ expect(controller.draft('lead'), isEmpty);
+ expect(outgoing(controller), [
+ ('Build the agreed plan.', SuperTabOutgoingState.unconfirmed),
+ ]);
+
+ await controller.retry();
+ expect(server.posts[0]['operationId'], server.posts[1]['operationId']);
+ expect(server.messages, hasLength(1));
+ expect(outgoing(controller), isEmpty);
+ expect(controller.messages('lead').map((m) => m.text), [
+ 'Build the agreed plan.',
+ ]);
+ },
+ );
+
+ test('an unconfirmed message the transcript already holds is not shown '
+ 'twice', () async {
+ final (:controller, :server) = open(
+ server: ConversationServer()..loseReply = true,
+ );
+ await controller.refresh();
+ controller.setDraft('lead', 'Once only');
+ await controller.send();
+ // The backend names a person's message by the send's operation id.
+ final sent = server.messages.single;
+ sent['id'] = server.posts.single['operationId'];
+ await controller.refresh();
+ expect(controller.messages('lead').map((m) => m.text), ['Once only']);
+ expect(outgoing(controller), isEmpty);
+ });
+
+ test('a refused message keeps its text and reason after a restart too; '
+ 'Retry sends it as it was, tags and reply included', () async {
+ final server = ConversationServer()
+ ..append('Which build?')
+ ..state['agents'] = [
+ {
+ 'id': 'builder',
+ 'name': 'Builder',
+ 'machineId': 'host',
+ 'harnessId': 'session',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'codex'},
+ },
+ ];
+ ((server.state['conversations'] as List)[0] as Map)['agentIds'] = [
+ 'builder',
+ ];
+ final first = open(server: server).controller;
+ await first.refresh();
+ first.setDraft('lead', '@Builder the arm64 one');
+ first.mention('lead', 'builder', '@Builder');
+ server.reject = true;
+ await first.send(replyTo: 'message-1');
+ expect(first.draft('lead'), isEmpty);
+ final refused = first.outgoing('lead').single;
+ expect(refused.state, SuperTabOutgoingState.refused);
+ expect(refused.text, '@Builder the arm64 one');
+ expect(refused.error, 'Choose an agent in this conversation.');
+ await first.flush();
+
+ final reopened = open(server: server, initial: server.saved).controller;
+ await reopened.refresh();
+ expect(
+ reopened.outgoing('lead').single.state,
+ SuperTabOutgoingState.refused,
+ );
+ server.reject = false;
+ await reopened.retryOutgoing(reopened.outgoing('lead').single);
+ expect(reopened.outgoing('lead'), isEmpty);
+ expect(reopened.draft('lead'), isEmpty);
+ expect(server.messages.last['text'], '@Builder the arm64 one');
+ expect(server.messages.last['replyTo'], 'message-1');
+ expect(server.posts.last['command']['recipientIds'], ['builder']);
+ });
+
+ test('losing access drops what was waiting to be shown', () async {
+ final (:controller, :server) = open(
+ server: ConversationServer()..reject = true,
+ );
+ await controller.refresh();
+ controller.setDraft('lead', 'Private');
+ await controller.send();
+ expect(controller.outgoing('lead'), hasLength(1));
+ controller.revokeAccess('Access removed.');
+ expect(controller.outgoing('lead'), isEmpty);
+ });
+
+ test('Delete removes a refused message, and nothing is sent', () async {
+ final (:controller, :server) = open(
+ server: ConversationServer()..reject = true,
+ );
+ await controller.refresh();
+ controller.setDraft('lead', 'Not this one');
+ await controller.send();
+ controller.discardOutgoing(controller.outgoing('lead').single);
+ expect(controller.outgoing('lead'), isEmpty);
+ expect(controller.operationError, isNull);
+ await controller.flush();
+ expect(server.saved!.containsKey('refused'), isFalse);
+ expect(server.messages, isEmpty);
+ });
+
+ test('Delete of an unconfirmed message that did arrive shows it once on the '
+ 'next read', () async {
+ final (:controller, :server) = open(
+ server: ConversationServer()..loseReply = true,
+ );
+ await controller.refresh();
+ controller.setDraft('lead', 'It got there');
+ await controller.send();
+ expect(
+ controller.outgoing('lead').single.state,
+ SuperTabOutgoingState.unconfirmed,
+ );
+ // The server took it and its answer was lost; the read after failed too.
+ expect(server.messages, hasLength(1));
+
+ controller.discardOutgoing(controller.outgoing('lead').single);
+ expect(controller.outgoing('lead'), isEmpty);
+ expect(controller.hasPendingAction, isFalse);
+ await controller.refresh();
+ expect(controller.messages('lead').map((m) => m.text), ['It got there']);
+ expect(controller.outgoing('lead'), isEmpty);
+ await controller.flush();
+ expect(server.saved!.containsKey('pending'), isFalse);
+ });
+
+ test('a refused message stays when the next one is sent, and a second '
+ 'refusal keeps both, until each is sent again or deleted', () async {
+ final (:controller, :server) = open();
+ await controller.refresh();
+ server.reject = true;
+ controller.setDraft('lead', 'First');
+ await controller.send();
+ server.reject = false;
+ controller.setDraft('lead', 'Second');
+ await controller.send();
+ expect(outgoing(controller), [('First', SuperTabOutgoingState.refused)]);
+ expect(controller.messages('lead').map((m) => m.text), ['Second']);
+
+ server.reject = true;
+ controller.setDraft('lead', 'Third');
+ await controller.send();
+ expect(outgoing(controller), [
+ ('First', SuperTabOutgoingState.refused),
+ ('Third', SuperTabOutgoingState.refused),
+ ]);
+ await controller.flush();
+ final reopened = open(server: server, initial: server.saved).controller;
+ await reopened.refresh();
+ expect(outgoing(reopened), outgoing(controller));
+
+ server.reject = false;
+ await reopened.retryOutgoing(reopened.outgoing('lead').first);
+ expect(server.messages.last['text'], 'First');
+ expect(outgoing(reopened), [('Third', SuperTabOutgoingState.refused)]);
+ reopened.discardOutgoing(reopened.outgoing('lead').single);
+ expect(outgoing(reopened), isEmpty);
+ });
+}