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
Show delivery receipts under the latest own Swarm message (#1534)
tony496sc6aa10e4d090
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex 8ef8b2ac9..1817519d4 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -564,6 +564,59 @@ describe('Super Tabs on a real Mongo replica set', () => {expect((await store.messages(owner, tab, 'lead', {})).messages[1]!.author).toMatchObject({ displayName })})+ it('stores the current delivery hold and its first time even after the compatibility notice exists', async () => {+ const { tab, lead } = await fixture()+ let now = Date.now()+ const timed = new SuperTabStore(db, () => now)+ await run(tab, message('Keep the reason beside this instruction.'))+ const delivery = (await store.deliveries(host, tab, lead))[0]!+ await timed.delivery(host, tab, lead, delivery.id, { type: 'claim', claimId: 'claim' })+ const since = new Date(now)+ for (const reason of ['team_waiting_idle', 'team_waiting_user', 'team_waiting_draft', 'team_waiting_control', 'team_waiting_unavailable'] as const) {+ await timed.delivery(host, tab, lead, delivery.id, { type: 'hold', claimId: 'claim', reason })+ expect(await db.superTabDelivery.findUnique({ where: { id: delivery.id } })).toMatchObject({ holdReason: reason, holdSince: since })+ const rows = (await timed.messages(owner, tab, 'lead', {})).messages+ expect(rows).toHaveLength(2)+ expect(rows[0]!.deliveries[0]).toMatchObject({ holdReason: reason, holdSince: since })+ expect(rows[1]).toMatchObject({ source: { kind: 'delivery-hold', messageId: delivery.messageId, deliveryId: delivery.id, agentId: lead },+ text: expect.stringContaining('It stays queued and goes in by itself') })+ now += 5000+ }+ })++ it.each(['delivered', 'answered', 'cancelled'] as const)('clears a delivery hold when it becomes %s', async status => {+ const { tab, lead } = await fixture()+ await run(tab, message('Finish this held instruction.'))+ const delivery = (await store.deliveries(host, tab, lead))[0]!+ await store.delivery(host, tab, lead, delivery.id, { type: 'claim', claimId: 'claim' })+ await store.delivery(host, tab, lead, delivery.id, { type: 'hold', claimId: 'claim', reason: 'team_waiting_idle' })+ if (status === 'delivered') await store.delivery(host, tab, lead, delivery.id, { type: 'ack', claimId: 'claim', receipt: 'typed', uncertain: false })+ else if (status === 'answered') await run(tab, { type: 'message.send', conversationId: 'lead', text: 'Finished.', replyTo: delivery.messageId, recipientIds: [] }, host, lead)+ else await run(tab, { type: 'agent.remove', agentId: lead })+ const saved = await db.superTabDelivery.findUnique({ where: { id: delivery.id } })+ expect(saved).toMatchObject({ status, holdReason: null, holdSince: null })+ const row = (await store.messages(owner, tab, 'lead', { messageId: delivery.messageId })).messages[0]!+ expect(row.deliveries[0]).toMatchObject({ status, holdReason: null, holdSince: null })+ })++ it('keeps delivery and answer times stable, including an answer after the terminal acknowledged delivery', async () => {+ const { tab, lead } = await fixture()+ let now = Date.now()+ const timed = new SuperTabStore(db, () => now)+ await run(tab, message('Record this reply duration.'))+ const delivery = (await store.deliveries(host, tab, lead))[0]!+ await timed.delivery(host, tab, lead, delivery.id, { type: 'claim', claimId: 'claim' })+ await timed.delivery(host, tab, lead, delivery.id, { type: 'ack', claimId: 'claim', receipt: 'typed', uncertain: false })+ const deliveredAt = new Date(now)+ now += 72000+ await timed.delivery(host, tab, lead, delivery.id, { type: 'ack', claimId: 'claim', receipt: 'typed', uncertain: false })+ await timed.execute(host, tab, { operationId: randomUUID(), command: {+ type: 'message.send', conversationId: 'lead', text: 'Done.', replyTo: delivery.messageId, recipientIds: [],+ } }, lead)+ const row = (await timed.messages(owner, tab, 'lead', { messageId: delivery.messageId })).messages[0]!+ expect(row.deliveries[0]).toMatchObject({ status: 'answered', deliveredAt, answeredAt: new Date(now) })+ })+it('a withdrawn host can retire its receipt without regaining conversation access', async () => {const { tab, lead } = await fixture()await run(tab, message('Keep the execution receipt after removal.'))diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex a398e75ef..14fbf9568 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -1096,6 +1096,11 @@ model SuperTabDelivery {status String @default("queued")claimId String?receipt String?+ // Optional on older records: backend first, then Desktop's inline receipt.+ holdReason String?+ holdSince DateTime?+ deliveredAt DateTime?+ answeredAt DateTime?createdAt DateTime @default(now())updatedAt DateTime @updatedAtdiff --git a/backend/src/superTabs/native.ts b/backend/src/superTabs/native.tsindex bdbefdef6..0058bf011 100644--- a/backend/src/superTabs/native.ts+++ b/backend/src/superTabs/native.ts@@ -181,6 +181,7 @@ export async function revokeNativeContexts(tx: Transaction, before: SuperTabStatconst revoked = await tx.superTabNativeContext.findMany({ where, select: { id: true } })await tx.superTabNativeContext.updateMany({ where, data: { revoked: true } })if (revoked.length) await tx.superTabDelivery.updateMany({ where: { tabId: before.id,- nativeContextId: { in: revoked.map(r => r.id) }, status: { in: ['queued', 'claimed', 'uncertain'] } }, data: { status: 'cancelled' } })+ nativeContextId: { in: revoked.map(r => r.id) }, status: { in: ['queued', 'claimed', 'uncertain'] } },+ data: { status: 'cancelled', holdReason: null, holdSince: null } })}}diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 6f1ad67fb..6a3a5ed8b 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -367,6 +367,8 @@ export class SuperTabStore {context.delivery = { ...delivery, text: message.text, ...(message.attachments ? { attachments: message.attachments as unknown as Attachment[] } : {}) }await tx.superTabDelivery.update({ where: { id: delivery.id }, data: {status: command.resolution === 'received' ? 'confirmed' : command.resolution === 'resend' ? 'superseded' : 'cancelled',+ holdReason: null, holdSince: null,+ ...(command.resolution === 'received' ? { deliveredAt: delivery.deliveredAt ?? new Date(context.now) } : {}),// The native receipt remains intact; the operation records the person's resolution.} })}@@ -407,7 +409,7 @@ export class SuperTabStore {// Keep immutable history and operation receipts for audit/replay; all// reads require a live conversation. No removed group can deliver work.await tx.superTabDelivery.updateMany({ where: { tabId, conversationId: { in: removedGroups.map(c => c.id) },- status: { in: ['queued', 'claimed', 'uncertain'] } }, data: { status: 'cancelled' } })+ status: { in: ['queued', 'claimed', 'uncertain'] } }, data: { status: 'cancelled', holdReason: null, holdSince: null } })}const revision = row.revision + 1if (command.type === 'agent.add' || command.type === 'agent.started' || command.type === 'agent.configuration') {@@ -472,7 +474,7 @@ export class SuperTabStore {if (activeWork(changed)) continueawait tx.superTabRun.deleteMany({ where: { tabId, assignmentId: group.assignment!.id } })await tx.superTabDelivery.updateMany({ where: { tabId, assignmentId: group.assignment!.id,- status: { in: ['queued', 'claimed', 'uncertain'] } }, data: { status: 'cancelled' } })+ status: { in: ['queued', 'claimed', 'uncertain'] } }, data: { status: 'cancelled', holdReason: null, holdSince: null } })}await tx.superTab.update({ where: { id: tabId, revision: row.revision }, data: {revision, state: json(effects.state), ...indexes(effects.state),@@ -492,13 +494,15 @@ export class SuperTabStore {// delivery was finally typed. An agent's reply settles that agent's own deliveries of the message.if (command.type === 'message.send' && command.replyTo && actor.kind === 'agent') {await tx.superTabDelivery.updateMany({ where: { tabId, messageId: command.replyTo, agentId: actor.agentId,- status: { in: ['queued', 'claimed', 'uncertain'] } }, data: { status: 'answered' } })+ status: { in: ['queued', 'claimed', 'uncertain', 'delivered', 'confirmed'] } },+ data: { status: 'answered', answeredAt: new Date(context.now), holdReason: null, holdSince: null } })}if (command.type === 'project.report' && actor.kind === 'agent') {const progress = projectsOf(original).find(p => p.id === command.projectId)?.progressif (progress?.requestMessageId && command.throughRevision >= progress.requestedRevision) {await tx.superTabDelivery.updateMany({ where: { tabId, agentId: actor.agentId, messageId: progress.requestMessageId,- status: { in: ['queued', 'claimed', 'uncertain', 'delivered'] } }, data: { status: 'answered' } })+ status: { in: ['queued', 'claimed', 'uncertain', 'delivered', 'confirmed'] } },+ data: { status: 'answered', answeredAt: new Date(context.now), holdReason: null, holdSince: null } })}}const revoked = [@@ -511,7 +515,7 @@ export class SuperTabStore {...revoked, ...(effects.cancelledAgents.length ? [{ agentId: { in: effects.cancelledAgents } }] : []),]if (cancelled.length) await tx.superTabDelivery.updateMany({ where: { tabId,- status: { in: ['queued', 'claimed', 'uncertain'] }, OR: cancelled }, data: { status: 'cancelled' } })+ status: { in: ['queued', 'claimed', 'uncertain'] }, OR: cancelled }, data: { status: 'cancelled', holdReason: null, holdSince: null } })for (const attempt of effects.previousAttempts) {await tx.superTabAttempt.create({ data: { id: attempt.assignment.id, tabId, conversationId: attempt.conversationId, snapshot: json(attempt) } })}@@ -611,7 +615,8 @@ export class SuperTabStore {const next = rows.length > 100 ? page.at(-1)!.sequence : nullif (!forward) page.reverse()const deliveries = page.length ? await tx.superTabDelivery.findMany({ where: { tabId, messageId: { in: page.map(m => m.id) } },- select: { id: true, messageId: true, agentId: true, status: true, receipt: true } }) : []+ select: { id: true, messageId: true, agentId: true, status: true, receipt: true,+ holdReason: true, holdSince: true, deliveredAt: true, answeredAt: true, createdAt: true, updatedAt: true } }) : []return { messages: page.map(m => ({ ...m, deliveries: deliveries.filter(d => d.messageId === m.id) })), next, revision: row.revision }})}@@ -884,7 +889,8 @@ export class SuperTabStore {// This write conflicts with concurrent revocation, even when only the delivery record changed.await tx.superTab.update({ where: { id: tabId, revision: row.revision }, data: { revision: { increment: 1 } } })const updated = await tx.superTabDelivery.update({ where: { id: delivery.id }, data: { status, claimId: action.claimId,- ...(action.type === 'ack' ? { receipt: action.receipt } : {}) } })+ ...(action.type === 'ack' ? { receipt: action.receipt, holdReason: null, holdSince: null,+ ...(!action.uncertain ? { deliveredAt: delivery.deliveredAt ?? new Date(this.now()) } : {}) } : {}) } })const message = await tx.superTabMessage.findUnique({ where: { id: delivery.messageId } })return { delivery: updated, message }})@@ -893,15 +899,22 @@ export class SuperTabStore {/** The host cannot type a claimed instruction yet. Say so once in the group, as the waiting agent; nobody is asked to act on it. */private async holdNotice(tx: Transaction, row: SuperTab, state: SuperTabState, delivery: SuperTabDelivery, reason: HoldReason) {const id = stableId('hold-notice', delivery.tabId, delivery.id)- if (delivery.status !== 'claimed' || await tx.superTabMessage.findUnique({ where: { id } })) return { noticed: false }+ if (delivery.status !== 'claimed') return { noticed: false }+ const notice = await tx.superTabMessage.findUnique({ where: { id } })+ if (notice && delivery.holdReason === reason && delivery.holdSince) return { noticed: false }+ // The notice is only sent once for older Desktops; the inline receipt keeps the current reason.+ await tx.superTabDelivery.update({ where: { id: delivery.id }, data: {+ holdReason: reason, holdSince: delivery.holdSince ?? new Date(this.now()),+ } })const group = conversation(state, delivery.conversationId), waiting = agent(state, delivery.agentId)const sender = author(state, { kind: 'agent', agentId: waiting.id, machineOwnerId: waiting.machineOwnerId })const revision = row.revision + 1- group.lastMessageSequence = revision+ if (!notice) group.lastMessageSequence = revisionawait tx.superTab.update({ where: { id: row.id, revision: row.revision }, data: { revision, state: json(state) } })- await this.writeMessages(tx, row.id, state, [{ id, conversationId: group.id, replyTo: null, recipients: [],+ if (!notice) await this.writeMessages(tx, row.id, state, [{ id, conversationId: group.id, replyTo: null, recipients: [],+ source: { kind: 'delivery-hold', messageId: delivery.messageId, deliveryId: delivery.id, agentId: delivery.agentId },text: holdNoticeText(sender.displayName ?? sender.name, reason), author: sender }], revision)- return { noticed: true }+ return { noticed: !notice }}/** Only the recorded execution host may attest that the actual session/attempt has stopped. */@@ -926,7 +939,7 @@ export class SuperTabStore {assignment.result = 'The execution host confirmed that this harness stopped.'await tx.superTabRun.deleteMany({ where: { tabId, assignmentId } })await tx.superTabDelivery.updateMany({ where: { tabId, assignmentId,- status: { in: ['queued', 'claimed', 'uncertain'] } }, data: { status: 'cancelled' } })+ status: { in: ['queued', 'claimed', 'uncertain'] } }, data: { status: 'cancelled', holdReason: null, holdSince: null } })await closeAssignment(tx, tabId, assignmentId, 'stopped', this.now())// No agent command closes this attempt, so nobody was told: in the two-account E2E of 2026-10-19// the Lead learned of a stopped worker only by re-reading status. Say it in the group, as thediff --git a/desktop/integration_test/super_tab_native_test.dart b/desktop/integration_test/super_tab_native_test.dartindex 6cdc7d9b5..3544ae1ef 100644--- a/desktop/integration_test/super_tab_native_test.dart+++ b/desktop/integration_test/super_tab_native_test.dart@@ -157,8 +157,24 @@ void main() {server.append('Keep changes on the device and sync when the connection returns.',);+ final instruction = server.messages.last;+ final deliveredAt = DateTime.now().subtract(const Duration(seconds: 42));+ instruction['deliveries'] = [+ // Typed loosely: the test advances this row through hold, uncertain and answered below.+ <String, Object?>{+ 'id': 'native-receipt',+ 'agentId': 'lead-agent',+ 'status': 'delivered',+ 'deliveredAt': deliveredAt.toIso8601String(),+ },+ ];server.append('Routed to Multiply');server.messages.last['source'] = routeRow()['source'];+ server.messages.last['author'] = {+ 'kind': 'agent',+ 'id': 'lead-agent',+ 'name': 'Lead',+ };server.routeDecisions['d1'] = decision();debugPrint('Swarm fixture: load conversation controller');final c = await tester.runAsync(() async {@@ -254,6 +270,46 @@ void main() {}await shot('conversation');+ expect(find.textContaining('Delivered '), findsOneWidget);+ expect(find.text('Queued'), findsNothing);+ final receipt =+ (instruction['deliveries'] as List).single as Map<String, Object?>;+ receipt.addAll({+ 'status': 'claimed',+ 'holdReason': 'team_waiting_idle',+ 'holdSince': DateTime.now()+ .subtract(const Duration(seconds: 34))+ .toIso8601String(),+ });+ await c.refresh();+ await tester.pump(const Duration(milliseconds: 100));+ expect(find.textContaining('Atlas is busy · waiting'), findsOneWidget);+ expect(+ find.text(+ "Atlas is finishing another task. Your message goes in by itself when it's done.",+ ),+ findsOneWidget,+ );+ await shot('receipt-held');+ receipt['status'] = 'uncertain';+ await c.refresh();+ await tester.pump(const Duration(milliseconds: 100));+ expect(find.text("Couldn't confirm delivery"), findsOneWidget);+ for (final label in ['Open terminal', 'Send again', 'It arrived']) {+ expect(find.text(label), findsOneWidget);+ }+ await shot('receipt-uncertain');+ receipt.addAll({+ 'status': 'answered',+ 'deliveredAt': deliveredAt.toIso8601String(),+ 'answeredAt': deliveredAt+ .add(const Duration(seconds: 72))+ .toIso8601String(),+ });+ await c.refresh();+ await tester.pump(const Duration(milliseconds: 100));+ expect(find.text('Replied · 1m 12s'), findsOneWidget);+ await shot('receipt-replied');expect(find.text('Lead'), findsNothing);expect(find.text('Atlas'), findsNWidgets(2));expect(find.text('Available capacity'), findsNothing);diff --git a/desktop/lib/shared/theme/app_icons.dart b/desktop/lib/shared/theme/app_icons.dartindex 9cc5a657d..a7d9f8a28 100644--- a/desktop/lib/shared/theme/app_icons.dart+++ b/desktop/lib/shared/theme/app_icons.dart@@ -44,6 +44,7 @@ abstract final class AppIcons {static const calendarDays = LucideIcons.calendarDays400;static const chartNoAxesColumn = LucideIcons.chartNoAxesColumn400;static const check = LucideIcons.check400;+ static const checkCheck = LucideIcons.checkCheck400;static const chevronDown = LucideIcons.chevronDown400;static const chevronLeft = LucideIcons.chevronLeft400;static const chevronRight = LucideIcons.chevronRight400;diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex a8f90e535..833dfb6e1 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -501,6 +501,48 @@ class SuperTabController extends ChangeNotifier {for (final m in _messages[id] ?? <SuperTabMessage>[]) m.id: m,for (final m in incoming) m.id: m,};+ final own = combined.values+ .where(+ (m) => !m.fromAgent && !m.fromTerminal && m.authorId == accountId,+ )+ .fold<SuperTabMessage?>(+ null,+ (latest, m) =>+ latest == null || m.sequence > latest.sequence ? m : latest,+ );+ if (!older &&+ own != null &&+ own.deliveries.isNotEmpty &&+ own.deliveries.any(+ (d) => !const {+ 'answered',+ 'cancelled',+ 'superseded',+ }.contains(d['status']),+ ) &&+ !incoming.any((m) => m.id == own.id)) {+ // New replies (or a long stream of agent updates) otherwise leave the+ // original row outside this page and its inline receipt stuck at Sent.+ final receipt = await request(+ 'GET',+ '$_path/conversations/${Uri.encodeComponent(id)}/messages?messageId=${Uri.encodeComponent(own.id)}',+ );+ if (_disposed || accessRevoked || snapshot?.conversation(id) == null) {+ return;+ }+ final rows = (receipt['messages'] as List)+ .map((m) => SuperTabMessage.fromJson(superTabMap(m)))+ .toList();+ if (rows.length > 1 ||+ rows.any((m) => m.id != own.id || m.conversationId != id)) {+ throw const FormatException(+ 'A different message receipt was returned.',+ );+ }+ for (final row in rows) {+ combined[row.id] = row;+ }+ }_messages[id] = combined.values.toList()..sort((a, b) => a.sequence.compareTo(b.sequence));if (older || !_before.containsKey(id)) {diff --git a/desktop/lib/super_tabs/message_receipt.dart b/desktop/lib/super_tabs/message_receipt.dartnew file mode 100644index 000000000..a93bbda0c--- /dev/null+++ b/desktop/lib/super_tabs/message_receipt.dart@@ -0,0 +1,341 @@+import 'dart:async';++import 'package:flutter/material.dart';++import '../core/models.dart';+import '../shared/theme/app_icons.dart';+import '../shared/theme/app_theme.dart' as grid;+import '../state/app_state.dart';+import '../state/harness_activity.dart';+import '../widgets/desktop_chrome.dart';+import 'controller.dart';+import 'machine_status.dart';+import 'model.dart';++/// The approved receipt line, scoped by the chat to its newest own message.+/// No new transport is inferred: missing native activity simply reads Delivered.+class SuperTabMessageReceipt extends StatefulWidget {+ const SuperTabMessageReceipt({+ super.key,+ required this.message,+ required this.controller,+ required this.onResolve,+ required this.onAddLead,+ required this.machineName,+ this.app,+ this.now = DateTime.now,+ });+ final SuperTabMessage message;+ final SuperTabController controller;+ final AppNotifier? app;+ final void Function(SuperTabDelivery delivery, String resolution) onResolve;+ final VoidCallback onAddLead;+ final String Function(String machineId) machineName;+ final DateTime Function() now;++ @override+ State<SuperTabMessageReceipt> createState() => _SuperTabMessageReceiptState();+}++class _SuperTabMessageReceiptState extends State<SuperTabMessageReceipt>+ with WidgetsBindingObserver {+ Timer? _timer;+ bool _enabled = true;++ @override+ void initState() {+ super.initState();+ WidgetsBinding.instance.addObserver(this);+ widget.app?.addListener(_changed);+ }++ @override+ void didUpdateWidget(SuperTabMessageReceipt oldWidget) {+ super.didUpdateWidget(oldWidget);+ if (oldWidget.app != widget.app) {+ oldWidget.app?.removeListener(_changed);+ widget.app?.addListener(_changed);+ }+ }++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ _enabled =+ TickerMode.valuesOf(context).enabled &&+ ModalRoute.isCurrentOf(context) != false;+ if (!_enabled) _timer?.cancel();+ }++ @override+ void didChangeAppLifecycleState(AppLifecycleState state) => _changed();++ void _changed() {+ if (mounted) setState(() {});+ }++ void _clock(bool needed) {+ _timer?.cancel();+ final lifecycle = WidgetsBinding.instance.lifecycleState;+ if (!needed ||+ !_enabled ||+ (lifecycle != null && lifecycle != AppLifecycleState.resumed)) {+ return;+ }+ _timer = Timer(const Duration(milliseconds: 500), _changed);+ }++ @override+ void dispose() {+ _timer?.cancel();+ widget.app?.removeListener(_changed);+ WidgetsBinding.instance.removeObserver(this);+ super.dispose();+ }++ String _clockText(Duration value) {+ final seconds = value.inSeconds.clamp(0, 1 << 31);+ return '${seconds ~/ 60}:${(seconds % 60).toString().padLeft(2, '0')}';+ }++ String _replyDuration(Duration value) {+ final seconds = value.inSeconds.clamp(0, 1 << 31);+ return seconds < 60 ? '${seconds}s' : '${seconds ~/ 60}m ${seconds % 60}s';+ }++ @override+ Widget build(BuildContext context) {+ final message = widget.message, c = widget.controller;+ final delivery = message.receiptDelivery;+ final agent = c.snapshot?.agent(delivery?.agentId ?? '');+ final name =+ c.snapshot?.agentName(delivery?.agentId ?? '', fallback: 'Lead') ??+ 'Lead';+ final now = widget.now();+ final machine = c.snapshot?.machines+ .where((m) => m['machineId'] == agent?.machineId)+ .firstOrNull;+ final observation = machine?['observation'];+ final receivedAt = observation is Map ? observation['receivedAt'] : null;+ final readingAt = receivedAt is num+ ? DateTime.fromMillisecondsSinceEpoch(receivedAt.toInt())+ : null;+ final native = agent == null ? null : widget.app?.stateOf(agent.machineId);+ final direct = native?.isLocalMachine == true;+ final offline =+ !c.backendUnreachable &&+ (machine != null || direct) &&+ superTabMachineStatus(+ age: readingAt == null ? null : now.difference(readingAt),+ connected: direct+ ? native!.connectionStatus == ConnectionStatus.connected &&+ !native.isOffline+ : null,+ ) ==+ SuperTabMachineStatus.offline;+ final working =+ delivery?.delivered == true &&+ agent != null &&+ widget.app != null &&+ harnessActivity(widget.app!, agent.machineId, agent.harnessId) ==+ HarnessActivity.working;+ final fresh =+ delivery?.pending == true &&+ message.createdAt != null &&+ now.difference(message.createdAt!) < const Duration(seconds: 3);+ final held = delivery?.pending == true && delivery?.holdReason != null;+ var color = DesktopChrome.muted;+ var icon = AppIcons.check;+ String title = 'Sent';+ String? detail, note, elapsed;+ bool sending = false;+ final actions = <(String, VoidCallback?)>[];+ final canResolve = c.canWrite && !c.saving && delivery?.id != null;++ if (delivery?.status == 'uncertain') {+ title = "Couldn't confirm delivery";+ icon = AppIcons.triangleAlert;+ color = Theme.of(context).colorScheme.error;+ note =+ "$name's computer may have typed this into the terminal without confirming. Check the terminal before sending again, or it could run twice.";+ for (final (label, resolution) in [+ ('Open terminal', 'open'),+ ('Send again', 'resend'),+ ('It arrived', 'received'),+ ]) {+ actions.add((+ label,+ canResolve && (resolution != 'open' || agent != null)+ ? () => widget.onResolve(delivery!, resolution)+ : null,+ ));+ }+ } else if (delivery?.status == 'answered') {+ title = 'Replied';+ icon = AppIcons.checkCheck;+ final answer = delivery?.answeredAt ?? delivery?.updatedAt;+ final start = delivery?.deliveredAt ?? message.createdAt;+ if (answer != null && start != null) {+ title += ' · ${_replyDuration(answer.difference(start))}';+ }+ } else if (delivery?.delivered == true) {+ icon = AppIcons.checkCheck;+ final at = (delivery!.deliveredAt ?? delivery.updatedAt)?.toLocal();+ title = at == null+ ? 'Delivered'+ : 'Delivered ${at.hour.toString().padLeft(2, '0')}:${at.minute.toString().padLeft(2, '0')}';+ if (working) {+ color = DesktopChrome.accent;+ detail = '$name is working';+ if (delivery.deliveredAt != null) {+ elapsed = _clockText(now.difference(delivery.deliveredAt!));+ }+ }+ } else if (delivery == null && c.selected?.leadId == null) {+ title = 'Not sent · this chat has no Lead';+ icon = AppIcons.triangleAlert;+ color = Theme.of(context).colorScheme.error;+ actions.add(('Add a Lead', c.canWrite ? widget.onAddLead : null));+ } else if (delivery?.status == 'cancelled') {+ title = 'Not sent';+ icon = AppIcons.triangleAlert;+ color = Theme.of(context).colorScheme.error;+ } else if (delivery?.pending == true && offline) {+ color = grid.AppPalette.warn;+ detail = "$name's computer is offline";+ final host =+ machine?['name'] as String? ?? widget.machineName(agent!.machineId);+ note = readingAt == null+ ? "$host is offline. Your message goes in when it's back online."+ : "$host was last seen ${superTabAgo(now.difference(readingAt))}. Your message goes in when it's back online.";+ } else if (held) {+ color = grid.AppPalette.warn;+ detail = switch (delivery!.holdReason) {+ 'team_waiting_idle' => '$name is busy',+ 'team_waiting_user' => "someone is typing in $name's terminal",+ 'team_waiting_draft' => "$name's terminal has unsent text",+ _ => "$name can't take messages right now",+ };+ if (delivery.holdSince != null) {+ detail +=+ ' · waiting ${_clockText(now.difference(delivery.holdSince!))}';+ }+ note = switch (delivery.holdReason) {+ 'team_waiting_idle' =>+ "$name is finishing another task. Your message goes in by itself when it's done.",+ 'team_waiting_user' =>+ "Someone is typing in $name's terminal. Your message goes in by itself when that clears.",+ 'team_waiting_draft' =>+ "$name's terminal has unsent text. Your message goes in by itself when that clears.",+ _ =>+ "$name can't take messages right now. Your message goes in by itself when that clears.",+ };+ } else if (fresh) {+ title = 'Sending…';+ sending = true;+ }+ _clock(fresh || working || held || (delivery?.pending == true && offline));+ final style = DesktopChrome.metadata(color: color).copyWith(+ fontSize: 12,+ fontFeatures: const [FontFeature.tabularFigures()],+ );+ final motion = !MediaQuery.disableAnimationsOf(context);+ final parts = <Widget>[+ if (sending && motion)+ SizedBox(+ width: 12,+ height: 12,+ child: CircularProgressIndicator(strokeWidth: 1.5, color: color),+ )+ else+ Icon(sending ? AppIcons.loaderCircle : icon, size: 14, color: color),+ Text(title, style: style),+ if (detail != null) ...[+ Text('·', style: style),+ Text(detail, style: style),+ ],+ if (working) ...[+ ExcludeSemantics(+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ for (var i = 0; i < 3; i++)+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 1.5),+ child: Opacity(+ opacity:+ !motion || (now.millisecondsSinceEpoch ~/ 500) % 3 == i+ ? 1+ : .25,+ child: Container(+ width: 4,+ height: 4,+ decoration: BoxDecoration(+ color: color,+ shape: BoxShape.circle,+ ),+ ),+ ),+ ),+ ],+ ),+ ),+ if (elapsed != null) Text(elapsed, style: style),+ ],+ 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),+ ),+ ],+ ];+ return Padding(+ padding: const EdgeInsets.only(top: 6),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Semantics(+ liveRegion: true,+ child: Wrap(+ spacing: 6,+ runSpacing: 2,+ crossAxisAlignment: WrapCrossAlignment.center,+ 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,+ ),+ ),+ ),+ ),+ ),+ ],+ ),+ );+ }+}diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dartindex 887513995..f5a084cd3 100644--- a/desktop/lib/super_tabs/model.dart+++ b/desktop/lib/super_tabs/model.dart@@ -288,6 +288,36 @@ SuperTabAttachment? _tryAttachment(Object? row) {}}+/// Optional timing/hold fields keep messages from older backends readable.+class SuperTabDelivery {+ SuperTabDelivery.fromJson(Map<String, dynamic> row)+ : id = row['id'] as String?,+ agentId = row['agentId'] as String? ?? '',+ status = row['status'] as String? ?? '',+ holdReason = row['holdReason'] as String?,+ holdSince = _date(row['holdSince']),+ deliveredAt = _date(row['deliveredAt']),+ answeredAt = _date(row['answeredAt']),+ updatedAt = _date(row['updatedAt']);+ final String? id, holdReason;+ final String agentId, status;+ final DateTime? holdSince, deliveredAt, answeredAt, updatedAt;+ static DateTime? _date(Object? value) =>+ value is String ? DateTime.tryParse(value) : null;+ bool get pending => status == 'queued' || status == 'claimed';+ bool get delivered => status == 'delivered' || status == 'confirmed';++ // One line cannot promise arrival while another recipient still waits.+ int get receiptOrder => switch (status) {+ 'uncertain' => 0,+ 'queued' || 'claimed' => 1,+ 'cancelled' => 2,+ 'delivered' || 'confirmed' => 3,+ 'answered' => 4,+ _ => 5,+ };+}+class SuperTabMessage {SuperTabMessage.fromJson(Map<String, dynamic> row): id = _text(row, 'id'),@@ -333,7 +363,11 @@ class SuperTabMessage {: 'Terminal answer';}- bool get uncertain => deliveries.any((d) => d['status'] == 'uncertain');+ SuperTabDelivery? get receiptDelivery {+ final rows = deliveries.map(SuperTabDelivery.fromJson).toList();+ rows.sort((a, b) => a.receiptOrder.compareTo(b.receiptOrder));+ return rows.firstOrNull;+ }}/// The `remote` a daemon reports for a project: `host/owner/repo`, alreadydiff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 4f7e5856c..2e1819f6b 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -19,6 +19,7 @@ import 'controller.dart';import 'dialog_scope.dart';import 'model.dart';import 'message_row.dart';+import 'message_receipt.dart';import 'route_row.dart';import 'work_details.dart';import 'project_sidebar.dart';@@ -893,89 +894,15 @@ class _SuperTabViewState extends State<SuperTabView>);}- Future<void> _reviewDelivery(+ Future<void> _resolveDelivery(SuperTabMessage message,- Map<String, dynamic> delivery,+ SuperTabDelivery delivery,+ String resolution,) async {final c = this.c;- final agent = c.snapshot?.agent(delivery['agentId'] as String);- final resolution = await showAppDialog<String>(- context: context,- builder: (context) => ListenableBuilder(- listenable: c,- builder: (context, _) => !c.canWrite- ? AlertDialog(- content: const Text(- 'This delivery is no longer available to change.',- ),- actions: [- TextButton(- onPressed: () => Navigator.pop(context),- child: const Text('Close'),- ),- ],- )- : AlertDialog(- title: DesktopDialogHeader(- title:- 'Check delivery to ${agent == null ? 'agent' : _agentName(agent)}',- padding: EdgeInsets.zero,- onClose: () => Navigator.pop(context),- ),- content: SizedBox(- width: 440,- child: SingleChildScrollView(- child: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.start,- children: [- if (agent != null) ...[- TextButton(- onPressed: () => Navigator.pop(context, 'open'),- child: const Text('Open terminal'),- ),- const SizedBox(height: 16),- ],- const Text(- 'This instruction may already have reached the terminal. Inspect it before sending again.',- ),- const SizedBox(height: 16),- SelectableText(message.text),- ],- ),- ),- ),- actions: [- Wrap(- spacing: DesktopChrome.controlGap,- runSpacing: DesktopChrome.controlGap,- alignment: WrapAlignment.end,- children: [- TextButton(- onPressed: () => Navigator.pop(context, 'cancel'),- child: const Text('Dismiss warning'),- ),- TextButton(- onPressed: () => Navigator.pop(context, 'received'),- child: const Text('Already received'),- ),- FilledButton(- onPressed: () => Navigator.pop(context, 'resend'),- child: const Text('Send again'),- ),- ],- ),- ],- ),- ),- );- if (!mounted ||- widget.controller != c ||- resolution == null ||- !c.canWrite) {- return;- }+ if (!c.canWrite || c.saving || delivery.id == null) return;if (resolution == 'open') {+ final agent = c.snapshot?.agent(delivery.agentId);if (agent != null) {c.select(message.conversationId);widget.onOpenTerminal(agent);@@ -984,7 +911,7 @@ class _SuperTabViewState extends State<SuperTabView>}await c.command({'type': 'delivery.resolve',- 'deliveryId': delivery['id'],+ 'deliveryId': delivery.id,'resolution': resolution,});}@@ -992,8 +919,9 @@ class _SuperTabViewState extends State<SuperTabView>Widget _message(SuperTabMessage message,bool grouped,- Map<String, SuperTabMessage> byId,- ) {+ Map<String, SuperTabMessage> byId, {+ bool showReceipt = false,+ }) {final route = message.route;if (route != null) {return SuperTabRouteRow(@@ -1045,16 +973,18 @@ class _SuperTabViewState extends State<SuperTabView>style: DesktopChrome.metadata(),),),- for (final delivery in message.deliveries.where(- (d) => d['status'] == 'uncertain',- ))- TextButton(- onPressed: c.canWrite && delivery['id'] is String- ? () => _reviewDelivery(message, delivery)- : null,- child: Text(- 'Check delivery to ${c.snapshot?.agentName(delivery['agentId'] as String, fallback: 'agent') ?? 'agent'}',- ),+ if (showReceipt)+ SuperTabMessageReceipt(+ key: ValueKey('super-message-receipt-${message.id}'),+ message: message,+ controller: c,+ app: widget.app,+ machineName: widget.machineName,+ onResolve: (delivery, resolution) =>+ unawaited(_resolveDelivery(message, delivery, resolution)),+ onAddLead: () {+ if (c.selected case final group?) widget.onAddAgent(group);+ },),],);@@ -1106,7 +1036,22 @@ class _SuperTabViewState extends State<SuperTabView>final group = c.selected;final writable = c.canWrite && group != null && !group.archived;final busy = c.saving || c.uploading;- final messages = c.messages(c.selectedId);+ final allMessages = c.messages(c.selectedId);+ final latestOwn = allMessages.reversed+ .where(+ (m) => !m.fromAgent && !m.fromTerminal && m.authorId == c.accountId,+ )+ .firstOrNull;+ // Older Desktops still show this plain notice. The inline receipt owns the+ // same explanation here, including after delivery settles, so it never resurfaces stale.+ final messages = allMessages+ .where(+ (m) =>+ !(m.source['kind'] == 'delivery-hold' &&+ m.source['messageId'] == latestOwn?.id &&+ m.source['deliveryId'] == latestOwn?.receiptDelivery?.id),+ )+ .toList();final entries = superTabTranscriptEntries(messages);final byId = {for (final message in messages) message.id: message};final grouped = SuperTabMessageRow.consecutiveUpdates(messages);@@ -1225,6 +1170,7 @@ class _SuperTabViewState extends State<SuperTabView>message,grouped.contains(message.id),byId,+ showReceipt: message.id == latestOwn?.id,),],);diff --git a/desktop/test/super_tab_controller_test.dart b/desktop/test/super_tab_controller_test.dartindex cab2314f7..e7ac030db 100644--- a/desktop/test/super_tab_controller_test.dart+++ b/desktop/test/super_tab_controller_test.dart@@ -6,6 +6,31 @@ import 'package:harness/super_tabs/controller.dart';import 'support/super_tab_fixture.dart';void main() {+ test(+ 'receipt refreshes the latest own message when a new reply arrives',+ () async {+ final server = ConversationServer()..append('Please start.');+ server.messages.first['deliveries'] = [+ {'id': 'delivery', 'agentId': 'lead-agent', 'status': 'claimed'},+ ];+ final c = server.controller();+ await c.refresh();+ server.messages.first['deliveries'] = [+ {'id': 'delivery', 'agentId': 'lead-agent', 'status': 'answered'},+ ];+ server.append('Done.');+ server.messages.last['author'] = {+ 'kind': 'agent',+ 'id': 'lead-agent',+ 'name': 'Lead',+ };+ server.messages.last['replyTo'] = server.messages.first['id'];+ await c.refresh();+ expect(c.messages('lead').first.deliveries.single['status'], 'answered');+ c.dispose();+ },+ );+test('group terminals keep every member when selecting one and after reopening',() async {diff --git a/desktop/test/super_tab_delivery_test.dart b/desktop/test/super_tab_delivery_test.dartindex ffe04b516..2c74f44a7 100644--- a/desktop/test/super_tab_delivery_test.dart+++ b/desktop/test/super_tab_delivery_test.dart@@ -42,7 +42,9 @@ void main() {expect(find.text('queued message'), findsOneWidget);expect(find.text('claimed message'), findsOneWidget);expect(find.text('Queued'), findsNothing);- expect(find.textContaining('Check delivery'), findsOneWidget);+ // The uncertain review is now the latest message's receipt and its actions (message_receipt.dart).+ expect(find.text("Couldn't confirm delivery"), findsOneWidget);+ expect(find.text('Send again'), findsOneWidget);},);@@ -207,17 +209,13 @@ void main() {await tester.sendKeyEvent(LogicalKeyboardKey.escape);await tester.pumpAndSettle();}- await tester.tap(find.text('Check delivery to Lead'));- await tester.pumpAndSettle();await shot('delivery');expect(server.posts, isEmpty);await tester.tap(find.text('Open terminal'));await tester.pumpAndSettle();expect(opened, 'lead-agent');expect(server.posts, isEmpty);- await tester.tap(find.text('Check delivery to Lead'));- await tester.pumpAndSettle();- await tester.tap(find.text('Already received'));+ await tester.tap(find.text('It arrived'));await tester.pumpAndSettle();expect((server.posts.single['command'] as Map), {'type': 'delivery.resolve',@@ -230,8 +228,6 @@ void main() {reason:'Confirmation does not submit the original instruction again.',);- await tester.tap(find.text('Check delivery to Lead'));- await tester.pumpAndSettle();controller.revokeAccess('Access removed.');await tester.pumpAndSettle();expect(find.byType(SelectableText), findsNothing);diff --git a/desktop/test/super_tab_receipt_test.dart b/desktop/test/super_tab_receipt_test.dartnew file mode 100644index 000000000..23a465aef--- /dev/null+++ b/desktop/test/super_tab_receipt_test.dart@@ -0,0 +1,374 @@+import 'dart:io';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/state/app_state.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/view.dart';++import 'support/super_tab_fixture.dart';+import 'support/capture.dart';+import 'swarm_state_test.dart' show createApp;++class ReceiptFixture {+ ReceiptFixture(this.tester, {this.status = 'claimed'});+ final WidgetTester tester;+ final String? status;+ final server = ConversationServer();+ final now = DateTime.now();+ late final SuperTabController controller;+ String? opened;+ bool addedLead = false;+ Map<String, dynamic> get message => server.messages.last;+ Map<String, dynamic> get delivery =>+ (message['deliveries'] as List).single as Map<String, dynamic>;++ Future<void> show({AppNotifier? app, void Function()? prepare}) async {+ server.state['agents'] = [+ {+ 'id': 'lead-agent',+ 'name': 'Lead',+ 'machineId': 'm',+ 'harnessId': 'a0',+ 'contributorId': 'owner',+ 'configuration': {'engine': 'codex'},+ },+ ];+ final group = (server.state['conversations'] as List).first as Map;+ group['leadId'] = 'lead-agent';+ group['agentIds'] = ['lead-agent'];+ server.state['machines'] = [+ {+ 'machineId': 'm',+ 'name': 'Team Mac',+ 'observation': {'receivedAt': now.millisecondsSinceEpoch},+ },+ ];+ server.append('Please start.');+ message['createdAt'] = now+ .subtract(const Duration(minutes: 2))+ .toIso8601String();+ if (status != null) {+ message['deliveries'] = [+ {+ 'id': 'delivery',+ 'agentId': 'lead-agent',+ 'status': status,+ 'deliveredAt': now+ .subtract(const Duration(seconds: 42))+ .toIso8601String(),+ },+ ];+ }+ prepare?.call();+ controller = server.controller();+ await controller.refresh();+ await tester.binding.setSurfaceSize(const Size(1000, 720));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.light),+ home: Scaffold(+ body: SuperTabView(+ controller: controller,+ app: app,+ onInvite: () {},+ onAddAgent: (_) => addedLead = true,+ onOpenTerminal: (agent) => opened = agent.id,+ machineName: (_) => 'Team Mac',+ ),+ ),+ ),+ );+ await tester.pump(const Duration(milliseconds: 100));+ }++ Future<void> close() async {+ expect(find.text('Queued'), findsNothing);+ expect(find.textContaining('Check delivery'), findsNothing);+ expect(tester.takeException(), isNull);+ final own = controller+ .messages('lead')+ .where((m) => !m.fromAgent && m.authorId == 'owner')+ .lastOrNull;+ final receipt = own?.receiptDelivery;+ await captureWindow(+ tester,+ Platform.environment['HARNESS_SUPER_TAB_CAPTURE'],+ 'receipt-${receipt?.status ?? 'no-lead'}-${receipt?.holdReason ?? 'plain'}',+ );+ await tester.pumpWidget(const SizedBox());+ await controller.flush();+ controller.dispose();+ }+}++void main() {+ setUpAll(+ () => loadCaptureFonts(Platform.environment['HARNESS_SUPER_TAB_CAPTURE']),+ );+ for (final status in ['queued', 'claimed']) {+ testWidgets(+ 'receipt: fresh $status reads Sending then an older message reads Sent',+ (tester) async {+ final f = ReceiptFixture(tester, status: status);+ await f.show(+ prepare: () =>+ f.message['createdAt'] = DateTime.now().toIso8601String(),+ );+ expect(find.text('Sending…'), findsOneWidget);+ f.message['createdAt'] = f.now+ .subtract(const Duration(seconds: 8))+ .toIso8601String();+ await f.controller.refresh();+ await tester.pump();+ expect(find.text('Sent'), findsOneWidget);+ expect(find.text('Sending…'), findsNothing);+ await f.close();+ },+ );+ }++ for (final status in ['delivered', 'confirmed']) {+ testWidgets(+ 'receipt: $status uses the recorded delivery time without inventing remote activity',+ (tester) async {+ final f = ReceiptFixture(tester, status: status);+ await f.show();+ final at = DateTime.parse(f.delivery['deliveredAt'] as String)+ .toLocal();+ expect(+ find.text(+ 'Delivered ${at.hour.toString().padLeft(2, '0')}:${at.minute.toString().padLeft(2, '0')}',+ ),+ findsOneWidget,+ );+ expect(find.textContaining('is working'), findsNothing);+ await f.close();+ },+ );+ }++ testWidgets(+ 'receipt: known working activity appears and clears without a new message',+ (tester) async {+ final app = createApp(connected: true);+ addTearDown(app.dispose);+ final f = ReceiptFixture(tester, status: 'delivered');+ await f.show(app: app);+ await app.handleEventForTest('m', {+ 'type': 'turn_started',+ 'agentId': 'a0',+ });+ await tester.pump();+ expect(find.text('Lead is working'), findsOneWidget);+ expect(find.textContaining(RegExp(r'^0:4[2-5]$')), findsOneWidget);+ await app.handleEventForTest('m', {+ 'type': 'turn_ended',+ 'agentId': 'a0',+ });+ await tester.pump(const Duration(milliseconds: 100));+ expect(find.text('Lead is working'), findsNothing);+ expect(find.textContaining('Delivered '), findsOneWidget);+ await f.close();+ },+ );++ for (final (reason, label) in [+ ('team_waiting_idle', 'Lead is busy'),+ ('team_waiting_user', "someone is typing in Lead's terminal"),+ ('team_waiting_draft', "Lead's terminal has unsent text"),+ ('team_waiting_control', "Lead can't take messages right now"),+ ('team_waiting_unavailable', "Lead can't take messages right now"),+ ]) {+ testWidgets('receipt: $reason explains the held message inline', (+ tester,+ ) async {+ final f = ReceiptFixture(tester);+ await f.show(+ prepare: () {+ f.delivery['holdReason'] = reason;+ f.delivery['holdSince'] = f.now+ .subtract(const Duration(seconds: 34))+ .toIso8601String();+ },+ );+ expect(find.text('Sent'), findsOneWidget);+ expect(find.textContaining('$label · waiting 0:3'), findsOneWidget);+ if (reason == 'team_waiting_idle') {+ expect(+ find.text(+ "Lead is finishing another task. Your message goes in by itself when it's done.",+ ),+ findsOneWidget,+ );+ }+ await f.close();+ });+ }++ testWidgets(+ 'receipt: offline recipient uses its machine reading and last-seen name',+ (tester) async {+ final f = ReceiptFixture(tester);+ await f.show(+ prepare: () {+ (f.server.state['machines'] as List)+ .first['observation']['receivedAt'] = f.now+ .subtract(const Duration(minutes: 3))+ .millisecondsSinceEpoch;+ },+ );+ expect(find.text("Lead's computer is offline"), findsOneWidget);+ expect(+ find.text(+ "Team Mac was last seen 3 min ago. Your message goes in when it's back online.",+ ),+ findsOneWidget,+ );+ await f.close();+ },+ );++ for (final (label, resolution) in [+ ('Open terminal', null),+ ('Send again', 'resend'),+ ('It arrived', 'received'),+ ]) {+ testWidgets(+ 'receipt: uncertainty keeps the warning and $label uses the existing action',+ (tester) async {+ final f = ReceiptFixture(tester, status: 'uncertain');+ await f.show();+ expect(find.text("Couldn't confirm delivery"), findsOneWidget);+ expect(+ find.text(+ "Lead's computer may have typed this into the terminal without confirming. Check the terminal before sending again, or it could run twice.",+ ),+ findsOneWidget,+ );+ for (final action in ['Open terminal', 'Send again', 'It arrived']) {+ expect(find.text(action), findsOneWidget);+ }+ await tester.tap(find.text(label));+ await tester.pump();+ if (resolution == null) {+ expect(f.opened, 'lead-agent');+ expect(f.server.posts, isEmpty);+ } else {+ expect(f.server.posts.single['command'], {+ 'type': 'delivery.resolve',+ 'deliveryId': 'delivery',+ 'resolution': resolution,+ });+ }+ await f.close();+ },+ );+ }++ testWidgets('receipt: no Lead is not sent and offers Add a Lead', (+ tester,+ ) async {+ final f = ReceiptFixture(tester, status: null);+ await f.show(+ prepare: () =>+ (f.server.state['conversations'] as List).first['leadId'] = null,+ );+ expect(find.text('Not sent · this chat has no Lead'), findsOneWidget);+ await tester.tap(find.text('Add a Lead'));+ expect(f.addedLead, isTrue);+ await f.close();+ });++ testWidgets('receipt: answered shows its fixed delivery-to-answer duration', (+ tester,+ ) async {+ final f = ReceiptFixture(tester, status: 'answered');+ await f.show(+ prepare: () {+ f.delivery['answeredAt'] = f.now.toIso8601String();+ f.delivery['deliveredAt'] = f.now+ .subtract(const Duration(seconds: 72))+ .toIso8601String();+ },+ );+ expect(find.text('Replied · 1m 12s'), findsOneWidget);+ await f.close();+ });++ testWidgets(+ 'receipt: only latest own message carries a receipt, even after another person speaks',+ (tester) async {+ final f = ReceiptFixture(tester);+ await f.show(+ prepare: () {+ f.server.append('Someone else speaks.');+ f.message['author'] = {+ 'kind': 'person',+ 'id': 'peer',+ 'name': 'Peer',+ };+ f.message['deliveries'] = [+ {+ 'id': 'peer-delivery',+ 'agentId': 'lead-agent',+ 'status': 'uncertain',+ },+ ];+ },+ );+ expect(find.text('Sent'), findsOneWidget);+ expect(find.text("Couldn't confirm delivery"), findsNothing);+ f.server.append('My next question.');+ f.message['deliveries'] = [+ {'id': 'new-delivery', 'agentId': 'lead-agent', 'status': 'delivered'},+ ];+ await f.controller.refresh();+ await tester.pump(const Duration(milliseconds: 100));+ expect(find.text('Sent'), findsNothing);+ expect(find.text('Delivered'), findsOneWidget);+ await f.close();+ },+ );++ testWidgets(+ 'receipt: matching compatibility notice is hidden while other agent messages stay',+ (tester) async {+ final f = ReceiptFixture(tester);+ await f.show(+ prepare: () {+ f.delivery['holdReason'] = 'team_waiting_idle';+ f.delivery['holdSince'] = f.now.toIso8601String();+ final original = f.message['id'];+ f.server.append('A message for Lead is waiting. It stays queued.');+ f.message['author'] = {+ 'kind': 'agent',+ 'id': 'lead-agent',+ 'name': 'Lead',+ };+ f.message['source'] = {+ 'kind': 'delivery-hold',+ 'messageId': original,+ 'deliveryId': 'delivery',+ 'agentId': 'lead-agent',+ };+ f.server.append('A real update.');+ f.message['author'] = {+ 'kind': 'agent',+ 'id': 'lead-agent',+ 'name': 'Lead',+ };+ },+ );+ expect(+ find.textContaining('A message for Lead is waiting.'),+ findsNothing,+ );+ expect(find.text('A real update.'), findsOneWidget);+ expect(find.textContaining('Lead is busy'), findsOneWidget);+ await f.close();+ },+ );+}diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dartindex d642d80a4..dd5d19c84 100644--- a/desktop/test/support/super_tab_fixture.dart+++ b/desktop/test/support/super_tab_fixture.dart@@ -266,10 +266,12 @@ class ConversationServer {final conversationId = uri.pathSegments[4];final after = int.tryParse(uri.queryParameters['after'] ?? '');final before = int.tryParse(uri.queryParameters['before'] ?? '');+ final messageId = uri.queryParameters['messageId'];var rows = messages.where((m) =>m['conversationId'] == conversationId &&+ (messageId == null || m['id'] == messageId) &&(after == null || (m['sequence'] as int) > after) &&(before == null || (m['sequence'] as int) < before),)