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.

Merge batch 11-03 bl: #2697 #2684 #2679 #2686 #2687 #2688 #2692 #2691 (#2703)

0xken15b8a64b53e5c3
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index 9e967837a..e6dd0e546 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -4749,6 +4749,9 @@ class SuperTabController extends ChangeNotifier {
unawaited(_drainSends());
return result.future;
}
+ // Read before the upload's wait: another chat may be open by its end, and
+ // this session belongs to the chat it was sent from.
+ final inSwarmBuddyChat = selected?.isSwarmBuddyChat == true;
final ids = await _uploadAll(
conversationId,
attachments(conversationId),
@@ -4775,9 +4778,7 @@ class SuperTabController extends ChangeNotifier {
if (oneBuddy) 'oneBuddy': true,
// A New session in one project of the reader's one Buddy chat (spec
// 2026-10-31-one-buddy-per-swarm).
- if (newSession &&
- sessionProjectId != null &&
- selected?.isSwarmBuddyChat == true)
+ if (newSession && sessionProjectId != null && inSwarmBuddyChat)
'sessionProjectId': sessionProjectId,
});
// On its way: the message shows in the chat, and the draft is free for
diff --git a/desktop/lib/super_tabs/project_status.dart b/desktop/lib/super_tabs/project_status.dart
index 267dff443..59f6a09ca 100644
--- a/desktop/lib/super_tabs/project_status.dart
+++ b/desktop/lib/super_tabs/project_status.dart
@@ -38,6 +38,14 @@ Future<void> showSuperTabProjectStatus(
SuperTabController c,
String projectId, {
DateTime Function() now = DateTime.now,
+}) => showSuperTabProjectStatusWith(context, c, projectId, now: now);
+
+/// The Status above, with the clock given, so a test fixes the day.
+Future<void> showSuperTabProjectStatusWith(
+ BuildContext context,
+ SuperTabController c,
+ String projectId, {
+ required DateTime Function() now,
}) => showAppDialog<void>(
context: context,
builder: (context) => SuperTabDialogScope(
diff --git a/desktop/test/super_tab_one_buddy_test.dart b/desktop/test/super_tab_one_buddy_test.dart
index 344d6c5c9..ec7f7342f 100644
--- a/desktop/test/super_tab_one_buddy_test.dart
+++ b/desktop/test/super_tab_one_buddy_test.dart
@@ -1,6 +1,11 @@
+import 'dart:async';
+import 'dart:typed_data';
+
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/harness_attachments.dart';
+import 'package:harness/super_tabs/attachment_upload.dart';
import 'package:harness/super_tabs/controller.dart';
import 'package:harness/super_tabs/section_heading.dart';
import 'package:harness/super_tabs/view.dart';
@@ -24,10 +29,11 @@ void main() {
WidgetTester tester,
ConversationServer server, {
Brightness brightness = Brightness.light,
+ SuperTabUpload? upload,
}) async {
await tester.binding.setSurfaceSize(const Size(1280, 800));
addTearDown(() => tester.binding.setSurfaceSize(null));
- final c = server.controller(account: 'peer');
+ final c = server.controller(account: 'peer', upload: upload);
await c.refresh();
await tester.pumpWidget(
MaterialApp(
@@ -425,5 +431,77 @@ void main() {
await close(tester, c);
},
);
+
+ // The check of the chat came after the upload's wait and read the selected
+ // chat, so opening another during it sent the session with no project: it
+ // started as All projects and could not hand work to the project's PM.
+ testWidgets('keeps its project when another chat opens during the upload', (
+ tester,
+ ) async {
+ final server = oneBuddySwarm();
+ giveSwarmBuddy(server);
+ final hold = Completer<void>();
+ final c = await show(
+ tester,
+ server,
+ upload:
+ ({
+ required tabId,
+ required conversationId,
+ required name,
+ required mime,
+ required file,
+ required cancel,
+ required onProgress,
+ }) async {
+ await hold.future;
+ return server.upload(
+ tabId: tabId,
+ conversationId: conversationId,
+ name: name,
+ mime: mime,
+ file: file,
+ cancel: cancel,
+ onProgress: onProgress,
+ );
+ },
+ );
+ await tester.tap(buddyRow);
+ await tester.pumpAndSettle();
+ final buddyChat = c.selectedId;
+ await tester.tap(find.byKey(const ValueKey('super-chat-new-session')));
+ await tester.pumpAndSettle();
+ await tester.tap(
+ find.byKey(const ValueKey('super-chat-session-project')),
+ );
+ await tester.pumpAndSettle();
+ await tester.tap(
+ find.byKey(const ValueKey('super-chat-session-in-lead')).last,
+ );
+ await tester.pumpAndSettle();
+ c.attachments(buddyChat).add([
+ HarnessAttachment('notes.txt', Uint8List.fromList([104, 105])),
+ ]);
+ await tester.enterText(
+ find.byKey(const ValueKey('super-message-composer')),
+ 'Hand this off',
+ );
+ await tester.pump();
+ await tester.tap(find.byTooltip('Send message'));
+ await tester.pump();
+ expect(c.uploading, isTrue);
+
+ await c.select('lead');
+ await tester.pump();
+ expect(c.selectedId, 'lead');
+ hold.complete();
+ await tester.pumpAndSettle();
+
+ final sent = commands(server, 'message.send').last;
+ expect(sent['conversationId'], buddyChat);
+ expect(sent['newSession'], isTrue);
+ expect(sent['sessionProjectId'], 'lead');
+ await close(tester, c);
+ });
});
}
diff --git a/desktop/test/super_tab_project_menu_test.dart b/desktop/test/super_tab_project_menu_test.dart
index 76afbb725..20c85a39e 100644
--- a/desktop/test/super_tab_project_menu_test.dart
+++ b/desktop/test/super_tab_project_menu_test.dart
@@ -1,12 +1,20 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shared/theme/app_icons.dart';
+import 'package:harness/super_tabs/project_status.dart';
import 'super_tab_mentions_test.dart' show showView;
import 'support/super_tab_fixture.dart';
-// 20:33 on this computer, whatever its zone.
-final reported = DateTime(2026, 11, 2, 20, 33);
+// 20:33 today on this computer, so the label shows the time and no date
+// whatever the day this runs.
+final reported = DateTime(
+ DateTime.now().year,
+ DateTime.now().month,
+ DateTime.now().day,
+ 20,
+ 33,
+);
ConversationServer swarm({bool status = true, String owner = 'owner'}) {
final server = ConversationServer();
@@ -109,6 +117,39 @@ void main() {
expect(find.text('Three fixes are on main tonight.'), findsNothing);
});
+ testWidgets('Status shows the time alone on any day it runs', (tester) async {
+ final day = DateTime.now();
+ final late = DateTime(day.year, day.month, day.day, 23, 30);
+ final c = swarm().controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Builder(
+ builder: (context) => TextButton(
+ onPressed: () => showSuperTabProjectStatusWith(
+ context,
+ c,
+ 'lead',
+ now: () => late,
+ ),
+ child: const Text('open'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('open'));
+ await tester.pumpAndSettle();
+ expect(
+ find.text('Status · updated 8:33 PM'),
+ findsOneWidget,
+ reason: 'today, so no date, whatever the day',
+ );
+ expect(find.text('Three fixes are on main tonight.'), findsOneWidget);
+ });
+
testWidgets('with no report, Status is there and opens nothing', (
tester,
) async {
diff --git a/docs/plans/2026-11-02-phone-remove-note-plan.md b/docs/plans/2026-11-02-phone-remove-note-plan.md
new file mode 100644
index 000000000..a706d40a8
--- /dev/null
+++ b/docs/plans/2026-11-02-phone-remove-note-plan.md
@@ -0,0 +1,70 @@
+# Phone: remove a note in a project's Instructions Implementation Plan
+
+> **Way of working:** by this project's instructions (Engineer role), not subagent-driven-development: the failing test committed before its code, one independent review of the pull request. There is no Execution Handoff.
+
+**Goal:** A person who may remove one of the PM's notes can do it on the phone, under the rule Desktop uses.
+
+**Architecture:** The phone's Instructions page gets a Delete action on each note for a person who can write in the Swarm. It asks first, sends `note.remove`, and reads the notes again. The server keeps the rule and tells the PM.
+
+**Tech Stack:** Flutter widgets and `flutter_test`, in `mobile/`.
+
+**Spec:** Task #2277 (Tony). Desktop's `desktop/lib/super_tabs/instructions_panel.dart` `_removeNote`.
+
+## Global Constraints
+
+- The PR body starts with: Requested by [email protected] through Harness.
+- Mobile only. No new colors or icons. Phone tests use fakes. Never install on a phone. No on/off switch.
+
+## Sketch
+
+```
+ ‹ Instructions
+ #openharness · revision 12
+
+ …the instructions…
+
+ River's notes
+ Do not use Codex on machine A.
+ asked by dee · 2h ago Delete
+ Ship the phone first.
+ asked by tony · 1d ago · until 18:00 Delete
+
+ ┌───────────────────────────────┐
+ │ Delete this note? │
+ │ River is told it was deleted. │
+ │ Cancel Delete │
+ └───────────────────────────────┘
+```
+
+Nothing shows for a viewer. While a delete is under way its button is off, and a refusal says why above the text, where this page says errors.
+
+## Review Focus
+
+- Pressed twice: one `note.remove`.
+- Refused or offline: the note stays, and the page says why.
+- A note already gone (another device, or expired): the server's refusal shows and the next read drops it.
+- A person who becomes a viewer while the page is open loses Delete.
+- Delete sits inside the page's selectable text: a tap still presses it.
+
+## Design
+
+- **Growth, concurrency, migration, audience, identity:** N/A because it sends an existing command the server authorizes.
+- **Read cost:** one read of the document after a remove, as a revision move already does.
+- **Scale:** N/A because it is one command per press.
+- **Compatibility:** every backend that has notes takes the command.
+- **Failure:** a refusal is said on the page.
+- **Platforms:** iOS and Android share this page.
+
+---
+
+### Task 1: Delete on a note
+
+**Files:**
+- Modify: `mobile/lib/swarm/swarm_instructions_page.dart`
+- Test: `mobile/test/swarm/swarm_instructions_page_test.dart`
+
+- [ ] **Step 1: Write the failing tests:** an allowed person confirms and `note.remove` goes once with the project and note; Cancel sends nothing; a viewer sees no Delete; a refusal says why and keeps the note.
+- [ ] **Step 2: Run to verify they fail.** Run: `flutter test test/swarm/swarm_instructions_page_test.dart`. Expected: FAIL.
+- [ ] **Step 3: Implement,** with `confirmPhoneAction`.
+- [ ] **Step 4: Run to verify they pass,** then `flutter test test/swarm`.
+- [ ] **Step 5: Commit** the test first, then the code; push. Add a screenshot to the PR.
diff --git a/docs/plans/2026-11-03-phone-decision-choices-plan.md b/docs/plans/2026-11-03-phone-decision-choices-plan.md
new file mode 100644
index 000000000..821243a3e
--- /dev/null
+++ b/docs/plans/2026-11-03-phone-decision-choices-plan.md
@@ -0,0 +1,110 @@
+# Phone Decision Choices Implementation Plan
+
+> **How this is worked:** by the project's instructions, task by task, each failing test committed before its code.
+
+**Goal:** On the phone, an open decision also offers `Let <coordinator> decide` and `Not now`, and the answered ones are listed, with Desktop's words and rules.
+
+**Architecture:** `SwarmAsks` learns to send `delegate: true` and to read the `settled` list, falling back to `answered` on an older backend, as Desktop's `SuperTabDecisions` does. The session holds a delegation for Undo as it holds an answer. `Not now` keeps ids on this phone in `SwarmHomePrefs`, as Desktop keeps them on its computer. Activity shows the last 5 answered.
+
+**Tech Stack:** Flutter, `flutter_test` with fakes.
+
+**Spec:** Task #2281, Tony's phone list, task 26. Desktop: `desktop/lib/super_tabs/decisions.dart`, `decisions_view.dart`.
+
+## Sketch
+
+In a chat, an open decision:
+
+```
+┌───────────────────────────────────────┐
+│ Ship the beta on Friday? │
+│ Unblocks: the release notes │
+│ │
+│ [ Yes, Friday ] ( No, wait ) │
+│ │
+│ Let Product Manager decide · Not now │
+└───────────────────────────────────────┘
+```
+
+After `Not now`, in that chat:
+
+```
+ 1 decision set aside · Show
+```
+
+After `Let Product Manager decide`, for the Undo window, as an answer is held today:
+
+```
+┌───────────────────────────────────────┐
+│ Ship the beta on Friday? │
+│ Leaving it to Product Manager Undo │
+│ ▓▓▓▓▓▓▓▓▓▓░░░░░ │
+└───────────────────────────────────────┘
+```
+
+In Activity, under what's open, on the decisions it already lists:
+
+```
+ ┌─ Ship the beta on Friday? ─────────┐
+ │ Let Product Manager decide │
+ └────────────────────────────────────┘
+
+ Answered
+ ┌────────────────────────────────────┐
+ │ Which region first? │
+ │ You chose: Europe │
+ ├────────────────────────────────────┤
+ │ Ship the beta on Friday? │
+ │ Product Manager decided: Yes │
+ └────────────────────────────────────┘
+```
+
+Rules, as Desktop's:
+
+- `Let <coordinator> decide` shows only with a recommended option, in the word the project calls its coordinator.
+- `Not now` shows only in a chat: it folds that card there. It stays in Activity and its count, and isn't sent to the server. A decision asked later still shows.
+- `Answered` shows the last 5. A decision the coordinator took never reads as the person's own choice.
+
+## Global Constraints
+
+- The PR body starts with: `Requested by [email protected] through Harness.`
+- Mobile only, on main. No new colors or icons, no on/off switch. Never install a build on anyone's phone; tests use fakes.
+
+## Review Focus
+
+1. A delegation that didn't get a reply is sent again as a delegation, under the same receipt, never as a choice.
+2. Answered rows read after access was lost, or from an earlier read of the Swarm, never show.
+3. An older backend with no `settled` list falls back to `answered`; one with no decisions shows none.
+4. A recommended option missing from a decision offers no `Let <coordinator> decide`, where the phone used to read it as option 0.
+
+## Design
+
+- **Growth:** set-aside ids on the phone are capped, oldest first, and forgotten once answered or gone.
+- **Concurrency:** one answered read at a time per Swarm; one read asked during it runs once more.
+- **Read cost:** the answered list is read when Activity opens and after an answer, not on every poll. The backend caps it.
+- **Scale:** N/A because it's one capped list per Swarm, only while Activity is open.
+- **Compatibility:** falls back as Rule 3 says. An old phone ignores the new field.
+- **Migration and rollback:** none. Rolling back leaves unused ids in the phone's prefs.
+- **Audience:** the server enforces who reads each list; the phone keeps only ids.
+- **Identity:** the server decides who may answer, as today.
+- **Failure:** a failed read of the answered list says so on the section, and a failed send says so on the card.
+- **Platforms:** the phone app on iOS and Android, the same code.
+
+---
+
+### Task 1: The model and the sends
+
+**Files:** Modify `mobile/lib/swarm/swarm_asks.dart`, `swarm_session.dart`. Test `mobile/test/swarm/swarm_asks_test.dart`.
+
+**Interfaces:** Produces `SuperTabDecision.delegated`, `canDelegate`; `SwarmAsks.delegate`, `answered`, `readAnswered`; `SwarmSession.holdDelegate`.
+
+- [ ] Failing tests: delegate sends `delegate: true` and resends the same; the answered list reads `settled`, then `answered` on a 400, and none on a 404; a read from before the Swarm was read again is dropped; a missing recommended option can't be delegated.
+- [ ] Run them, implement, run them, commit.
+
+### Task 2: The screens
+
+**Files:** Modify `swarm_need_rows.dart`, `swarm_conversation_page.dart`, `swarm_activity_page.dart`, `swarm_home_prefs.dart`. Test `mobile/test/swarm/swarm_decision_choices_test.dart`, and a shots test.
+
+**Interfaces:** Produces `SwarmHomePrefs.decisionAside`, `setDecisionsAside`, `forgetDecisionsAside`.
+
+- [ ] Failing tests: the card offers both with the project's word; `Not now` folds it in the chat, `Show` brings it back, it survives a restart, and a later decision still shows; `Let … decide` holds for Undo, then sends; Activity lists the last 5 with the right words.
+- [ ] Run them, implement, run them, take screenshots, commit, mark the pull request ready and ask Quinn 2.
diff --git a/docs/plans/2026-11-03-phone-drafts-and-unsent-plan.md b/docs/plans/2026-11-03-phone-drafts-and-unsent-plan.md
new file mode 100644
index 000000000..03e797e40
--- /dev/null
+++ b/docs/plans/2026-11-03-phone-drafts-and-unsent-plan.md
@@ -0,0 +1,88 @@
+# Phone: drafts and unsent messages survive Implementation Plan
+
+> Worked by the project instructions (Engineer, revision 27): each plan task commits its failing test, then its code.
+
+**Goal:** A chat's draft stays per chat and thread until sent or cleared; a Not sent message survives a restart and can be retried or deleted; both are per account and go on sign-out and on losing access.
+
+**Architecture:** One sealed file per signed-in account (`SwarmKept`), as the kept Home is, read when the session starts. `SwarmConversation` and `SwarmThread` read their draft and posts from it when opened and write to it as they change. `SwarmInbox` drops a Swarm's part when access is lost; `SwarmHost` clears all of it on sign-out.
+
+**Tech Stack:** Flutter, ChaCha20-Poly1305 under a Keychain key, widget tests over `FakeSwarm` with an in-memory key.
+
+**Spec:** Tony's mobile list, task 25; Desktop's #2610 for thread drafts.
+
+## Sketch: the Not sent row
+
+```
+┌──────────────────────────────────────┐
+│ (D) dee │
+│ Ship the fix tonight? │
+│ ⚠ Not sent · Retry · Delete │
+└──────────────────────────────────────┘
+```
+
+Same row as today, in the same yellow and blue, with Delete added beside Retry. After a restart it looks the same. Delete takes it away at once, with no question. A draft has no new look: the words are simply still in the box.
+
+## Decisions
+
+- **Sealed, not the plain store.** Drafts hold what someone wrote, unlike read marks (ids and numbers). They are sealed as the kept Home is, with their own Keychain key.
+- **A Not sent message may already have arrived.** Its answer was lost, so nobody knows. Retry uses the same receipt, so it never posts twice. If it did arrive, Delete cannot unsend it: the message appears when the chat is next read.
+- **A post caught mid-send by a kill** comes back as Not sent, for the same reason.
+- **Files are not kept.** A draft's waiting files stay in memory only, as on Desktop. A Not sent post keeps the files already uploaded, as references in its command, but its row no longer draws their chips after a restart.
+- **A moment with no account is not a sign-out.** The app clears the kept file when someone signs out, another account signs in, or Swarm is turned off, not while the same account is still being read.
+
+## Design
+
+- growth: a sent or emptied draft and a post read back, refused or deleted leave at once. At most 500 drafts and 200 posts per account, oldest first; the whole file goes on sign-out.
+- concurrency: writes run one at a time per file, and a clear is never undone by an earlier write, as the kept Home does.
+- read cost: read once per session; a write comes at most every 300 ms while typing. A kept chat absent from the Swarm's read is asked for once per session, to learn whether access is gone.
+- scale: bounded per phone by the caps above; nothing server-side beyond that one ask. The file's size warns first.
+- compatibility: no file reads as nothing. No server change: Retry is the same command under the same receipt.
+- migration + rollback: nothing to migrate. An older app ignores the file, which stays sealed.
+- audience: only the signed-in account's, on this phone; another account's file opens for nobody, and its key goes on clear.
+- identity: the account id of the session.
+- failure: a Keychain or disk that refuses keeps nothing and logs it, and the draft stays in memory for this run.
+- platforms: phone, iOS and Android, through the Keychain or Keystore already used by the kept Home.
+
+## Global Constraints
+
+- PR body starts: Requested by [email protected] through Harness.
+- Mobile only, based on main. No new colors or icons. No on/off switch.
+- Never install builds on anyone's phone. Phone tests use fakes, never a real sign-out.
+
+## Review Focus
+
+- A chat lost while it is closed: its draft goes without the chat being opened.
+- Two accounts on one phone, one after the other: neither ever reads the other's.
+- A write under way when sign-out clears: nothing comes back.
+- Sent, then killed before the debounce: no sent text returns as a draft.
+- A restored post that the first read shows arrived: it leaves, and shows once.
+
+---
+
+### Task 1: A sealed file per account
+
+**Files:** Create `mobile/lib/swarm/swarm_kept.dart`. Test `mobile/test/swarm/swarm_kept_test.dart`.
+
+- [ ] Failing tests: round trip; another account reads none; a clear takes file and key; a damaged file is none; caps hold.
+- [ ] Implement, commit test first, then code.
+
+### Task 2: Drafts stay
+
+**Files:** Modify `swarm_conversation.dart`, `swarm_thread.dart`, `swarm_inbox.dart`, `swarm_reader.dart`, `swarm_session.dart`, `phone_shell.dart`. Test as above.
+
+- [ ] Failing tests: chat and thread drafts survive leaving and a restart; sending clears them.
+- [ ] Implement, commit test first, then code.
+
+### Task 3: Not sent stays, with Retry and Delete
+
+**Files:** Modify `swarm_outbox.dart`, `swarm_post_line.dart`, `swarm_conversation.dart`, `swarm_thread.dart`, the two pages.
+
+- [ ] Failing tests: a Not sent post survives a restart; Retry sends the same receipt; Delete removes it for good; a read that holds it settles it.
+- [ ] Implement, commit test first, then code.
+
+### Task 4: Clearing
+
+**Files:** Modify `swarm_session.dart`, `swarm_inbox.dart`, `swarm_conversation.dart`.
+
+- [ ] Failing tests: sign-out, another account and Swarm off clear it; a Swarm lost and a chat lost, open or closed, clear their part.
+- [ ] Implement, commit test first, then code. Screenshots in the PR.
diff --git a/docs/plans/2026-11-03-phone-no-lead-receipt-plan.md b/docs/plans/2026-11-03-phone-no-lead-receipt-plan.md
new file mode 100644
index 000000000..2ab73634b
--- /dev/null
+++ b/docs/plans/2026-11-03-phone-no-lead-receipt-plan.md
@@ -0,0 +1,74 @@
+# Phone: "Not sent · this chat has no Lead" Implementation Plan
+
+> Worked by the project instructions (Engineer, revision 27): each plan task commits its failing test, then its code.
+
+**Goal:** A message sent where no Lead runs says so, with Desktop's words, and the phone offers Add a Lead where it can start one.
+
+**Architecture:** `SwarmMessageReceipt` gains Desktop's no-Lead case. In a project chat, Add a Lead picks a machine with the new-project sheet's `swarmLeadMachines` and sends `lead.start`, as a new project does.
+
+**Tech Stack:** Flutter, widget tests over `FakeSwarm`.
+
+**Spec:** Tony's mobile list, task 29; `desktop/lib/super_tabs/message_receipt.dart`.
+
+## Sketch
+
+```
+┌──────────────────────────────────────┐
+│ (D) dee │
+│ Who picks this up? │
+│ ⚠ Not sent · this chat has no │
+│ Lead │
+│ Add a Lead │
+└──────────────────────────────────────┘
+
+Add a Lead opens the phone's usual sheet:
+
+┌──────────────────────────────────────┐
+│ Machine │
+│ ▭ MacBook Pro │
+│ ▭ Mac Studio │
+│ ▭ Mac mini offline │
+└──────────────────────────────────────┘
+```
+
+Red, as Desktop draws it. Choosing a machine starts the Lead; the line goes once the chat has one.
+
+## Decisions
+
+- **Same rule as Desktop:** the person's newest message, no delivery, the chat has no Lead, and it is not a Buddy chat.
+- **Where the phone differs:** Desktop's Add a Lead opens its New Harness box in that chat. The phone has no such box, and starting an agent in a task from a phone is a new feature. So:
+ - **Project chat:** Add a Lead works, through `lead.start`, which the phone already sends for a new project.
+ - **Task chat:** the same line with no action. Offering a button that cannot work would be worse.
+- **Who:** only someone the server lets manage the project sees the action; a refusal shows its words.
+
+## Design
+
+N/A for growth, concurrency, migration, audience and identity: nothing new is stored, and the server decides who may start a Lead. Read cost: no new reads. Compatibility: `lead.start` is already sent by this app. Failure: a refusal shows its words on the line. Platforms: phone.
+
+## Global Constraints
+
+- PR body starts: Requested by [email protected] through Harness.
+- Mobile only, based on main. No new colors or icons. No on/off switch.
+- Never install builds on anyone's phone. Phone tests use fakes.
+
+## Review Focus
+
+- A message kept from before, with the chat's Lead arriving meanwhile: no line.
+- A Lead already starting: no second start.
+- A Buddy chat: no line.
+- No machine free: the sheet says why rather than opening empty.
+- A viewer: no action.
+
+---
+
+### Task 1: The receipt
+
+**Files:** Modify `mobile/lib/swarm/swarm_message_receipt.dart`, `swarm_conversation_page.dart`. Test `mobile/test/swarm/swarm_no_lead_receipt_test.dart`.
+
+- [ ] Failing tests for each case above; implement; commit test first, then code.
+
+### Task 2: Add a Lead
+
+**Files:** Modify `mobile/lib/swarm/swarm_message_receipt.dart`, `swarm_conversation.dart`. Test as above.
+
+- [ ] Failing tests: the sheet lists machines, choosing one sends `lead.start`, one receipt on a retry, a refusal shows its words. Implement; commit test first, then code. Screenshots in the PR.
diff --git a/docs/plans/2026-11-03-phone-work-details-plan.md b/docs/plans/2026-11-03-phone-work-details-plan.md
new file mode 100644
index 000000000..c1f613046
--- /dev/null
+++ b/docs/plans/2026-11-03-phone-work-details-plan.md
@@ -0,0 +1,107 @@
+# Phone: a task's Work details: Implementation Plan
+
+> Way of working: this project's instructions. The Engineer implements it task by task, each failing test committed before its code. Reviewer: Orion. The Lead approves the sketch for Tony.
+
+**Goal:** A person can open a task's Work details on the phone and read its goal, changes, constraints and each acceptance check with its evidence, as Desktop shows them.
+
+**Architecture:** A read-only `SwarmWorkDetailsPage`, pushed from the chat's ⋮ sheet, the same place Desktop's chat menu has it. It reads only the conversation the phone's Swarm read already holds and rebuilds as that read changes. It sends nothing.
+
+**Tech Stack:** Flutter, Dart, existing Swarm widgets and widget tests with fakes.
+
+**Spec:** Task #2286; Desktop's `desktop/lib/super_tabs/work_details.dart`.
+
+## Screen sketch
+
+From the chat's existing ⋮ sheet, a new first row:
+
+```text
+Fix the login loop
+────────────────────
+Work details ←
+Rename
+Archive
+Notifications
+ All ✓
+ Mentions
+ Muted
+```
+
+The page, with the same top bar and text as the phone's Instructions page:
+
+```text
+← Work details
+ Fix the login loop
+──────────────────────────────────
+Goal:
+People signed out on a phone get
+sent back to sign-in in a loop.
+
+Changes:
+Keep the session through the
+redirect.
+
+Constraints:
+No new dependency.
+
+#14 Review PR 12: passed
+
+Builder · review
+
+ACCEPTANCE CHECKS
+
+The new test fails on main and
+passes
+Failed at abc123, passes at def456.
+Verified
+
+Tried on a real phone
+Not verified
+
+RESULT
+PR 12 at def456.
+```
+
+With no brief, the page says `This task has no description yet.`, as Desktop does. Sections with nothing in them don't show.
+
+## Global Constraints
+
+- Mobile only (`mobile/`). Same sections and words as Desktop, without its Record check button: this view is read-only.
+- No new colors or icons. Follows the phone's Swarm screens.
+- Phone tests use fakes. Never install a build on anyone's phone. No on/off switch.
+- PR body starts: `Requested by [email protected] through Harness.`
+
+## Review Focus
+
+- The row shows where Desktop's does: never in a project's own chat, a Buddy chat or a private conversation.
+- The page goes once the chat can no longer be read: access lost, signed out or the chat gone.
+- A check's fields are read from the server's row: one with no evidence, or an unknown assignment agent, must not throw.
+
+## Design
+
+- **Growth:** N/A because nothing is stored.
+- **Concurrency:** N/A because it only reads the snapshot on the UI thread.
+- **Read cost:** no new request: it reads what the Swarm read holds.
+- **Scale (10x):** N/A because it shows one task; a long brief scrolls.
+- **Compatibility:** N/A because it uses fields the phone already parses. An older server's missing field shows as an empty section.
+- **Migration + rollback:** none.
+- **Audience:** the server sends a chat only to those who may read it; the page goes when that ends.
+- **Identity:** N/A because it names the assignee as the read does, never the machine owner.
+- **Failure:** nothing to fail after the read; a chat gone closes the page.
+- **Platforms:** the phone app, iOS and Android.
+
+---
+
+### Task 1: The page, and its row in the ⋮ sheet
+
+**Files:**
+- Create: `mobile/lib/swarm/swarm_work_details_page.dart`, `mobile/test/swarm/swarm_work_details_page_test.dart`, `mobile/test/swarm/swarm_work_details_shots_test.dart`
+- Modify: `mobile/lib/swarm/swarm_chat_menu.dart`, `mobile/lib/swarm/swarm_chat_manage.dart`
+
+**Interfaces:**
+- Produces: `swarmHasWorkDetails(SwarmReader, String chatId)`; `openSwarmWorkDetails(BuildContext, {reader, chatId})`.
+- Consumes: `SuperTabConversation.brief/checks/assignment`, `superTabLinkedLine`, `superTabWorkStatusLabel`, `swarmTextParts`.
+
+- [ ] **Step 1: Commit failing tests:** the page shows goal, changes, constraints, linked line, assignee and status, each check with its evidence and Verified or Not verified, and the result; no brief says so; no write controls; it goes when the chat does; the row shows only where Desktop's does and opens the page.
+- [ ] **Step 2: Watch them fail.**
+- [ ] **Step 3: Commit the code.**
+- [ ] **Step 4: Screenshots** on a 390-point phone in both themes from made-up data, in the PR.
diff --git a/mobile/lib/phone/welcome/phone_welcome.dart b/mobile/lib/phone/welcome/phone_welcome.dart
index 084b766bc..5d1000a21 100644
--- a/mobile/lib/phone/welcome/phone_welcome.dart
+++ b/mobile/lib/phone/welcome/phone_welcome.dart
@@ -8,6 +8,7 @@ import 'package:harness_mobile/auth/sign_in_provider.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/state/app_state.dart';
import 'package:harness_mobile/swarm/swarm_home_cache.dart';
+import 'package:harness_mobile/swarm/swarm_kept.dart';
import '../exit_app.dart';
import '../tty.dart';
@@ -70,6 +71,7 @@ class PhoneWelcome extends StatefulWidget {
this.signIn,
this.scanCamera,
this.swarmHome,
+ this.swarmKept,
});
final AppNotifier notifier;
@@ -84,6 +86,7 @@ class PhoneWelcome extends StatefulWidget {
/// The Swarm Home kept on this phone ([SwarmHomeCache.device] when null).
final SwarmHomeCache? swarmHome;
+ final SwarmKeptStore? swarmKept;
@override
State<PhoneWelcome> createState() => _PhoneWelcomeState();
@@ -124,6 +127,8 @@ class _PhoneWelcomeState extends State<PhoneWelcome> {
// Signed out, so the last Swarm Home goes: a session that ended while the app was not running
// never had a signed-in shell to clear it ([SwarmHost]).
unawaited((widget.swarmHome ?? SwarmHomeCache.device()).clear());
+ // So do the drafts and unsent posts, whoever signs in next.
+ unawaited((widget.swarmKept ?? SealedSwarmKeptStore.device()).clear());
}
@override
diff --git a/mobile/lib/swarm/identity.dart b/mobile/lib/swarm/identity.dart
index 934a0f3fd..963e8a2ef 100644
--- a/mobile/lib/swarm/identity.dart
+++ b/mobile/lib/swarm/identity.dart
@@ -1,3 +1,3 @@
-/// How a person is named in the Swarm: their email's name, as the desktop
-/// names them (`desktop/lib/super_tabs/identity.dart`).
+/// Fallback for a person's recorded name when their Swarm membership is no
+/// longer available, as Desktop does (`desktop/lib/super_tabs/identity.dart`).
String superTabPersonName(String email) => email.split('@').first;
diff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dart
index ba706369d..6b8767e29 100644
--- a/mobile/lib/swarm/model.dart
+++ b/mobile/lib/swarm/model.dart
@@ -842,11 +842,12 @@ class SuperTabSnapshot {
/// Whether more than one person can start work here: teammates' agents are a question only then.
bool get hasTeammates => people.where((p) => p.role != 'viewer').length > 1;
- // Resolve the person shown in chat from the same identity as the roster.
- // Recorded labels remain the fallback for agents no longer in the Swarm.
+ // Resolve people shown in chat from the same identity as the roster.
+ // Recorded labels remain the fallback when a person or agent has left.
String authorName(SuperTabMessage message) => message.fromAgent
? agentName(message.authorId, fallback: message.authorName)
- : superTabPersonName(message.authorName);
+ : people.where((p) => p.id == message.authorId).firstOrNull?.username ??
+ superTabPersonName(message.authorName);
}
/// The Swarm's Local models add-on (docs/plans/2026-10-23-swarm-local-models.md): its grid, whether it is on, and what the
diff --git a/mobile/lib/swarm/swarm_activity.dart b/mobile/lib/swarm/swarm_activity.dart
index a42f69561..2557b937c 100644
--- a/mobile/lib/swarm/swarm_activity.dart
+++ b/mobile/lib/swarm/swarm_activity.dart
@@ -506,9 +506,10 @@ class SwarmActivity extends ChangeNotifier {
final decision = need.decision;
final asks = inbox.asks(need.swarmId);
final busy =
- session.held(need) != null ||
+ session.holding(need) ||
(asks?.answering.contains(decision.id) ?? false) ||
- asks?.unconfirmed(decision) != null;
+ asks?.unconfirmed(decision) != null ||
+ (asks?.unconfirmedDelegate(decision) ?? false);
final choice = decision.recommended;
if (!busy && choice >= 0 && choice < decision.options.length) {
return decision.options[choice];
@@ -651,9 +652,7 @@ class SwarmActivity extends ChangeNotifier {
bool _held(String key) => inbox.needs.any(
(need) =>
- need.key == key &&
- need is SwarmDecisionNeed &&
- session.held(need) != null,
+ need.key == key && need is SwarmDecisionNeed && session.holding(need),
);
/// On this phone's first Activity of a Swarm, the reactions already there
diff --git a/mobile/lib/swarm/swarm_activity_page.dart b/mobile/lib/swarm/swarm_activity_page.dart
index 279745353..691311221 100644
--- a/mobile/lib/swarm/swarm_activity_page.dart
+++ b/mobile/lib/swarm/swarm_activity_page.dart
@@ -10,7 +10,6 @@ import 'package:harness_mobile/shared/theme/app_space.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/shared/theme/app_type.dart';
-import 'identity.dart';
import 'model.dart';
import 'swarm_activity.dart';
import 'swarm_activity_feed.dart';
@@ -373,6 +372,12 @@ class _SwarmActivityViewState extends State<SwarmActivityView> {
SwarmGroup(
children: [for (final item in items) _row(context, session, item)],
),
+ if (_filter == SwarmActivityFilter.needsYou)
+ _AnsweredDecisions(
+ session: session,
+ swarmId: widget.swarmId,
+ projectId: widget.projectId,
+ ),
];
}
@@ -637,6 +642,144 @@ class _ClosesWhenGoneState extends State<_ClosesWhenGone> {
}
/// A line over the rows, with what can be done about it.
+/// The last few decisions answered, as the desktop's Notifications pane lists
+/// them under the open ones: each with the option chosen, or that the
+/// coordinator decided, called what its project calls it, and never as the
+/// person's own. Read when this shows, and again after an answer.
+class _AnsweredDecisions extends StatefulWidget {
+ const _AnsweredDecisions({
+ required this.session,
+ required this.swarmId,
+ required this.projectId,
+ });
+
+ final SwarmSession session;
+ final String? swarmId, projectId;
+
+ /// How many stay in view, as on the desktop.
+ static const shown = 5;
+
+ @override
+ State<_AnsweredDecisions> createState() => _AnsweredDecisionsState();
+}
+
+class _AnsweredDecisionsState extends State<_AnsweredDecisions> {
+ /// What was asked for, by Swarm and its read: a Swarm read again from
+ /// nothing is read again, and each only once otherwise.
+ final _asked = <String>{};
+
+ Iterable<(String, SwarmAsks)> get _asks sync* {
+ for (final swarm in widget.session.inbox.swarms) {
+ if (widget.swarmId != null && swarm.id != widget.swarmId) continue;
+ if (widget.session.inbox.asks(swarm.id) case final asks?) {
+ yield (swarm.id, asks);
+ }
+ }
+ }
+
+ void _read(String swarmId, SwarmAsks asks) => unawaited(
+ asks.readAnswered().then((_) {
+ widget.session.home.forgetDecisionsAside(swarmId, [
+ for (final decision in asks.answered) decision.id,
+ ]);
+ }),
+ );
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: widget.session.inbox,
+ builder: (context, _) {
+ final all = _asks.toList();
+ for (final (swarmId, asks) in all) {
+ if (_asked.add('$swarmId/${asks.reader.generation}')) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _read(swarmId, asks);
+ });
+ }
+ }
+ return ListenableBuilder(
+ listenable: Listenable.merge([for (final (_, asks) in all) asks]),
+ builder: (context, _) => _list(context, all),
+ );
+ },
+ );
+
+ Widget _list(BuildContext context, List<(String, SwarmAsks)> all) {
+ final projectId = widget.projectId;
+ final rows = [
+ for (final (_, asks) in all)
+ for (final decision in asks.answered)
+ if (projectId == null || decision.projectId == projectId)
+ (decision, asks),
+ ];
+ final epoch = DateTime.fromMillisecondsSinceEpoch(0);
+ rows.sort(
+ (a, b) => (b.$1.createdAt ?? epoch).compareTo(a.$1.createdAt ?? epoch),
+ );
+ final failed = all.where((e) => e.$2.answeredError != null).firstOrNull;
+ final caption = AppType.caption(
+ color: AppPalette.textSecondary,
+ height: 1.35,
+ );
+ return Column(
+ key: rows.isEmpty ? null : const ValueKey('swarm-answered'),
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ if (failed != null)
+ Padding(
+ padding: const EdgeInsets.only(top: AppSpace.s),
+ child: _Note(
+ text: failed.$2.answeredError!,
+ action: SwarmButton(
+ key: const ValueKey('swarm-answered-retry'),
+ label: 'Try again',
+ style: SwarmButtonStyle.link,
+ onPressed: () => _read(failed.$1, failed.$2),
+ ),
+ ),
+ ),
+ if (rows.isNotEmpty) ...[
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ AppSpace.xs,
+ AppSpace.l,
+ AppSpace.xs,
+ AppSpace.s,
+ ),
+ child: Text('Answered', style: caption),
+ ),
+ SwarmGroup(
+ children: [
+ for (final (decision, asks) in rows.take(
+ _AnsweredDecisions.shown,
+ ))
+ Padding(
+ key: ValueKey('swarm-answered-${decision.id}'),
+ padding: const EdgeInsets.all(AppSpace.m),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(
+ decision.question,
+ style: AppType.body(color: AppPalette.textPrimary),
+ ),
+ const SizedBox(height: 2),
+ Text(
+ '${decision.delegated ? '${asks.reader.snapshot?.coordinatorNameOf(decision.projectId) ?? kDefaultCoordinatorName} decided' : 'You chose'}: '
+ '${swarmOption(decision.options, decision.choice ?? -1)}',
+ style: caption,
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ],
+ ],
+ );
+ }
+}
+
class _Note extends StatelessWidget {
const _Note({super.key, required this.text, required this.action});
@@ -884,9 +1027,10 @@ class SwarmActivityRow extends StatelessWidget {
if (item case SwarmActivityNeed(need: final SwarmDecisionNeed need)
when handled == null) {
final asks = session.inbox.asks(need.swarmId);
- if (session.held(need) != null ||
+ if (session.holding(need) ||
(asks?.answering.contains(need.decision.id) ?? false) ||
asks?.unconfirmed(need.decision) != null ||
+ (asks?.unconfirmedDelegate(need.decision) ?? false) ||
session.dropped(need)) {
return SwarmDecisionAnswer(session: session, need: need);
}
@@ -943,7 +1087,7 @@ class SwarmActivityRow extends StatelessWidget {
/// Who an Activity row is from, by an id its avatar is coloured by and a
/// name, read in the row's own Swarm ([reader]) and never another's: the
/// asker, the tagging Lead, the worker, a thread's last writer, or who
-/// reacted. A person is named by their email's name, never the email.
+/// reacted. A person is named by their username, never the email.
({String id, String name}) swarmActivityWho(
SwarmActivityItem item,
SwarmReader? reader,
@@ -954,10 +1098,8 @@ class SwarmActivityRow extends StatelessWidget {
if (kind == 'agent') {
return snapshot?.agentName(id, fallback: fallback) ?? fallback;
}
- final email = snapshot?.people.where((p) => p.id == id).firstOrNull?.email;
- return email == null || email.isEmpty
- ? 'Someone'
- : superTabPersonName(email);
+ final person = snapshot?.people.where((p) => p.id == id).firstOrNull;
+ return person == null || person.email.isEmpty ? 'Someone' : person.username;
}
return switch (item) {
diff --git a/mobile/lib/swarm/swarm_asks.dart b/mobile/lib/swarm/swarm_asks.dart
index 485a3337a..4a4387057 100644
--- a/mobile/lib/swarm/swarm_asks.dart
+++ b/mobile/lib/swarm/swarm_asks.dart
@@ -38,6 +38,12 @@ class SuperTabDecision implements SwarmAskItem {
recommended = (row['recommended'] as num?)?.toInt() ?? 0,
unblocks = row['unblocks'] as String? ?? '',
choice = (row['choice'] as num?)?.toInt(),
+ delegated = row['delegated'] == true,
+ canDelegate = switch (row['recommended']) {
+ final num r =>
+ r >= 0 && r < (row['options'] as List? ?? const []).length,
+ _ => false,
+ },
note = row['note'] as String?,
createdAt = DateTime.tryParse(row['createdAt'] as String? ?? '');
@override
@@ -46,8 +52,15 @@ class SuperTabDecision implements SwarmAskItem {
final List<String> options;
final int recommended;
- /// The option the reader chose; null while it is open.
+ /// The option the reader chose, or the coordinator chose for them
+ /// ([delegated]); null while it is open.
final int? choice;
+
+ /// The reader left it to the coordinator, who took the recommended option.
+ final bool delegated;
+
+ /// Whether the coordinator can answer it: only with a recommended option.
+ final bool canDelegate;
final String? note;
@override
final DateTime? createdAt;
@@ -132,7 +145,7 @@ class SwarmAsks extends ChangeNotifier {
/// Answers sent whose reply never came, by decision: sent again under the
/// same receipt and choice until one is confirmed, so the backend applies
/// the answer once and no other is offered meanwhile.
- final _unconfirmed = <String, ({String operationId, int choice})>{};
+ final _unconfirmed = <String, ({String operationId, int? choice})>{};
/// Tags being marked done, tags whose Done failed (with what to say on
/// them), and tags confirmed done that a list read before then may still
@@ -153,6 +166,13 @@ class SwarmAsks extends ChangeNotifier {
int? unconfirmed(SuperTabDecision decision) =>
_unconfirmed[decision.id]?.choice;
+ /// A delegation sent for [decision] and not confirmed: [delegate] sends it
+ /// again.
+ bool unconfirmedDelegate(SuperTabDecision decision) {
+ final sent = _unconfirmed[decision.id];
+ return sent != null && sent.choice == null;
+ }
+
/// An ask that arrived after the first read: what a phone notice tells.
void Function(SwarmAskItem item)? onArrived;
@@ -376,7 +396,15 @@ class SwarmAsks extends ChangeNotifier {
/// as it was, whatever [choice] says; a decision the backend has answered
/// already (by this answer, its reply lost, or another device) is read
/// back.
- Future<bool> answer(SuperTabDecision decision, int choice) async {
+ Future<bool> answer(SuperTabDecision decision, int choice) =>
+ _answer(decision, choice);
+
+ /// Let the coordinator decide: the backend answers with the recommended
+ /// option on the reader's behalf, recorded as the coordinator's choice,
+ /// never as theirs. Sent again as [answer] is.
+ Future<bool> delegate(SuperTabDecision decision) => _answer(decision, null);
+
+ Future<bool> _answer(SuperTabDecision decision, int? choice) async {
if (_disposed || !answering.add(decision.id)) return false;
final sent = _unconfirmed[decision.id] ??= (
operationId: superTabOperationId(),
@@ -387,7 +415,10 @@ class SwarmAsks extends ChangeNotifier {
await _command({
'type': 'decision.answer',
'decisionId': decision.id,
- 'choice': sent.choice,
+ if (sent.choice case final chosen?)
+ 'choice': chosen
+ else
+ 'delegate': true,
}, operationId: sent.operationId);
} on SuperTabFailure catch (failure) {
if (failure.code != 'DECISION_ANSWERED') {
@@ -412,10 +443,73 @@ class SwarmAsks extends ChangeNotifier {
_unconfirmed.remove(decision.id);
error = null;
await load();
+ if (_answeredAt != null) unawaited(readAnswered());
unawaited(reader.refresh());
return true;
}
+ /// The newest decisions answered, by the reader or the coordinator, as the
+ /// last [readAnswered] found them. Read only on asking: nothing polls them.
+ /// What was read of an earlier read of the Swarm, or before access was lost,
+ /// never shows.
+ List<SuperTabDecision> get answered =>
+ _answeredAt == reader.generation && !reader.accessRevoked
+ ? _answered
+ : const [];
+ List<SuperTabDecision> _answered = const [];
+ int? _answeredAt;
+
+ /// What to say when the answered list could not be read; null otherwise.
+ String? get answeredError => answered.isEmpty ? _answeredError : null;
+ String? _answeredError;
+ Future<void>? _answeredReading;
+ bool _answeredAgain = false;
+
+ /// Reads [answered]; asked during a read, reads once more after it.
+ Future<void> readAnswered() {
+ if (_answeredReading case final running?) {
+ _answeredAgain = true;
+ return running;
+ }
+ return _answeredReading = () async {
+ do {
+ _answeredAgain = false;
+ await _readAnswered();
+ } while (_answeredAgain && !_disposed);
+ }().whenComplete(() => _answeredReading = null);
+ }
+
+ Future<void> _readAnswered() async {
+ final generation = reader.generation;
+ try {
+ final rows = await _settledRows();
+ if (_disposed || reader.generation != generation) return;
+ _answered = List.unmodifiable(rows.map(SuperTabDecision.fromJson));
+ _answeredAt = generation;
+ _answeredError = null;
+ } catch (failure) {
+ if (_disposed || reader.generation != generation) return;
+ appLog.warn(
+ 'swarm',
+ 'Answered decisions in ${reader.tabId} not read',
+ error: failure,
+ );
+ _answeredError = 'Could not load answered decisions. Try again.';
+ }
+ notifyListeners();
+ }
+
+ /// `settled` holds the answers the coordinator gave too. A backend from
+ /// before Let PM decide has no such list: its `answered` holds every answer.
+ Future<List<Map<String, dynamic>>> _settledRows() async {
+ try {
+ return await _rows('decisions?state=settled', 'decisions');
+ } on SuperTabFailure catch (failure) {
+ if (failure.statusCode != 400) rethrow;
+ return _rows('decisions?state=answered', 'decisions');
+ }
+ }
+
/// The reader is finished with [mention]: [finishing] at once, out of
/// [mentions] once the backend confirms it. A failure says so on that tag
/// alone ([notDone]); the tag stays, to be marked again.
diff --git a/mobile/lib/swarm/swarm_buddy.dart b/mobile/lib/swarm/swarm_buddy.dart
index 9b7fd05d2..e10ed76a0 100644
--- a/mobile/lib/swarm/swarm_buddy.dart
+++ b/mobile/lib/swarm/swarm_buddy.dart
@@ -1,6 +1,5 @@
import 'package:flutter/foundation.dart';
-import 'identity.dart';
import 'model.dart';
import 'swarm_reader.dart';
import 'swarm_request.dart';
@@ -499,17 +498,14 @@ String _machineName(Object? name, {String fallback = 'Your machine'}) {
: name;
}
-/// A person of [reader]'s Swarm by the name it shows them by: their address
-/// before the @; "its owner" while the Swarm does not list them (the
+/// A person of [reader]'s Swarm by the name it shows them by: their username;
+/// "its owner" while the Swarm does not list them (the
/// desktop's `buddyPersonName`).
String swarmBuddyPersonName(SwarmReader reader, String personId) {
- final email = reader.snapshot?.people
+ final person = reader.snapshot?.people
.where((p) => p.id == personId)
- .firstOrNull
- ?.email;
- return email == null || email.isEmpty
- ? 'its owner'
- : superTabPersonName(email);
+ .firstOrNull;
+ return person == null || person.email.isEmpty ? 'its owner' : person.username;
}
/// Opens the person's Buddy chat in [projectId], on the server first when
diff --git a/mobile/lib/swarm/swarm_chat_menu.dart b/mobile/lib/swarm/swarm_chat_menu.dart
index e11187a40..322098c26 100644
--- a/mobile/lib/swarm/swarm_chat_menu.dart
+++ b/mobile/lib/swarm/swarm_chat_menu.dart
@@ -13,6 +13,7 @@ import 'swarm_chat_manage.dart';
import 'swarm_chat_notify.dart';
import 'swarm_buddy.dart' show swarmIsOldBuddyChat;
import 'swarm_reader.dart';
+import 'swarm_work_details_page.dart';
/// The chat menu's Notifications rows (the desktop's chat menu, Slack's
/// channel notifications): one per [SwarmNotify], the reader's own setting
@@ -191,9 +192,21 @@ class _SwarmChatMenuButtonState extends State<SwarmChatMenuButton> {
widget.reader,
widget.chatId,
onShown: (route) => _sheet = route,
- // Rename and Archive where the desktop's chat menu has them.
- actions: () =>
- swarmChatManageActions(context, widget.reader, widget.chatId),
+ // Work details, Rename and Archive where the desktop's chat menu has
+ // them.
+ actions: () => [
+ if (swarmHasWorkDetails(widget.reader, widget.chatId))
+ PhoneSheetAction(
+ icon: LucideIcons.info300,
+ label: 'Work details',
+ onTap: () => openSwarmWorkDetails(
+ context,
+ reader: widget.reader,
+ chatId: widget.chatId,
+ ),
+ ),
+ ...swarmChatManageActions(context, widget.reader, widget.chatId),
+ ],
).whenComplete(() => _sheet = null);
@override
diff --git a/mobile/lib/swarm/swarm_conversation.dart b/mobile/lib/swarm/swarm_conversation.dart
index 7a1b74fcf..a9945e6f2 100644
--- a/mobile/lib/swarm/swarm_conversation.dart
+++ b/mobile/lib/swarm/swarm_conversation.dart
@@ -52,6 +52,76 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {
reader.addListener(_swarmChanged);
reader.reads.addListener(_swarmChanged);
files.addListener(_filesChanged);
+ _composer.addListener(_keepDraft);
+ _takeKept();
+ }
+
+ /// What a person wrote and has not got through, from before this chat was
+ /// opened: its draft, and its posts as Not sent. A read that holds one drops
+ /// it ([SwarmOutbox.settle]).
+ void _takeKept() {
+ final kept = reader.kept;
+ if (kept == null || _disposed) return;
+ if (!kept.loaded) {
+ kept.addListener(_takeKeptOnce);
+ return;
+ }
+ if (_draft.isEmpty) {
+ if (kept.draft(reader.tabId, id, null) case final draft?) {
+ _draft = _keptDraft = draft.text;
+ _mentions.addAll(draft.mentions);
+ }
+ }
+ if (_outbox.isEmpty) {
+ final posts = [
+ for (final row in kept.posts(reader.tabId, id, null))
+ ?SwarmPost.fromKept(row, _heldOf),
+ ];
+ if (posts.isNotEmpty) _outbox.restore(posts);
+ }
+ _composer.changed();
+ }
+
+ void _takeKeptOnce() {
+ reader.kept?.removeListener(_takeKeptOnce);
+ _takeKept();
+ }
+
+ /// What a kept post puts back in the box if it is refused: only its words.
+ static Object? _heldOf(String text) => (
+ draft: text,
+ mentions: const <String, String>{},
+ replyTo: null as SuperTabMessage?,
+ newSession: false,
+ sessionProjectId: null as String?,
+ );
+
+ String _keptDraft = '';
+
+ void _keepDraft() {
+ if (_disposed || _refused || _draft == _keptDraft) return;
+ _keptDraft = _draft;
+ reader.kept?.setDraft(reader.tabId, id, null, _draft, _mentions);
+ }
+
+ void _keepPosts() {
+ if (_disposed) return;
+ reader.kept?.setPosts(reader.tabId, id, null, [
+ for (final post in _outbox.posts)
+ if (post.state != SwarmPostState.confirmed) post.kept,
+ ]);
+ }
+
+ /// Takes [post], Not sent, away for good: Delete. It may still have arrived,
+ /// and then it shows when the chat is next read.
+ void deletePost(SwarmPost post) {
+ if (_disposed || post.state != SwarmPostState.unconfirmed) return;
+ _uploads.forget(post.files);
+ _outbox.remove(post);
+ if (error != null && error == _postError && _outbox.unconfirmed == null) {
+ error = null;
+ _tell();
+ }
}
final SwarmReader reader;
@@ -126,8 +196,13 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {
/// `threadDraft`): a thread closed and opened again finds it.
final _threadDrafts = <String, String>{};
- String threadDraft(String root) => _threadDrafts[root] ?? '';
+ String threadDraft(String root) =>
+ _threadDrafts[root] ??
+ reader.kept?.draft(reader.tabId, id, root)?.text ??
+ '';
void setThreadDraft(String root, String text) {
+ if (_refused) return;
+ reader.kept?.setDraft(reader.tabId, id, root, text);
if (text.isEmpty) {
_threadDrafts.remove(root);
} else {
@@ -238,6 +313,7 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {
path: '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}/commands',
timeout: sendTimeout,
onChanged: () {
+ _keepPosts();
if (!_disposed) _tell();
},
onTaken: (post) {
@@ -619,8 +695,9 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {
error != null;
_refused = true;
_forget();
- _draft = '';
+ _draft = _keptDraft = '';
_threadDrafts.clear();
+ reader.kept?.dropChat(reader.tabId, id);
// A thread's files go too; its own screen hears it and gives up theirs.
for (final box in _threadFiles.values) {
box.clear();
@@ -780,7 +857,10 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {
);
}
// A post read back shows as its message, once, whatever its answer.
- changed |= _outbox.settle(messages);
+ if (_outbox.settle(messages)) {
+ changed = true;
+ _keepPosts();
+ }
if (older || !_read || latest) {
final before = SuperTabPage.read(answer['next']);
changed |=
@@ -860,6 +940,7 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {
);
_draft = '';
_mentions.clear();
+ _keepDraft();
_replyingTo = null;
_newSession = false;
_sessionProjectId = null;
@@ -1398,6 +1479,8 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {
@override
void dispose() {
+ _keepDraft();
+ reader.kept?.removeListener(_takeKeptOnce);
_disposed = true;
_uploads.close();
_outbox.close();
diff --git a/mobile/lib/swarm/swarm_conversation_page.dart b/mobile/lib/swarm/swarm_conversation_page.dart
index 7b56ce2c1..095ecbe39 100644
--- a/mobile/lib/swarm/swarm_conversation_page.dart
+++ b/mobile/lib/swarm/swarm_conversation_page.dart
@@ -372,12 +372,15 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
: widget.messageId ?? _held.value,
);
c.composer.addListener(_drafted);
+ // The draft it kept, in the box.
+ _drafted();
c.addListener(_chatMoved);
c.addListener(_guardVoice);
if (widget.mention case final agentId?) c.mention(agentId);
reader.addListener(_see);
reader.addListener(_guardVoice);
session.inbox.addListener(_see);
+ session.home.addListener(_see);
_see();
_watch();
unawaited(
@@ -664,6 +667,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
session?.inbox
?..removeListener(_attach)
..removeListener(_see);
+ session?.home.removeListener(_see);
if (_conversation case final c?) {
c.composer.removeListener(_drafted);
c.removeListener(_chatMoved);
@@ -1002,6 +1006,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
state: post.state,
quote: null,
onSendAgain: () => unawaited(t.retry(post)),
+ onDelete: () => t.deletePost(post),
),
);
}
@@ -1434,6 +1439,36 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
);
},
),
+ if (view.decisionsAside.isNotEmpty)
+ Padding(
+ key: const ValueKey('swarm-decisions-aside'),
+ padding: const EdgeInsets.symmetric(
+ horizontal: AppSpace.l,
+ ),
+ child: Row(
+ children: [
+ Text(
+ view.decisionsAside.length == 1
+ ? '1 decision set aside'
+ : '${view.decisionsAside.length} decisions set aside',
+ style: swarmChatText(
+ 13.5,
+ color: AppPalette.textSecondary,
+ ),
+ ),
+ SwarmButton(
+ key: const ValueKey('swarm-decisions-show'),
+ label: 'Show',
+ style: SwarmButtonStyle.link,
+ onPressed: () => _session?.home.setDecisionsAside(
+ c.reader.tabId,
+ view.decisionsAside,
+ aside: false,
+ ),
+ ),
+ ],
+ ),
+ ),
if (view.old)
Padding(
key: const ValueKey('swarm-old-chat'),
@@ -1534,15 +1569,14 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
/// cannot read it (#2090).
/// The people [m] tags: each one's address by their username, as the
/// server names them; an older server's member without one goes by their
- /// email's name.
+ /// email name.
static Map<String, String> _taggedOf(
SwarmConversation c,
SuperTabMessage m,
) => {
if (m.mentions.isNotEmpty)
for (final person in c.reader.snapshot?.people ?? <SuperTabPerson>[])
- if (m.mentions.contains(person.id))
- person.chosenUsername ?? person.email.split('@').first: person.email,
+ if (m.mentions.contains(person.id)) person.username: person.email,
};
/// The open task's steps, each read on its own, merged into its chat (task
@@ -1599,13 +1633,14 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
(picture: agent?.avatar, status: null);
/// Who gave a reaction, by name and never by email: "You", an agent's
- /// name, another person's email name.
+ /// name, another person's username.
String _reactorName(SwarmConversation c, String kind, String id) {
if (kind == 'person' && id == c.reader.accountId) return 'You';
final snapshot = c.reader.snapshot;
if (kind == 'agent') return snapshot?.agentName(id) ?? 'Agent';
- final email = snapshot?.people.where((p) => p.id == id).firstOrNull?.email;
- return email == null ? 'Someone' : superTabPersonName(email);
+ final person = snapshot?.people.where((p) => p.id == id).firstOrNull;
+ return person?.username ??
+ (person == null ? 'Someone' : superTabPersonName(person.email));
}
/// The reaction picker over thread [t]'s message [id], as [_pickReaction]
@@ -1797,7 +1832,12 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
final reactions = c.reactionsOf(m);
final receipt =
m.id == latestOwn?.id &&
- const {'queued', 'uncertain'}.contains(m.receiptDelivery?.status);
+ // Sent to nobody: where no Lead runs, the line says so.
+ (m.receiptDelivery == null ||
+ const {
+ 'queued',
+ 'uncertain',
+ }.contains(m.receiptDelivery?.status));
// A card's facts are its group's: only a reader of the group has
// them, and a change to them draws the row again.
final group = c.conversation;
@@ -2007,6 +2047,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
text: reply?.text,
),
onSendAgain: () => unawaited(_retry(c, post)),
+ onDelete: () => c.deletePost(post),
);
}
if (index - lead < entries.length) {
@@ -2362,6 +2403,7 @@ class _ChatView {
required this.leads,
required this.mentionable,
required this.decisions,
+ required this.decisionsAside,
required this.buddyProject,
required this.hint,
required this.cards,
@@ -2401,7 +2443,7 @@ class _ChatView {
// (Dee, 11-01: they blocked the project chat). A chat not open to the
// person shows none either, even while the decisions read has not caught
// up.
- final decisions = [
+ final asked = [
if (group != null && buddyProject != null)
for (final need in session.inbox.needs)
if (need is SwarmDecisionNeed &&
@@ -2410,6 +2452,12 @@ class _ChatView {
need.decision.projectId == buddyProject))
need,
];
+ bool aside(SwarmDecisionNeed need) =>
+ session.home.decisionAside(need.swarmId, need.decision.id);
+ final decisions = [
+ for (final need in asked)
+ if (!aside(need)) need,
+ ];
return _ChatView(
known: group != null,
title: group == null
@@ -2437,6 +2485,10 @@ class _ChatView {
decisions: before != null && _sameAsks(before.decisions, decisions)
? before.decisions
: List.unmodifiable(decisions),
+ decisionsAside: [
+ for (final need in asked)
+ if (aside(need)) need.decision.id,
+ ],
buddyProject: buddyProject,
// "Message Wren"; plain while no Buddy runs to read it.
hint: buddyProject != null && swarmBuddy(reader, buddyProject) != null
@@ -2480,6 +2532,9 @@ class _ChatView {
final List<String> mentionable;
final List<SwarmDecisionNeed> decisions;
+ /// The decisions of this Buddy chat set aside with Not now, by id.
+ final List<String> decisionsAside;
+
/// The project whose Buddy chat of the person's own this is; null for any
/// other chat.
final String? buddyProject;
@@ -2524,6 +2579,7 @@ class _ChatView {
setEquals(other.leads, leads) &&
listEquals(other.mentionable, mentionable) &&
identical(other.decisions, decisions) &&
+ listEquals(other.decisionsAside, decisionsAside) &&
other.buddyProject == buddyProject &&
other.hint == hint &&
mapEquals(other.cards, cards);
@@ -2538,6 +2594,7 @@ class _ChatView {
old,
Object.hashAll(names),
Object.hashAll(mentionable),
+ Object.hashAll(decisionsAside),
decisions,
buddyProject,
hint,
@@ -2980,6 +3037,7 @@ class _Pending extends StatelessWidget {
required this.state,
required this.quote,
required this.onSendAgain,
+ required this.onDelete,
required this.look,
});
@@ -2994,7 +3052,7 @@ class _Pending extends StatelessWidget {
final SwarmMentions mentions;
final SwarmPostState state;
final Widget? quote;
- final VoidCallback onSendAgain;
+ final VoidCallback onSendAgain, onDelete;
@override
Widget build(BuildContext context) {
@@ -3047,7 +3105,11 @@ class _Pending extends StatelessWidget {
if (state != SwarmPostState.confirmed)
Padding(
padding: const EdgeInsets.only(top: AppSpace.xs),
- child: SwarmPostLine(sending: sending, onRetry: onSendAgain),
+ child: SwarmPostLine(
+ sending: sending,
+ onRetry: onSendAgain,
+ onDelete: onDelete,
+ ),
),
],
),
@@ -3149,6 +3211,11 @@ class _Ask extends StatelessWidget {
session: session,
need: need,
fillRecommended: true,
+ onNotNow: () => session.home.setDecisionsAside(
+ need.swarmId,
+ [need.decision.id],
+ aside: true,
+ ),
),
),
],
diff --git a/mobile/lib/swarm/swarm_home_cache.dart b/mobile/lib/swarm/swarm_home_cache.dart
index 43b74ae52..f929acbb7 100644
--- a/mobile/lib/swarm/swarm_home_cache.dart
+++ b/mobile/lib/swarm/swarm_home_cache.dart
@@ -26,14 +26,14 @@ abstract interface class SwarmHomeKey {
/// [SwarmHomeKey] in the iOS Keychain (Android: Keystore-backed), readable
/// after the first unlock and never carried to another device or a backup.
class KeychainSwarmHomeKey implements SwarmHomeKey {
- const KeychainSwarmHomeKey();
+ const KeychainSwarmHomeKey({this._name = 'swarm_home_key'});
static const _storage = FlutterSecureStorage(
iOptions: IOSOptions(
accessibility: KeychainAccessibility.first_unlock_this_device,
),
);
- static const _name = 'swarm_home_key';
+ final String _name;
@override
Future<String?> read() => _storage.read(key: _name);
diff --git a/mobile/lib/swarm/swarm_home_prefs.dart b/mobile/lib/swarm/swarm_home_prefs.dart
index 42f94ba50..e5c692b0e 100644
--- a/mobile/lib/swarm/swarm_home_prefs.dart
+++ b/mobile/lib/swarm/swarm_home_prefs.dart
@@ -10,6 +10,7 @@ import 'swarm_home_list.dart';
typedef _SwarmHomeKept = ({
List<String> pins,
List<String> folds,
+ List<String> aside,
String? swarmId,
DateTime? seenAt,
SwarmHomeFilter filter,
@@ -37,6 +38,9 @@ class SwarmHomePrefs extends ChangeNotifier {
/// The most pins kept; the oldest goes first.
static const keptPins = 50;
+ /// The most decisions set aside kept; the oldest goes first.
+ static const keptAside = 200;
+
/// The most folded status cards kept, as the desktop keeps
/// (`SuperTabController.statusFoldedKept`); the oldest goes first.
static const keptFolds = 200;
@@ -57,6 +61,11 @@ class SwarmHomePrefs extends ChangeNotifier {
Set<String> get folds => Set.unmodifiable(_folds);
final _folds = <String>{};
+ /// The open decisions set aside in the person's Buddy chat with Not now,
+ /// by [swarmHomeProjectKey] of their Swarm and id, oldest first: kept on this
+ /// phone, as the desktop keeps them on its computer.
+ final _aside = <String>{};
+
/// The one Swarm Home shows; null for all of them.
String? get swarmId => _swarmId;
String? _swarmId;
@@ -97,7 +106,7 @@ class SwarmHomePrefs extends ChangeNotifier {
/// Before the choices are read back: the pins taken off and the cards
/// unfolded meanwhile, which what is read does not bring back, and whether
/// a Swarm was chosen to show, which stands over the one read.
- final _unpinned = <String>{}, _unfolded = <String>{};
+ final _unpinned = <String>{}, _unfolded = <String>{}, _unaside = <String>{};
bool _shownChosen = false,
_filterChosen = false,
_sortChosen = false,
@@ -152,6 +161,41 @@ class SwarmHomePrefs extends ChangeNotifier {
_changed();
}
+ /// Whether decision [id] of [swarmId] is set aside with Not now.
+ bool decisionAside(String swarmId, String id) =>
+ _aside.contains(swarmHomeProjectKey(swarmId, id));
+
+ /// Sets decisions [ids] of [swarmId] aside, or shows them again.
+ void setDecisionsAside(
+ String swarmId,
+ Iterable<String> ids, {
+ required bool aside,
+ }) {
+ var moved = false;
+ for (final id in ids) {
+ final key = swarmHomeProjectKey(swarmId, id);
+ if (!_loaded) {
+ if (aside) {
+ _unaside.remove(key);
+ } else if (_unaside.add(key)) {
+ _touched = true;
+ }
+ }
+ moved |= aside ? _aside.add(key) : _aside.remove(key);
+ }
+ if (!moved) return;
+ _cap();
+ _changed();
+ }
+
+ /// Decisions [ids] of [swarmId] are answered: nothing keeps them aside.
+ void forgetDecisionsAside(String swarmId, Iterable<String> ids) {
+ final keys = [for (final id in ids) swarmHomeProjectKey(swarmId, id)];
+ if (!keys.any(_aside.contains)) return;
+ _aside.removeAll(keys);
+ _changed();
+ }
+
/// Home shows Swarm [swarmId] alone; null shows them all.
void show(String? swarmId) {
if (!_loaded) {
@@ -232,16 +276,19 @@ class SwarmHomePrefs extends ChangeNotifier {
/// Drops the pins, folds and choice of any Swarm but [swarmIds]; whether
/// any went.
bool _keep(Set<String> swarmIds) {
- final before = _pins.length + _folds.length;
+ final before = _pins.length + _folds.length + _aside.length;
bool other(String key) => !swarmIds.contains(key.split('/').first);
_pins.removeWhere(other);
_folds.removeWhere(other);
+ _aside.removeWhere(other);
final gone = _swarmId != null && !swarmIds.contains(_swarmId);
if (gone) _swarmId = null;
final buddyGone =
_buddySwarmId != null && !swarmIds.contains(_buddySwarmId);
if (buddyGone) _buddySwarmId = null;
- return gone || buddyGone || _pins.length + _folds.length != before;
+ return gone ||
+ buddyGone ||
+ _pins.length + _folds.length + _aside.length != before;
}
/// At most [keptPins] pins and [keptFolds] folds, the oldest going first;
@@ -254,8 +301,8 @@ class SwarmHomePrefs extends ChangeNotifier {
return true;
}
- final pins = trim(_pins, keptPins);
- return trim(_folds, keptFolds) || pins;
+ final pins = trim(_pins, keptPins), aside = trim(_aside, keptAside);
+ return trim(_folds, keptFolds) || pins || aside;
}
void _changed() {
@@ -296,6 +343,7 @@ class SwarmHomePrefs extends ChangeNotifier {
merge(_pins, pins, _unpinned);
merge(_folds, folds, _unfolded);
+ merge(_aside, read.aside, _unaside);
if (!_shownChosen) _swarmId = swarmId;
if (!_filterChosen) _filter = read.filter;
if (!_sortChosen) _sort = read.sort;
@@ -307,6 +355,7 @@ class SwarmHomePrefs extends ChangeNotifier {
}
_unpinned.clear();
_unfolded.clear();
+ _unaside.clear();
// Swarms the account lost meanwhile take what was read of them too.
final kept = _swarms;
final dropped = kept != null && _keep(kept);
@@ -318,6 +367,7 @@ class SwarmHomePrefs extends ChangeNotifier {
static const _SwarmHomeKept _nothingKept = (
pins: [],
folds: [],
+ aside: [],
swarmId: null,
seenAt: null,
filter: SwarmHomeFilter.all,
@@ -341,6 +391,7 @@ class SwarmHomePrefs extends ChangeNotifier {
return (
pins: keys(json['pins']),
folds: keys(json['folded']),
+ aside: keys(json['aside']),
swarmId: json['swarm'] is String ? json['swarm'] as String : null,
seenAt: switch (json['seen']) {
final int ms when ms > 0 => DateTime.fromMillisecondsSinceEpoch(ms),
@@ -370,6 +421,7 @@ class SwarmHomePrefs extends ChangeNotifier {
try {
if (_pins.isEmpty &&
_folds.isEmpty &&
+ _aside.isEmpty &&
_swarmId == null &&
_buddySwarmId == null &&
_seenAt == null &&
@@ -381,6 +433,7 @@ class SwarmHomePrefs extends ChangeNotifier {
jsonEncode({
'pins': [..._pins],
if (_folds.isNotEmpty) 'folded': [..._folds],
+ if (_aside.isNotEmpty) 'aside': [..._aside],
'swarm': ?_swarmId,
'buddySwarm': ?_buddySwarmId,
'seen': ?_seenAt?.millisecondsSinceEpoch,
diff --git a/mobile/lib/swarm/swarm_inbox.dart b/mobile/lib/swarm/swarm_inbox.dart
index 095ac463a..3c7b9e83c 100644
--- a/mobile/lib/swarm/swarm_inbox.dart
+++ b/mobile/lib/swarm/swarm_inbox.dart
@@ -8,6 +8,7 @@ import 'model.dart';
import 'swarm_asks.dart';
import 'swarm_buddy.dart';
import 'swarm_home_cache.dart';
+import 'swarm_kept.dart';
import 'swarm_home_keeper.dart';
import 'swarm_read_marks.dart';
import 'swarm_reader.dart';
@@ -98,13 +99,19 @@ class SwarmInbox extends ChangeNotifier {
SwarmHomeCache? homeCache,
Duration homeWait = const Duration(seconds: 30),
this.readMarks,
- }) : _now = now ?? DateTime.now,
+ SwarmKeptStore? keptStore,
+ }) : kept = SwarmKept(accountId: accountId, store: keptStore),
+ _now = now ?? DateTime.now,
_home = homeCache == null
? null
: SwarmHomeKeeper(homeCache, accountId, wait: homeWait) {
+ kept.addListener(_dropUnlisted);
if (_home != null) unawaited(_restore());
}
+ /// The account's drafts and unsent posts ([SwarmKept]).
+ final SwarmKept kept;
+
/// Keeps the last Home ([SwarmHomeCache]), so a cold start draws it at once.
final SwarmHomeKeeper? _home;
@@ -402,6 +409,8 @@ class SwarmInbox extends ChangeNotifier {
}
if (_disposed) return;
if (!listEquals(listed, swarms)) swarms = listed;
+ _listedIds = {for (final swarm in listed) swarm.id};
+ _dropUnlisted();
// What was read of them stays while they cannot be read again.
if (invited != null && !listEquals(invited, invitations)) {
invitations = invited;
@@ -557,6 +566,11 @@ class SwarmInbox extends ChangeNotifier {
reader.reads.addListener(() => _readerRead(id, reader));
reader.readMarks = SwarmReadMarks(reader, store: readMarks)
..addListener(_relay);
+ reader.kept = kept;
+ void watch() => _checkKept(id, reader);
+ _keptWatches[id] = watch;
+ reader.addListener(watch);
+ kept.addListener(watch);
_asks[id] = SwarmAsks(reader)
..onArrived = ((ask) => onArrived?.call(switch (ask) {
final SuperTabDecision decision => SwarmDecisionNeed(id, decision),
@@ -570,11 +584,61 @@ class SwarmInbox extends ChangeNotifier {
/// A Swarm off the list ([lost]), or the inbox closing: what a screen
/// still holds of it is taken back ([SwarmReader.revoke]) before it is
/// dropped.
+ /// The Swarms the last list that answered named; null before one has.
+ Set<String>? _listedIds;
+
+ /// A Swarm the account no longer has goes from what is kept, also one lost
+ /// while the app was closed, which has no reader to say so. Once what was
+ /// kept is back, and only from a list that answered.
+ void _dropUnlisted() {
+ final listed = _listedIds;
+ if (_disposed || listed == null || !kept.loaded) return;
+ for (final id in kept.tabs) {
+ if (!listed.contains(id)) kept.dropSwarm(id);
+ }
+ }
+
+ /// How [_checkKept] follows each Swarm, by its id.
+ final _keptWatches = <String, VoidCallback>{};
+
+ /// Chats kept but not in a Swarm's read, already asked for this session.
+ final _keptAsked = <(String, String)>{};
+
+ /// What is kept of Swarm [id] goes when the person has lost it, and of one of
+ /// its chats when that is lost, opened or not: a closed chat is in no full
+ /// read, so one missing from it is asked for by id, once a session.
+ void _checkKept(String id, SwarmReader reader) {
+ if (_disposed || !kept.loaded) return;
+ if (reader.accessRevoked) {
+ kept.dropSwarm(id);
+ return;
+ }
+ final snapshot = reader.snapshot;
+ if (snapshot == null || reader.heldLoad == 0) return;
+ for (final chat in kept.chats(id)) {
+ if (snapshot.conversation(chat) != null) continue;
+ if (!_keptAsked.add((id, chat))) continue;
+ unawaited(() async {
+ try {
+ if (!await reader.loadConversation(chat) && !_disposed) {
+ kept.dropChat(id, chat);
+ }
+ } catch (_) {
+ // Not known either way: it stays, and is asked for again next session.
+ }
+ }());
+ }
+ }
+
void _drop(String id, {bool lost = true}) {
+ final watch = _keptWatches.remove(id);
+ if (watch != null) kept.removeListener(watch);
+ if (lost) kept.dropSwarm(id);
final threads = _threads.remove(id);
_asks.remove(id)?.dispose();
final reader = _readers.remove(id)?..removeListener(_relay);
if (reader != null) {
+ if (watch != null) reader.removeListener(watch);
final marks = reader.readMarks;
// Lost, it is revoked first, so its read marks leave the phone too;
// the inbox closing keeps them, written now, for the next one.
@@ -691,6 +755,9 @@ class SwarmInbox extends ChangeNotifier {
for (final id in _readers.keys.toList()) {
_drop(id, lost: false);
}
+ kept
+ ..removeListener(_dropUnlisted)
+ ..dispose();
super.dispose();
}
}
diff --git a/mobile/lib/swarm/swarm_instructions_page.dart b/mobile/lib/swarm/swarm_instructions_page.dart
index 2a66f837d..ca8e4d34a 100644
--- a/mobile/lib/swarm/swarm_instructions_page.dart
+++ b/mobile/lib/swarm/swarm_instructions_page.dart
@@ -5,6 +5,7 @@ import 'package:flutter/material.dart';
import 'package:harness_mobile/core/relative_time.dart';
import 'package:harness_mobile/phone/phone_navigation.dart';
+import 'package:harness_mobile/phone/phone_sheet.dart';
import 'package:harness_mobile/phone/tty.dart';
import 'package:harness_mobile/shared/theme/app_space.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
@@ -30,11 +31,12 @@ void openSwarmInstructions(
),
);
-/// A project's instruction document and its coordinator's notes, read only
-/// (project instructions, decisions 15 and 16). Read when it opens and again
-/// when the project's `instructionsRevision` or `notesRevision` moves in the
-/// Swarm read; a pull reads again. Nothing is read on a poll, and nothing is
-/// written from the phone.
+/// A project's instruction document and its coordinator's notes (project
+/// instructions, decisions 15 and 16). Read when it opens and again when the
+/// project's `instructionsRevision` or `notesRevision` moves in the Swarm read;
+/// a pull reads again. Nothing is read on a poll. A person who can write in the
+/// Swarm may delete a note, after confirming; the document is edited on a
+/// computer.
class SwarmInstructionsPage extends StatefulWidget {
const SwarmInstructionsPage({
super.key,
@@ -59,6 +61,12 @@ class _SwarmInstructionsPageState extends State<SwarmInstructionsPage> {
Future<void>? _reading;
bool _again = false;
+ /// The notes a delete is under way for: one at a time each.
+ final _deleting = <String>{};
+
+ /// Why the last delete was refused; null when it went or none was tried.
+ String? _deleteError;
+
SuperTabProject? get _project => widget.reader.snapshot?.projects
.where((p) => p.id == widget.projectId)
.firstOrNull;
@@ -71,6 +79,56 @@ class _SwarmInstructionsPageState extends State<SwarmInstructionsPage> {
?.username ??
'a member';
+ /// Whether the person may delete a note: as Desktop, one who can write in the
+ /// Swarm. The server decides.
+ bool get _canWrite =>
+ !widget.reader.accessRevoked &&
+ (widget.reader.snapshot?.people
+ .where((p) => p.id == widget.reader.accountId)
+ .firstOrNull
+ ?.canWrite ??
+ false);
+
+ Future<void> _delete(SuperTabNote note, String coordinator) async {
+ if (_deleting.contains(note.id)) return;
+ final confirmed = await confirmPhoneAction(
+ context,
+ title: 'Delete this note?',
+ message: '$coordinator is told it was deleted.',
+ confirmLabel: 'Delete',
+ );
+ if (!confirmed || !mounted || !_deleting.add(note.id)) return;
+ setState(() => _deleteError = null);
+ String? refused;
+ final reader = widget.reader;
+ try {
+ await reader.request(
+ 'POST',
+ '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}/commands',
+ body: {
+ 'operationId': superTabOperationId(),
+ 'command': {
+ 'type': 'note.remove',
+ 'projectId': widget.projectId,
+ 'noteId': note.id,
+ },
+ },
+ );
+ } on SuperTabFailure catch (failure) {
+ refused = failure.message;
+ } on Object {
+ refused = 'The note was not deleted. Try again.';
+ }
+ if (!mounted) return;
+ setState(() {
+ _deleting.remove(note.id);
+ _deleteError = refused;
+ });
+ // Its revision moved with the command; a refusal may mean it is gone.
+ unawaited(_read());
+ if (refused == null) unawaited(reader.refresh());
+ }
+
@override
void initState() {
super.initState();
@@ -231,13 +289,14 @@ class _SwarmInstructionsPageState extends State<SwarmInstructionsPage> {
);
}
final now = clock.now();
+ final canWrite = _canWrite;
final notes = [...doc.notes]..sort((a, b) => b.at.compareTo(a.at));
return SelectionArea(
child: ListView(
physics: scroll,
padding: padding,
children: [
- if (_error case final error?) ...[
+ if (_deleteError ?? _error case final error?) ...[
Text(
error,
key: const ValueKey('swarm-instructions-error'),
@@ -267,19 +326,51 @@ class _SwarmInstructionsPageState extends State<SwarmInstructionsPage> {
Padding(
key: ValueKey('swarm-instructions-note-${note.id}'),
padding: const EdgeInsets.only(bottom: AppSpace.m),
- child: Column(
+ child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- Text(note.text, style: swarmChatText(15)),
- Text(
- [
- 'asked by ${_personName(note.askedBy)}',
- relativeAgo(note.at, now),
- if (note.expiresAt case final until?)
- 'until ${_until(until, now)}',
- ].join(' · '),
- style: quiet,
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(note.text, style: swarmChatText(15)),
+ Text(
+ [
+ 'asked by ${_personName(note.askedBy)}',
+ relativeAgo(note.at, now),
+ if (note.expiresAt case final until?)
+ 'until ${_until(until, now)}',
+ ].join(' · '),
+ style: quiet,
+ ),
+ ],
+ ),
),
+ if (canWrite)
+ TtyTap(
+ key: ValueKey('swarm-instructions-delete-${note.id}'),
+ semanticsLabel: 'Delete this note',
+ onTap: _deleting.contains(note.id)
+ ? null
+ : () =>
+ unawaited(_delete(note, doc.coordinatorName)),
+ child: Padding(
+ padding: const EdgeInsets.only(
+ left: AppSpace.s,
+ top: AppSpace.xs,
+ bottom: AppSpace.xs,
+ ),
+ child: Text(
+ 'Delete',
+ style: swarmChatText(
+ 14,
+ color: _deleting.contains(note.id)
+ ? AppPalette.textFaint
+ : AppPalette.accentOnSurface,
+ ),
+ ),
+ ),
+ ),
],
),
),
diff --git a/mobile/lib/swarm/swarm_kept.dart b/mobile/lib/swarm/swarm_kept.dart
new file mode 100644
index 000000000..6c46e8d0c
--- /dev/null
+++ b/mobile/lib/swarm/swarm_kept.dart
@@ -0,0 +1,409 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:cryptography/cryptography.dart';
+import 'package:cryptography/dart.dart';
+import 'package:flutter/foundation.dart';
+
+import '../core/harness_file_store.dart';
+import '../e2ee/bytes.dart';
+import '../logging/app_log.dart';
+import 'swarm_home_cache.dart' show KeychainSwarmHomeKey, SwarmHomeKey;
+
+/// Where [SwarmKept] keeps what it holds, one account's at a time.
+abstract interface class SwarmKeptStore {
+ /// [accountId]'s, or null: none, or none it can open.
+ Future<Map<String, dynamic>?> read(String accountId);
+ Future<void> write(String accountId, Map<String, dynamic> kept);
+
+ /// Nothing kept, and nothing left that could open it.
+ Future<void> clear();
+}
+
+/// [SwarmKeptStore] for tests and for a phone that keeps nothing past the run.
+class MemorySwarmKeptStore implements SwarmKeptStore {
+ Map<String, dynamic>? held;
+ String heldBy = 'me';
+
+ @override
+ Future<Map<String, dynamic>?> read(String accountId) async =>
+ accountId == heldBy ? held : null;
+
+ @override
+ Future<void> write(String accountId, Map<String, dynamic> kept) async {
+ heldBy = accountId;
+ held = jsonDecode(jsonEncode(kept)) as Map<String, dynamic>;
+ }
+
+ @override
+ Future<void> clear() async => held = null;
+}
+
+/// What a person wrote and has not got through, sealed as the kept Home is
+/// (`SwarmHomeCache`): ChaCha20-Poly1305 under a random key of its own in the
+/// Keychain, in [file] beside the app's state. A file that does not open is
+/// none, and goes; [clear] takes the key too.
+class SealedSwarmKeptStore implements SwarmKeptStore {
+ SealedSwarmKeptStore({required this.key, required this.file});
+
+ /// The device's: one, so its clears and writes keep one order, whoever asks.
+ factory SealedSwarmKeptStore.device() => _device ??= SealedSwarmKeptStore(
+ key: const KeychainSwarmHomeKey(name: 'swarm_kept_key'),
+ file: File('${HarnessFileStore.shared.directory.path}/swarm-kept.bin'),
+ );
+ static SealedSwarmKeptStore? _device;
+
+ final SwarmHomeKey key;
+ final File file;
+
+ static const _format = 1;
+ static const _aead = DartChacha20.poly1305Aead();
+ static const _nonceBytes = 12, _macBytes = 16;
+
+ Future<void> _tail = Future.value();
+
+ /// One operation at a time: a clear is never undone by a write before it.
+ Future<T> _serial<T>(Future<T> Function() action) {
+ final run = _tail.then((_) => action());
+ _tail = run.then((_) {}, onError: (Object _) {});
+ return run;
+ }
+
+ @override
+ Future<Map<String, dynamic>?> read(String accountId) => _serial(() async {
+ try {
+ if (!await file.exists()) return null;
+ final secret = await key.read();
+ final opened = secret == null
+ ? null
+ : _open(b64d(secret), await file.readAsBytes());
+ if (opened == null ||
+ opened['format'] != _format ||
+ opened['account'] != accountId) {
+ await _forget();
+ return null;
+ }
+ return opened;
+ } catch (failure) {
+ appLog.warn('swarm', 'Drafts not read: ${failure.runtimeType}');
+ await _forget();
+ return null;
+ }
+ });
+
+ @override
+ Future<void> write(String accountId, Map<String, dynamic> kept) =>
+ _serial(() async {
+ try {
+ var secret = await key.read();
+ if (secret == null) {
+ secret = b64e(secureRandomBytes(32));
+ await key.write(secret);
+ }
+ final nonce = secureRandomBytes(_nonceBytes);
+ final box = _aead.encryptSync(
+ utf8.encode(
+ jsonEncode({'format': _format, 'account': accountId, ...kept}),
+ ),
+ secretKey: SecretKeyData(b64d(secret)),
+ nonce: nonce,
+ );
+ await file.parent.create(recursive: true);
+ final next = File('${file.path}.next');
+ await next.writeAsBytes(box.concatenation(), flush: true);
+ await next.rename(file.path);
+ } catch (failure) {
+ // Held in memory for this run; never words in the log.
+ appLog.warn('swarm', 'Drafts not kept: ${failure.runtimeType}');
+ await _forget();
+ }
+ });
+
+ @override
+ Future<void> clear() => _serial(() async {
+ await _forget();
+ try {
+ await key.delete();
+ } catch (_) {}
+ });
+
+ Future<void> _forget() async {
+ for (final path in [file.path, '${file.path}.next']) {
+ try {
+ await File(path).delete();
+ } on FileSystemException {
+ // Not there.
+ }
+ }
+ }
+
+ static Map<String, dynamic>? _open(Uint8List secret, Uint8List sealed) {
+ if (sealed.length < _nonceBytes + _macBytes) return null;
+ try {
+ final clear = _aead.decryptSync(
+ SecretBox.fromConcatenation(
+ sealed,
+ nonceLength: _nonceBytes,
+ macLength: _macBytes,
+ ),
+ secretKey: SecretKeyData(secret),
+ );
+ final json = jsonDecode(utf8.decode(clear));
+ return json is Map<String, dynamic> ? json : null;
+ } on SecretBoxAuthenticationError {
+ return null;
+ }
+ }
+}
+
+/// A draft as kept: its words, and those it mentions by id.
+typedef SwarmKeptDraft = ({String text, Map<String, String> mentions});
+
+/// The account's drafts and unsent posts, by Swarm, chat and thread, for as
+/// long as they are its own (Tony's mobile list, task 25; the desktop's
+/// `threadDrafts`, #2610). Held here for the session, whatever a chat does, and
+/// in [store] across restarts. One per [SwarmInbox]; [SwarmHost] clears the
+/// store when the account leaves.
+class SwarmKept extends ChangeNotifier {
+ SwarmKept({
+ required this.accountId,
+ SwarmKeptStore? store,
+ this.saveAfter = const Duration(milliseconds: 300),
+ }) : _store = store {
+ if (store == null) {
+ _loaded = true;
+ ready = Future.value();
+ } else {
+ ready = _load();
+ }
+ }
+
+ static const maxDrafts = 500, maxPosts = 200;
+
+ final String accountId;
+ final SwarmKeptStore? _store;
+
+ /// How long a draft waits to be written, while someone types.
+ final Duration saveAfter;
+
+ /// Done once what was kept is read back.
+ late final Future<void> ready;
+
+ bool get loaded => _loaded;
+ bool _loaded = false;
+
+ /// Oldest first, so the caps let the oldest go.
+ final _drafts = <String, Map<String, dynamic>>{};
+ final _posts = <String, Map<String, dynamic>>{};
+
+ /// What changed before the read back: it wins over what was kept.
+ final _touched = <String>{};
+ Timer? _save;
+ bool _disposed = false;
+
+ static String _at(String tab, String chat, String? root) =>
+ jsonEncode([tab, chat, root]);
+
+ Future<void> _load() async {
+ Map<String, dynamic>? kept;
+ try {
+ kept = await _store!.read(accountId);
+ } catch (_) {
+ // None: this run's stays in memory.
+ }
+ if (_disposed) return;
+ final older = <String, Map<String, dynamic>>{};
+ for (final raw in _list(kept?['drafts'])) {
+ if (raw case {
+ 'tab': final String tab,
+ 'chat': final String chat,
+ 'text': final String _,
+ }) {
+ older[_at(tab, chat, raw['root'] as String?)] = raw;
+ }
+ }
+ final olderPosts = <String, Map<String, dynamic>>{};
+ for (final raw in _list(kept?['posts'])) {
+ if (raw case {
+ 'tab': final String tab,
+ 'chat': final String chat,
+ 'posts': final List _,
+ }) {
+ olderPosts[_at(tab, chat, raw['root'] as String?)] = raw;
+ }
+ }
+ bool isDropped(Map<String, dynamic> row) =>
+ _dropped.any((gone) => gone(row));
+ final held = older.length + olderPosts.length;
+ older.removeWhere((at, row) => _touched.contains(at) || isDropped(row));
+ olderPosts.removeWhere(
+ (at, row) => _touched.contains(at) || isDropped(row),
+ );
+ // Something dropped before it was read: the file must lose it too.
+ final filtered = older.length + olderPosts.length < held;
+ // Older first, then what this run has already changed.
+ final drafts = {...older, ..._drafts};
+ final posts = {...olderPosts, ..._posts};
+ _drafts
+ ..clear()
+ ..addAll(drafts);
+ _posts
+ ..clear()
+ ..addAll(posts);
+ _loaded = true;
+ if (_touched.isNotEmpty || filtered) _saveSoon(now: filtered);
+ notifyListeners();
+ }
+
+ static List<Map<String, dynamic>> _list(Object? raw) => [
+ if (raw is List)
+ for (final row in raw)
+ if (row is Map<String, dynamic>) row,
+ ];
+
+ SwarmKeptDraft? draft(String tab, String chat, String? root) {
+ final row = _drafts[_at(tab, chat, root)];
+ if (row == null) return null;
+ return (
+ text: row['text'] as String,
+ mentions: {
+ if (row['mentions'] case final Map mentions)
+ for (final MapEntry(:key, :value) in mentions.entries)
+ if (key is String && value is String) key: value,
+ },
+ );
+ }
+
+ /// Keeps [text] as the draft there; empty, it leaves.
+ void setDraft(
+ String tab,
+ String chat,
+ String? root,
+ String text, [
+ Map<String, String> mentions = const {},
+ ]) {
+ if (_disposed) return;
+ final at = _at(tab, chat, root);
+ _touched.add(at);
+ final was = _drafts.remove(at);
+ if (text.isEmpty) {
+ if (was != null) _saveSoon();
+ return;
+ }
+ _drafts[at] = {
+ 'tab': tab,
+ 'chat': chat,
+ 'root': ?root,
+ 'text': text,
+ if (mentions.isNotEmpty) 'mentions': mentions,
+ };
+ while (_drafts.length > maxDrafts) {
+ _drafts.remove(_drafts.keys.first);
+ }
+ _saveSoon();
+ }
+
+ List<Map<String, dynamic>> posts(String tab, String chat, String? root) => [
+ for (final post in _list(_posts[_at(tab, chat, root)]?['posts'])) post,
+ ];
+
+ int get _postCount =>
+ _posts.values.fold(0, (n, row) => n + (row['posts'] as List).length);
+
+ /// Keeps [posts] as those on their way there, written at once: a phone may
+ /// be killed the moment after a send.
+ void setPosts(
+ String tab,
+ String chat,
+ String? root,
+ List<Map<String, dynamic>> posts,
+ ) {
+ if (_disposed) return;
+ final at = _at(tab, chat, root);
+ final was = _posts[at];
+ if (was == null && posts.isEmpty) return;
+ _touched.add(at);
+ _posts.remove(at);
+ if (posts.isNotEmpty) {
+ _posts[at] = {'tab': tab, 'chat': chat, 'root': ?root, 'posts': posts};
+ }
+ while (_postCount > maxPosts) {
+ _posts.remove(_posts.keys.first);
+ }
+ _saveSoon(now: true);
+ }
+
+ /// The chats it holds something of in Swarm [tab].
+ Set<String> chats(String tab) => {
+ for (final row in [..._drafts.values, ..._posts.values])
+ if (row['tab'] == tab) row['chat'] as String,
+ };
+
+ /// The Swarms it holds something of.
+ Set<String> get tabs => {
+ for (final row in [..._drafts.values, ..._posts.values])
+ row['tab'] as String,
+ };
+
+ /// The person lost [chat]: nothing of it stays.
+ void dropChat(String tab, String chat) =>
+ _drop((row) => row['tab'] == tab && row['chat'] == chat);
+
+ /// The person lost Swarm [tab]: nothing of it stays.
+ void dropSwarm(String tab) => _drop((row) => row['tab'] == tab);
+
+ void _drop(bool Function(Map<String, dynamic>) gone) {
+ if (_disposed) return;
+ for (final held in [_drafts, _posts]) {
+ for (final at in [
+ for (final MapEntry(:key, :value) in held.entries)
+ if (gone(value)) key,
+ ]) {
+ held.remove(at);
+ _touched.add(at);
+ }
+ }
+ _dropped.add(gone);
+ _saveSoon(now: true);
+ }
+
+ /// What was dropped before the read back: it does not come back with it.
+ final _dropped = <bool Function(Map<String, dynamic>)>[];
+
+ void _saveSoon({bool now = false}) {
+ if (!_loaded || _store == null || _disposed) return;
+ _save?.cancel();
+ _save = null;
+ if (now || saveAfter == Duration.zero) {
+ unawaited(_write());
+ } else {
+ _save = Timer(saveAfter, () => unawaited(_write()));
+ }
+ }
+
+ Future<void> _write() async {
+ _save = null;
+ await _store?.write(accountId, {
+ 'drafts': _drafts.values.toList(),
+ 'posts': _posts.values.toList(),
+ });
+ }
+
+ /// Written now: the app going to the background may be its last moment.
+ Future<void> flush() async {
+ if (_disposed || !_loaded || _store == null) return;
+ _save?.cancel();
+ await _write();
+ }
+
+ @override
+ void dispose() {
+ if (_save != null) {
+ _save?.cancel();
+ unawaited(_write());
+ }
+ _disposed = true;
+ super.dispose();
+ }
+}
diff --git a/mobile/lib/swarm/swarm_leaderboard.dart b/mobile/lib/swarm/swarm_leaderboard.dart
index 716e5032b..e7d9fabb4 100644
--- a/mobile/lib/swarm/swarm_leaderboard.dart
+++ b/mobile/lib/swarm/swarm_leaderboard.dart
@@ -12,7 +12,6 @@ import 'package:harness_mobile/shared/theme/app_type.dart';
import 'package:harness_mobile/shared/widgets/skeleton.dart';
import 'package:harness_mobile/shared/widgets/touch_target.dart';
-import 'identity.dart';
import 'swarm_invites_sheet.dart';
import 'model.dart';
import 'swarm_leaderboard_reader.dart';
@@ -61,8 +60,7 @@ List<SwarmProjectHuman> swarmProjectHumans(
for (final person in swarmProjectPeople(snapshot, project))
(
person: person,
- name:
- scores[person.id]?.displayName ?? superTabPersonName(person.email),
+ name: scores[person.id]?.displayName ?? person.username,
score: scores[person.id],
own: person.id == viewer,
),
@@ -553,7 +551,7 @@ class _SwarmLeaderboardPageState extends State<SwarmLeaderboardPage> {
SuperTabPerson? personOf(String id) =>
people.where((p) => p.id == id).firstOrNull;
String nameOf(SwarmScore score) => switch (personOf(score.personId)) {
- final person? => score.displayName ?? superTabPersonName(person.email),
+ final person? => score.displayName ?? person.username,
null => 'Former member',
};
final week = _shownLabel(reader, current);
diff --git a/mobile/lib/swarm/swarm_machines.dart b/mobile/lib/swarm/swarm_machines.dart
index 04b237c3e..53260f455 100644
--- a/mobile/lib/swarm/swarm_machines.dart
+++ b/mobile/lib/swarm/swarm_machines.dart
@@ -8,7 +8,6 @@ import '../shared/theme/app_icon_size.dart';
import '../shared/theme/app_space.dart';
import '../shared/theme/app_theme.dart';
import '../shared/theme/app_type.dart';
-import 'identity.dart';
import 'model.dart';
import 'swarm_buddy.dart';
import 'swarm_machine_menu.dart';
@@ -144,7 +143,7 @@ class _SwarmMachinesSectionState extends State<SwarmMachinesSection> {
const SizedBox(width: AppSpace.s),
SwarmAvatar(
id: owner.id,
- name: superTabPersonName(owner.email),
+ name: owner.username,
picture: owner.avatar,
size: AppIconSize.standalone,
),
@@ -271,7 +270,7 @@ class SwarmMachineSheet extends StatelessWidget {
),
_detail('Status', view.status),
if (view.owner case final owner?)
- _detail('Owner', superTabPersonName(owner.email)),
+ _detail('Owner', owner.username),
_heading('Hardware'),
if (view.dim)
_detail('Readings', 'Current readings unavailable')
diff --git a/mobile/lib/swarm/swarm_message_receipt.dart b/mobile/lib/swarm/swarm_message_receipt.dart
index de5e0fc0e..2d95264b4 100644
--- a/mobile/lib/swarm/swarm_message_receipt.dart
+++ b/mobile/lib/swarm/swarm_message_receipt.dart
@@ -4,6 +4,7 @@ import 'package:clock/clock.dart';
import 'package:flutter/material.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
+import 'package:harness_mobile/phone/phone_sheet.dart';
import 'package:harness_mobile/phone/phone_shell_scope.dart';
import 'package:harness_mobile/shared/theme/app_space.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
@@ -12,6 +13,8 @@ import 'package:harness_mobile/shared/theme/app_type.dart';
import 'model.dart';
import 'swarm_conversation.dart';
import 'swarm_message_row.dart' show swarmChatText;
+import 'swarm_new_project_sheet.dart' show SwarmLeadMachine, swarmLeadMachines;
+import 'swarm_request.dart';
import 'swarm_thread_line.dart' show swarmAgo;
/// How long a queued delivery's claims fail before its sender is told, and how
@@ -125,6 +128,17 @@ class _SwarmMessageReceiptState extends State<SwarmMessageReceipt>
final delivery = message.receiptDelivery;
final agent = delivery == null ? null : snapshot?.agent(delivery.agentId);
final now = clock.now();
+ // Desktop's "Not sent · this chat has no Lead": sent to nobody, where no
+ // Lead runs. A Buddy chat has none: its Buddy takes the message.
+ if (snapshot != null &&
+ group != null &&
+ delivery == null &&
+ group.leadId == null &&
+ !group.isBuddyChat &&
+ reader.error == null) {
+ _wakeUpAt(null, now);
+ return _noLead(context, c, snapshot.isProjectLead(group.id));
+ }
// Said only of a recipient of this chat, from what was just read: a row
// kept from before, or the Swarm out of reach, says nothing of where it is.
if (snapshot == null ||
@@ -196,6 +210,122 @@ class _SwarmMessageReceiptState extends State<SwarmMessageReceipt>
);
}
+ /// A Lead being started from this line, and what refused it.
+ bool _startingLead = false;
+ String? _leadError;
+
+ /// One receipt per machine chosen, kept while its answer may have been lost,
+ /// so trying again is the same start.
+ final _leadStarts = <String, String>{};
+
+ /// Desktop's no-Lead line. Add a Lead only where the phone can start one: a
+ /// project chat, through `lead.start` as a new project does. A task chat's
+ /// Lead comes from Desktop's New Harness box, which the phone has not.
+ Widget _noLead(BuildContext context, SwarmConversation c, bool projectChat) {
+ final free = c.canPost && !_startingLead;
+ return _line(
+ icon: LucideIcons.triangleAlert,
+ color: Theme.of(context).colorScheme.error,
+ title: 'Not sent · this chat has no Lead',
+ note: _leadError,
+ actions: [
+ if (projectChat)
+ _ReceiptLink(
+ key: const ValueKey('swarm-receipt-add-lead'),
+ label: 'Add a Lead',
+ busy: _startingLead,
+ dimmed: !free && !_startingLead,
+ onPressed: free ? () => unawaited(_pickLeadMachine(c)) : null,
+ ),
+ ],
+ );
+ }
+
+ /// The Swarm's machines that could run the project's Lead, as New project
+ /// lists them; one that cannot now is listed with why, and not picked.
+ Future<void> _pickLeadMachine(SwarmConversation c) async {
+ final snapshot = c.reader.snapshot;
+ if (snapshot == null) return;
+ final machines = swarmLeadMachines(
+ snapshot,
+ c.reader.accountId,
+ now: clock.now(),
+ );
+ if (machines.isEmpty) {
+ setState(
+ () => _leadError =
+ 'No machine in this Swarm can run a Lead. Add one on Desktop.',
+ );
+ return;
+ }
+ await showPhoneSheet(
+ context,
+ title: 'Machine',
+ sections: [
+ PhoneSheetSection(
+ actions: [
+ for (final m in machines)
+ PhoneSheetAction(
+ icon: LucideIcons.laptop,
+ label: m.name,
+ value: m.startable ? null : m.detail,
+ enabled: m.startable,
+ onTap: () => unawaited(_startLead(c, m)),
+ ),
+ ],
+ ),
+ ],
+ );
+ }
+
+ Future<void> _startLead(SwarmConversation c, SwarmLeadMachine machine) async {
+ final reader = c.reader;
+ final group = c.conversation;
+ final project = group == null
+ ? null
+ : reader.snapshot?.projectFor(group.id);
+ if (project == null || _startingLead || !machine.startable) return;
+ final url = project.repository?['repositoryUrl'];
+ final operationId = _leadStarts[machine.id] ??= superTabOperationId();
+ setState(() {
+ _startingLead = true;
+ _leadError = null;
+ });
+ try {
+ await reader.request(
+ 'POST',
+ '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}/commands',
+ body: {
+ 'operationId': operationId,
+ 'command': {
+ 'type': 'lead.start',
+ 'projectId': project.id,
+ 'machineId': machine.id,
+ 'engine': machine.engine,
+ if (url is String && url.isNotEmpty) 'repositoryUrl': url,
+ },
+ },
+ );
+ _leadStarts.remove(machine.id);
+ unawaited(reader.refresh());
+ } on SuperTabFailure catch (failure) {
+ // Refused, it made no start: the next try is a new one.
+ final status = failure.statusCode;
+ if (status >= 400 && status < 500 && status != 408 && status != 429) {
+ _leadStarts.remove(machine.id);
+ }
+ if (mounted) setState(() => _leadError = failure.message);
+ } catch (_) {
+ if (mounted) {
+ setState(
+ () => _leadError = 'Couldn’t start the Lead. Try again to check it.',
+ );
+ }
+ } finally {
+ if (mounted) setState(() => _startingLead = false);
+ }
+ }
+
/// The desktop's "Couldn't confirm delivery": its computer may have typed
/// it without confirming, so the person checks before it goes again. Open
/// terminal only where this phone can open that computer's terminals.
@@ -255,7 +385,7 @@ class _SwarmMessageReceiptState extends State<SwarmMessageReceipt>
required IconData icon,
required Color color,
required String title,
- required String note,
+ String? note,
List<Widget> actions = const [],
}) {
return Padding(
@@ -275,28 +405,29 @@ class _SwarmMessageReceiptState extends State<SwarmMessageReceipt>
],
),
),
- Padding(
- padding: const EdgeInsets.only(top: AppSpace.xs),
- child: DecoratedBox(
- decoration: BoxDecoration(
- color: color.withValues(alpha: .09),
- borderRadius: BorderRadius.circular(AppCard.insetRadius),
- ),
- child: Padding(
- padding: const EdgeInsets.all(AppSpace.s),
- child: SizedBox(
- width: double.infinity,
- child: Text(
- note,
- style: AppType.caption(
- color: AppPalette.textSecondary,
- height: 1.45,
+ if (note != null)
+ Padding(
+ padding: const EdgeInsets.only(top: AppSpace.xs),
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ color: color.withValues(alpha: .09),
+ borderRadius: BorderRadius.circular(AppCard.insetRadius),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.all(AppSpace.s),
+ child: SizedBox(
+ width: double.infinity,
+ child: Text(
+ note,
+ style: AppType.caption(
+ color: AppPalette.textSecondary,
+ height: 1.45,
+ ),
),
),
),
),
),
- ),
// Each link's own padding sets it in from the note's edge: the
// first is pulled back to line up with it.
if (actions.isNotEmpty)
diff --git a/mobile/lib/swarm/swarm_need_rows.dart b/mobile/lib/swarm/swarm_need_rows.dart
index c025a27d9..e5afe80c7 100644
--- a/mobile/lib/swarm/swarm_need_rows.dart
+++ b/mobile/lib/swarm/swarm_need_rows.dart
@@ -8,6 +8,7 @@ import '../shared/theme/app_space.dart';
import '../shared/theme/app_theme.dart';
import '../shared/theme/app_type.dart';
import '../theme/app_theme.dart' show AppColors;
+import 'model.dart' show kDefaultCoordinatorName;
import 'swarm_asks.dart';
import 'swarm_inbox.dart';
import 'swarm_row.dart';
@@ -158,6 +159,7 @@ class SwarmNeedLine extends StatelessWidget {
final SwarmDecisionNeed decision => switch (session.held(decision)) {
final choice? =>
'Sending “${swarmOption(decision.decision.options, choice)}”',
+ null when session.heldDelegate(decision) => 'Leaving it to be decided',
null => decision.decision.question,
},
SwarmMentionNeed(:final mention) =>
@@ -335,12 +337,16 @@ class SwarmDecisionAnswer extends StatelessWidget {
required this.session,
required this.need,
this.fillRecommended = false,
+ this.onNotNow,
});
final SwarmSession session;
final SwarmDecisionNeed need;
final bool fillRecommended;
+ /// Sets it aside where it shows: in the Buddy chat alone, as on the desktop.
+ final VoidCallback? onNotNow;
+
@override
Widget build(BuildContext context) {
AppTheme.watch(context);
@@ -349,8 +355,26 @@ class SwarmDecisionAnswer extends StatelessWidget {
final held = session.held(need);
final sending = asks?.answering.contains(decision.id) ?? false;
final note = AppType.caption(color: AppColors.warning, height: 1.35);
+ final coordinator =
+ session.inbox
+ .reader(need.swarmId)
+ ?.snapshot
+ ?.coordinatorNameOf(decision.projectId) ??
+ kDefaultCoordinatorName;
final Widget actions;
- if (held != null) {
+ if (session.heldDelegate(need)) {
+ actions = _Held(
+ key: ValueKey('swarm-held-box-${decision.id}-delegate'),
+ label: 'Leaving it to $coordinator',
+ window: session.undoWindow,
+ action: SwarmButton(
+ key: ValueKey('swarm-undo-${decision.id}'),
+ label: 'Undo',
+ style: SwarmButtonStyle.link,
+ onPressed: () => session.undo(need),
+ ),
+ );
+ } else if (held != null) {
actions = _Held(
key: ValueKey('swarm-held-box-${decision.id}-$held'),
label: 'Sending “${swarmOption(decision.options, held)}”',
@@ -365,6 +389,17 @@ class SwarmDecisionAnswer extends StatelessWidget {
);
} else if (sending) {
actions = const _Held(label: 'Sending…');
+ } else if (asks?.unconfirmedDelegate(decision) ?? false) {
+ // Sent, and maybe taken: only the same delegation may go again.
+ actions = _Held(
+ label: 'Leaving it to $coordinator is not confirmed.',
+ action: SwarmButton(
+ key: ValueKey('swarm-resend-${decision.id}'),
+ label: 'Send again',
+ style: SwarmButtonStyle.link,
+ onPressed: () => unawaited(asks!.delegate(decision)),
+ ),
+ );
} else if (asks?.unconfirmed(decision) case final choice?) {
// Sent, and maybe taken: only the same answer may go again.
actions = _Held(
@@ -394,6 +429,33 @@ class SwarmDecisionAnswer extends StatelessWidget {
keyOf: (index) => ValueKey('swarm-option-${decision.id}-$index'),
onTap: (index) => session.hold(need, index),
),
+ if (decision.canDelegate || onNotNow != null) ...[
+ const SizedBox(height: 4),
+ Wrap(
+ crossAxisAlignment: WrapCrossAlignment.center,
+ children: [
+ if (decision.canDelegate)
+ SwarmButton(
+ key: ValueKey('swarm-decision-delegate-${decision.id}'),
+ label: 'Let $coordinator decide',
+ style: SwarmButtonStyle.link,
+ onPressed: () => session.holdDelegate(need),
+ ),
+ if (decision.canDelegate && onNotNow != null)
+ Text(
+ '·',
+ style: AppType.caption(color: AppPalette.textSecondary),
+ ),
+ if (onNotNow case final notNow?)
+ SwarmButton(
+ key: ValueKey('swarm-decision-later-${decision.id}'),
+ label: 'Not now',
+ style: SwarmButtonStyle.link,
+ onPressed: notNow,
+ ),
+ ],
+ ),
+ ],
],
);
}
diff --git a/mobile/lib/swarm/swarm_outbox.dart b/mobile/lib/swarm/swarm_outbox.dart
index c04564cbb..49853c423 100644
--- a/mobile/lib/swarm/swarm_outbox.dart
+++ b/mobile/lib/swarm/swarm_outbox.dart
@@ -78,6 +78,34 @@ class SwarmPost {
/// [SwarmOutbox.onTaken] was told.
bool _told = false;
+ /// What the phone keeps of it across a restart: what it sends, and the
+ /// message that would show it arrived.
+ Map<String, dynamic> get kept => {'body': body, 'messageId': messageId};
+
+ /// A post kept from before a restart, or none: nobody knows whether it got
+ /// there, so it says Not sent, and Retry goes under its own receipt.
+ static SwarmPost? fromKept(
+ Map<String, dynamic> row,
+ Object? Function(String) held,
+ ) {
+ if (row case {
+ 'body': {
+ 'operationId': final String _,
+ 'command': {'text': final String text},
+ },
+ 'messageId': final String messageId,
+ }) {
+ return SwarmPost(
+ body: row['body'] as Map<String, dynamic>,
+ messageId: messageId,
+ held: held(text),
+ )
+ ..state = SwarmPostState.unconfirmed
+ ..error = 'Your message was not sent. Retry to check it.';
+ }
+ return null;
+ }
+
String get operationId => body['operationId'] as String;
Map<String, dynamic> get command => body['command'] as Map<String, dynamic>;
String get text => command['text'] as String;
@@ -158,6 +186,19 @@ class SwarmOutbox {
return deliver(post);
}
+ /// [posts], kept from before a restart, back in the list: sent only by Retry.
+ void restore(Iterable<SwarmPost> posts) {
+ if (_closed) return;
+ _posts.addAll(posts);
+ onChanged();
+ }
+
+ /// [post] goes for good, and an answer still to come changes nothing: Delete.
+ void remove(SwarmPost post) {
+ post._timer?.cancel();
+ if (_posts.remove(post)) onChanged();
+ }
+
/// Sends [post] — again, when it is [SwarmPostState.unconfirmed] — under
/// its own receipt, so the backend posts it once however often it goes.
Future<SwarmPostOutcome> deliver(SwarmPost post) {
diff --git a/mobile/lib/swarm/swarm_post_line.dart b/mobile/lib/swarm/swarm_post_line.dart
index a806e2b3a..c68b96395 100644
--- a/mobile/lib/swarm/swarm_post_line.dart
+++ b/mobile/lib/swarm/swarm_post_line.dart
@@ -11,18 +11,23 @@ import 'swarm_message_row.dart' show swarmChatText;
const _finger = 44.0;
/// The line under the person's post on its way, as Slack shows it (Dee,
-/// 10-29): "Sending…", then — its answer lost — "Not sent · Retry". A post
+/// 10-29): "Sending…", then — its answer lost — "Not sent · Retry · Delete". A post
/// that arrived carries no line.
class SwarmPostLine extends StatelessWidget {
const SwarmPostLine({
super.key,
required this.sending,
required this.onRetry,
+ required this.onDelete,
});
final bool sending;
final VoidCallback onRetry;
+ /// Takes it away, Not sent: it may still have arrived, and then it shows when
+ /// the chat is next read.
+ final VoidCallback onDelete;
+
@override
Widget build(BuildContext context) {
final tty = Tty.of(context);
@@ -40,33 +45,50 @@ class SwarmPostLine extends StatelessWidget {
const SizedBox(width: AppSpace.xs),
Text(sending ? 'Sending…' : 'Not sent', style: style),
if (!sending) ...[
- Text(' · ', style: style),
- Semantics(
- button: true,
- label: 'Retry',
- excludeSemantics: true,
- child: GestureDetector(
- key: const ValueKey('swarm-resend-post'),
- behavior: HitTestBehavior.opaque,
- onTap: onRetry,
- child: ConstrainedBox(
- constraints: const BoxConstraints(
- minHeight: _finger,
- minWidth: _finger,
- ),
- child: Center(
- widthFactor: 1,
- child: Text(
- 'Retry',
- style: swarmChatText(14, color: tty.blue),
- ),
- ),
- ),
- ),
+ const SizedBox(width: AppSpace.xs),
+ Text('·', style: style),
+ _action(
+ 'Retry',
+ const ValueKey('swarm-resend-post'),
+ tty.blue,
+ onRetry,
+ ),
+ Text('·', style: style),
+ _action(
+ 'Delete',
+ const ValueKey('swarm-delete-post'),
+ tty.blue,
+ onDelete,
),
],
],
),
);
}
+
+ Widget _action(String label, Key key, Color color, VoidCallback onTap) =>
+ Semantics(
+ button: true,
+ label: label,
+ excludeSemantics: true,
+ child: GestureDetector(
+ key: key,
+ behavior: HitTestBehavior.opaque,
+ onTap: onTap,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(
+ minHeight: _finger,
+ minWidth: _finger,
+ ),
+ child: Center(
+ widthFactor: 1,
+ // Even on both sides, and wide enough for a finger.
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.xs),
+ child: Text(label, style: swarmChatText(14, color: color)),
+ ),
+ ),
+ ),
+ ),
+ );
}
diff --git a/mobile/lib/swarm/swarm_profile_sheet.dart b/mobile/lib/swarm/swarm_profile_sheet.dart
index 9e4a175ae..205409373 100644
--- a/mobile/lib/swarm/swarm_profile_sheet.dart
+++ b/mobile/lib/swarm/swarm_profile_sheet.dart
@@ -13,7 +13,6 @@ import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/shared/theme/app_type.dart';
import 'package:harness_mobile/theme/app_theme.dart' show AppColors;
-import 'identity.dart';
import 'model.dart';
import 'swarm_face.dart';
import 'swarm_profile.dart';
@@ -280,7 +279,7 @@ class _SwarmProfileSheetState extends State<SwarmProfileSheet> {
SuperTabPersonStatus? status,
SwarmProfile profile,
) {
- final name = superTabPersonName(me.email);
+ final name = me.username;
final edit = profile.canEdit && !_busy;
final current = me.avatar;
final text = _text.text.trim();
@@ -702,7 +701,7 @@ class SwarmPersonSheet extends StatelessWidget {
Widget _sheet(BuildContext context, SwarmReader reader) {
final person = reader.snapshot?.person(personId);
final mine = personId == reader.accountId;
- final name = person == null ? 'Someone' : superTabPersonName(person.email);
+ final name = person == null ? 'Someone' : person.username;
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
diff --git a/mobile/lib/swarm/swarm_project_tasks.dart b/mobile/lib/swarm/swarm_project_tasks.dart
index 279f478d2..5ddd88681 100644
--- a/mobile/lib/swarm/swarm_project_tasks.dart
+++ b/mobile/lib/swarm/swarm_project_tasks.dart
@@ -424,6 +424,17 @@ class SwarmWaitingRow extends StatelessWidget {
if (need is! SwarmDecisionNeed) return (null, reply);
final decision = need.decision;
final asks = session.inbox.asks(need.swarmId);
+ if (session.heldDelegate(need)) {
+ return (
+ 'Leaving it to be decided',
+ SwarmButton(
+ key: ValueKey('swarm-undo-${decision.id}'),
+ label: 'Undo',
+ style: SwarmButtonStyle.link,
+ onPressed: () => session.undo(need),
+ ),
+ );
+ }
if (session.held(need) case final held?) {
return (
'Sending “${swarmOption(decision.options, held)}”',
@@ -450,6 +461,7 @@ class SwarmWaitingRow extends StatelessWidget {
// Sent and not confirmed, or a recommendation the decision does not
// offer: its chat says what can be done.
if (asks?.unconfirmed(decision) != null ||
+ (asks?.unconfirmedDelegate(decision) ?? false) ||
decision.recommended < 0 ||
decision.recommended >= decision.options.length) {
return (null, reply);
diff --git a/mobile/lib/swarm/swarm_reader.dart b/mobile/lib/swarm/swarm_reader.dart
index c5926c38d..febe3b2f4 100644
--- a/mobile/lib/swarm/swarm_reader.dart
+++ b/mobile/lib/swarm/swarm_reader.dart
@@ -9,6 +9,7 @@ import 'model.dart';
import 'parts.dart';
import 'swarm_buddy.dart';
import 'swarm_chat_notify.dart';
+import 'swarm_kept.dart';
import 'swarm_read_marks.dart';
import 'swarm_request.dart';
import 'waiting_work.dart';
@@ -107,6 +108,10 @@ class SwarmReader extends ChangeNotifier {
/// null where nobody keeps them, and nothing reads as unread.
SwarmReadMarks? readMarks;
+ /// The account's drafts and unsent posts, which its inbox keeps; null where
+ /// nobody keeps them, and each chat holds its own while it is open.
+ SwarmKept? kept;
+
/// What the last read could not do, as a sentence; null once one succeeds.
String? error;
diff --git a/mobile/lib/swarm/swarm_session.dart b/mobile/lib/swarm/swarm_session.dart
index ac1e863d5..ee14977ed 100644
--- a/mobile/lib/swarm/swarm_session.dart
+++ b/mobile/lib/swarm/swarm_session.dart
@@ -15,6 +15,7 @@ import 'swarm_face.dart';
import 'swarm_home_cache.dart';
import 'swarm_home_prefs.dart';
import 'swarm_inbox.dart';
+import 'swarm_kept.dart';
import 'swarm_mark_all.dart';
import 'swarm_notices.dart';
import 'swarm_profile.dart';
@@ -38,6 +39,7 @@ class SwarmSession extends ChangeNotifier {
this.markAllHold = swarmMarkAllHold,
SwarmHomeCache? homeCache,
LocalKeyValueStore? readMarks,
+ SwarmKeptStore? kept,
SwarmTold? told,
}) : inbox = SwarmInbox(
accountId: accountId,
@@ -46,6 +48,7 @@ class SwarmSession extends ChangeNotifier {
pollInterval: pollInterval,
homeCache: homeCache,
readMarks: readMarks,
+ keptStore: kept,
),
home = SwarmHomePrefs(accountId: accountId, store: readMarks) {
_announcer = SwarmAnnouncer(
@@ -122,7 +125,7 @@ class SwarmSession extends ChangeNotifier {
late final SwarmChatNotices _chatNotices;
int _screens = 0;
final _watching = <String, int>{};
- final _held = <String, ({int choice, Timer timer})>{};
+ final _held = <String, ({int? choice, Timer timer})>{};
/// Needs whose held answer was dropped unsent: their card says so until
/// another answer is held.
@@ -133,7 +136,11 @@ class SwarmSession extends ChangeNotifier {
/// watches every few seconds. Behind, nothing is. Going behind sends a
/// held Mark all read at once: the app may not come back to send it.
set foreground(bool value) {
- if (!value) _markAll?.commit();
+ if (!value) {
+ _markAll?.commit();
+ // The app going behind may be its last moment.
+ unawaited(inbox.kept.flush());
+ }
_foreground = value;
inbox.shown = value;
_show();
@@ -207,13 +214,28 @@ class SwarmSession extends ChangeNotifier {
/// The option held for [need], while its Undo window runs.
int? held(SwarmDecisionNeed need) => _held[need.key]?.choice;
+ /// Whether anything is held for [need]: an answer, or leaving it.
+ bool holding(SwarmDecisionNeed need) => _held.containsKey(need.key);
+
+ /// [need] is held to be left to its coordinator, while its Undo window runs.
+ bool heldDelegate(SwarmDecisionNeed need) {
+ final held = _held[need.key];
+ return held != null && held.choice == null;
+ }
+
/// [need]'s held answer was dropped before it was sent: it left the list
/// meanwhile (the Swarm read again in full) and came back.
bool dropped(SwarmDecisionNeed need) => _dropped.contains(need.key);
/// Answers [need] with option [choice] once [undoWindow] has passed,
/// unless [undo] takes it back first.
- void hold(SwarmDecisionNeed need, int choice) {
+ void hold(SwarmDecisionNeed need, int choice) => _hold(need, choice);
+
+ /// Leaves [need] to its coordinator once [undoWindow] has passed, unless
+ /// [undo] takes it back first, as an answer is held.
+ void holdDelegate(SwarmDecisionNeed need) => _hold(need, null);
+
+ void _hold(SwarmDecisionNeed need, int? choice) {
if (_disposed) return;
// Off the list since it was asked (answered elsewhere, or access taken
// away): there is nothing to answer.
@@ -240,10 +262,15 @@ class SwarmSession extends ChangeNotifier {
}
}
- void _send(SwarmDecisionNeed need, int choice) {
+ void _send(SwarmDecisionNeed need, int? choice) {
if (_disposed) return;
notifyListeners();
- unawaited(inbox.asks(need.swarmId)?.answer(need.decision, choice));
+ final asks = inbox.asks(need.swarmId);
+ unawaited(
+ choice == null
+ ? asks?.delegate(need.decision)
+ : asks?.answer(need.decision, choice),
+ );
}
void _needsChanged() {
@@ -315,18 +342,24 @@ class SwarmHost extends ChangeNotifier {
this.computers,
SwarmHomeCache? homeCache,
LocalKeyValueStore? readMarks,
+ SwarmKeptStore? kept,
this.uploadAvatar,
this.voice,
this.dictation,
}) : features = features ?? experimentalFeaturesStore,
homeCache = homeCache ?? SwarmHomeCache.device(),
- readMarks = readMarks ?? HarnessFileStore.shared {
+ readMarks = readMarks ?? HarnessFileStore.shared,
+ kept = kept ?? SealedSwarmKeptStore.device() {
account.addListener(_update);
this.features.addListener(_update);
computers?.addListener(_computersChanged);
_update();
}
+ /// Where the session's drafts and unsent posts are kept, sealed; cleared when
+ /// the account leaves or Swarm is turned off, not while it is being read.
+ final SwarmKeptStore kept;
+
/// The signed-in account's id; null while nobody is.
final String? Function() accountId;
@@ -413,7 +446,10 @@ class SwarmHost extends ChangeNotifier {
// Swarm off with no session to end: its switch is read before the first
// frame, so this is known, and what an earlier run kept goes. A missing
// account is not: the signed-in shell is up before the account is read.
- if (!on && wasOn != false) unawaited(homeCache.clear());
+ if (!on && wasOn != false) {
+ unawaited(homeCache.clear());
+ unawaited(kept.clear());
+ }
// No session either way, but [accountComing] may have moved with it.
if (wasOn != null && on != wasOn) notifyListeners();
return;
@@ -423,7 +459,14 @@ class SwarmHost extends ChangeNotifier {
unawaited(homeCache.clear());
swarmForgetAvatarImages();
}
+ final hadSession = session != null;
+ // What it was still writing goes first: the clear comes after it.
session?.dispose();
+ // The same account still being read is no leaving: what it wrote waits.
+ if (hadSession &&
+ (!on || id != null || !(accountReading?.call() ?? false))) {
+ unawaited(kept.clear());
+ }
session = id == null
? null
: (SwarmSession(
@@ -433,6 +476,7 @@ class SwarmHost extends ChangeNotifier {
notices: notices,
homeCache: homeCache,
readMarks: readMarks,
+ kept: kept,
told: _told,
)..foreground = _foreground);
notifyListeners();
diff --git a/mobile/lib/swarm/swarm_ship_row.dart b/mobile/lib/swarm/swarm_ship_row.dart
index 191de1cab..9e76a9b4e 100644
--- a/mobile/lib/swarm/swarm_ship_row.dart
+++ b/mobile/lib/swarm/swarm_ship_row.dart
@@ -11,7 +11,6 @@ import 'package:harness_mobile/shared/theme/app_space.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/shared/theme/swarm_tokens_set_b.dart';
-import 'identity.dart';
import 'model.dart';
import 'swarm_message_row.dart';
import 'swarm_session.dart';
@@ -160,7 +159,7 @@ class _SwarmShipRowState extends State<SwarmShipRow> {
];
final credits = [
if (requester != null)
- ('Requested by', [(requester.id, superTabPersonName(requester.email))]),
+ ('Requested by', [(requester.id, requester.username)]),
('Built by', agents(ship.builderIds)),
('Reviewed by', agents(ship.reviewerIds)),
].where((credit) => credit.$2.isNotEmpty).toList();
diff --git a/mobile/lib/swarm/swarm_task_status.dart b/mobile/lib/swarm/swarm_task_status.dart
index a8ce45ddc..7bdb8257d 100644
--- a/mobile/lib/swarm/swarm_task_status.dart
+++ b/mobile/lib/swarm/swarm_task_status.dart
@@ -8,7 +8,6 @@ import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/shared/theme/app_type.dart';
import 'package:harness_mobile/theme/app_theme.dart' show AppColors;
-import 'identity.dart';
import 'model.dart';
/// A person of [snapshot] as the Swarm names them, for a task's "Waiting on
@@ -20,9 +19,7 @@ String? Function(String personId) swarmTaskPersonName(
) =>
(personId) =>
switch (snapshot.people.where((p) => p.id == personId).firstOrNull) {
- final person? when person.email.isNotEmpty => superTabPersonName(
- person.email,
- ),
+ final person? when person.email.isNotEmpty => person.username,
_ => null,
};
diff --git a/mobile/lib/swarm/swarm_thread.dart b/mobile/lib/swarm/swarm_thread.dart
index d9e5fcd8e..dc33c5bcd 100644
--- a/mobile/lib/swarm/swarm_thread.dart
+++ b/mobile/lib/swarm/swarm_thread.dart
@@ -56,6 +56,36 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {
chat.addListener(_chatChanged);
reader.addListener(_chatChanged);
files.addListener(_filesChanged);
+ final posts = [
+ for (final row
+ in reader.kept?.posts(reader.tabId, chat.id, root) ?? const [])
+ ?SwarmPost.fromKept(row, _heldOf),
+ ];
+ if (posts.isNotEmpty) _outbox.restore(posts);
+ }
+
+ /// What a kept reply puts back in the box if it is refused: only its words.
+ static Object? _heldOf(String text) =>
+ (draft: text, alsoSend: false, newSession: false);
+
+ void _keepPosts() {
+ if (_disposed) return;
+ reader.kept?.setPosts(reader.tabId, chat.id, root, [
+ for (final post in _outbox.posts)
+ if (post.state != SwarmPostState.confirmed) post.kept,
+ ]);
+ }
+
+ /// Takes [post], Not sent, away for good: Delete. It may still have arrived,
+ /// and then it shows when the thread is next read.
+ void deletePost(SwarmPost post) {
+ if (_disposed || post.state != SwarmPostState.unconfirmed) return;
+ _uploads.forget(post.files);
+ _outbox.remove(post);
+ if (error != null && error == _postError && _outbox.unconfirmed == null) {
+ error = null;
+ _tell();
+ }
}
final SwarmConversation chat;
@@ -311,6 +341,7 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {
path: '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}/commands',
timeout: chat.sendTimeout,
onChanged: () {
+ _keepPosts();
if (!_disposed) _tell();
},
onTaken: (post) {
@@ -433,7 +464,10 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {
/// A reply read back shows as its row, once, no longer on its way —
/// whatever its answer, which may still be coming.
void _settle() {
- if (_outbox.settle(messages)) _composer.changed();
+ if (_outbox.settle(messages)) {
+ _keepPosts();
+ _composer.changed();
+ }
}
/// Reads the thread: from its newest reply back through [pagesOnOpen]
diff --git a/mobile/lib/swarm/swarm_thread_line.dart b/mobile/lib/swarm/swarm_thread_line.dart
index ad400c212..e0edfdbe9 100644
--- a/mobile/lib/swarm/swarm_thread_line.dart
+++ b/mobile/lib/swarm/swarm_thread_line.dart
@@ -30,7 +30,7 @@ typedef SwarmThreadFace = ({
});
/// The newest reply authors of [thread] as [snapshot] names and dresses them:
-/// an agent by the Swarm's name for it, a person by their address's first
+/// an agent by the Swarm's name for it, a person by their username,
/// part, as the chat names a message's author. The project's coordinator
/// wears manager blue here as on its own messages, whatever its role is
/// called.
@@ -57,7 +57,12 @@ List<SwarmThreadFace> swarmThreadFaces(
look: snapshot?.agentLook(id) ?? (picture: null, status: null),
)
: (
- name: superTabPersonName(author['name'] as String? ?? ''),
+ name:
+ snapshot?.people
+ .where((p) => p.id == id)
+ .firstOrNull
+ ?.username ??
+ superTabPersonName(author['name'] as String? ?? ''),
id: id,
agent: false,
pm: false,
diff --git a/mobile/lib/swarm/swarm_work_details_page.dart b/mobile/lib/swarm/swarm_work_details_page.dart
new file mode 100644
index 000000000..80066a0e1
--- /dev/null
+++ b/mobile/lib/swarm/swarm_work_details_page.dart
@@ -0,0 +1,227 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+
+import 'package:harness_mobile/phone/phone_navigation.dart';
+import 'package:harness_mobile/phone/tty.dart';
+import 'package:harness_mobile/shared/theme/app_space.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+
+import 'linked_tasks.dart';
+import 'model.dart';
+import 'swarm_code_block.dart';
+import 'swarm_message_row.dart' show swarmChatText;
+import 'swarm_reader.dart';
+import 'swarm_style.dart';
+
+/// Whether chat [chatId] has Work details, where Desktop's chat menu offers
+/// them (`view.dart` `_options`): a chat of a project's work, never the
+/// project's own chat (whose menu is its project's), a Buddy chat, or a private
+/// conversation, which is chat only. False once the chat can no longer be read.
+bool swarmHasWorkDetails(SwarmReader reader, String chatId) {
+ final snapshot = reader.snapshot;
+ if (reader.accessRevoked || snapshot == null) return false;
+ final chat = snapshot.conversation(chatId);
+ return chat != null &&
+ !snapshot.isProjectLead(chatId) &&
+ !chat.isBuddyChat &&
+ !reader.buddies.chatOwners.containsKey(chatId) &&
+ chat.audience == null;
+}
+
+/// Opens chat [chatId]'s Work details over [context]'s page.
+void openSwarmWorkDetails(
+ BuildContext context, {
+ required SwarmReader reader,
+ required String chatId,
+}) => unawaited(
+ Navigator.of(context).push(
+ phoneRoute((_) => SwarmWorkDetailsPage(reader: reader, chatId: chatId)),
+ ),
+);
+
+/// A task's Work details, read only (Tony's mobile list, task 31; desktop
+/// `work_details.dart`): its brief as written, its linked steps, who has it,
+/// each acceptance check with its evidence, and the result. Desktop's words
+/// and order, without Record check: the phone records nothing. It reads only
+/// what the Swarm read holds, follows it, and goes once the chat can no longer
+/// be read: access lost, signed out, or the chat gone.
+class SwarmWorkDetailsPage extends StatefulWidget {
+ const SwarmWorkDetailsPage({
+ super.key,
+ required this.reader,
+ required this.chatId,
+ });
+
+ final SwarmReader reader;
+ final String chatId;
+
+ @override
+ State<SwarmWorkDetailsPage> createState() => _SwarmWorkDetailsPageState();
+}
+
+class _SwarmWorkDetailsPageState extends State<SwarmWorkDetailsPage> {
+ bool _leaving = false;
+
+ SuperTabConversation? get _chat => widget.reader.accessRevoked
+ ? null
+ : widget.reader.snapshot?.conversation(widget.chatId);
+
+ @override
+ void initState() {
+ super.initState();
+ widget.reader.addListener(_changed);
+ }
+
+ @override
+ void didUpdateWidget(SwarmWorkDetailsPage old) {
+ super.didUpdateWidget(old);
+ if (old.reader == widget.reader) return;
+ old.reader.removeListener(_changed);
+ widget.reader.addListener(_changed);
+ }
+
+ @override
+ void dispose() {
+ widget.reader.removeListener(_changed);
+ super.dispose();
+ }
+
+ void _changed() {
+ if (!mounted) return;
+ if (_chat == null) {
+ _leave();
+ } else {
+ setState(() {});
+ }
+ }
+
+ /// Takes the page down once this frame is done: a page whose chat went may
+ /// not change the navigator while it builds.
+ void _leave() {
+ if (_leaving) return;
+ _leaving = true;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted) return;
+ final route = ModalRoute.of(context);
+ if (route != null && route.isActive) route.navigator?.removeRoute(route);
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final chat = _chat;
+ if (chat == null) _leave();
+ return Scaffold(
+ backgroundColor: AppPalette.windowBg,
+ body: SafeArea(
+ bottom: false,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ SwarmTopBar(
+ leading: SwarmBackButton(
+ onPressed: () => Navigator.of(context).maybePop(),
+ ),
+ title: 'Work details',
+ subtitle: chat?.label,
+ ),
+ Expanded(
+ child: chat == null
+ ? const SizedBox.shrink()
+ : _body(context, chat),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ Widget _body(BuildContext context, SuperTabConversation chat) {
+ final snapshot = widget.reader.snapshot!;
+ final quiet = Tty.of(context)
+ .style(color: AppPalette.textFaint, size: 12.5);
+ final assignment = chat.assignment;
+ final linked = superTabLinkedLine(snapshot, chat);
+ Widget text(String value, {Key? key, Color? color}) => Padding(
+ key: key,
+ padding: const EdgeInsets.only(bottom: AppSpace.s),
+ child: Text(value, style: swarmChatText(15, color: color)),
+ );
+ // Code fenced in a brief or evidence reads as code, as in the chat.
+ List<Widget> written(String value) => [
+ for (final part in swarmTextParts(value))
+ if (part.code)
+ SwarmCodeBlock(code: part.text, name: part.name)
+ else
+ text(part.text),
+ ];
+ return SelectionArea(
+ child: ListView(
+ key: const ValueKey('swarm-work-details'),
+ padding: EdgeInsets.fromLTRB(
+ AppSpace.m,
+ AppSpace.xs,
+ AppSpace.m,
+ MediaQuery.paddingOf(context).bottom + AppSpace.xl,
+ ),
+ children: [
+ // The brief as written (the backend writes a task's from its parts),
+ // never parts of a fixed shape.
+ if (chat.brief.isNotEmpty)
+ ...written(chat.brief)
+ else
+ text(
+ 'This task has no description yet.',
+ color: AppPalette.textSecondary,
+ ),
+ if (linked != null) ...[
+ const SizedBox(height: AppSpace.s),
+ text(linked),
+ ],
+ if (assignment != null) ...[
+ const SizedBox(height: AppSpace.s),
+ text(
+ '${_agentName(snapshot, assignment['agentId'])} · '
+ '${superTabWorkStatusLabel(assignment['status'] as String? ?? '')}',
+ ),
+ ],
+ if (chat.checks.isNotEmpty) const SwarmCaption('Acceptance checks'),
+ for (final check in chat.checks)
+ Padding(
+ key: ValueKey('swarm-work-check-${check['id']}'),
+ padding: const EdgeInsets.only(bottom: AppSpace.m),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ check['description'] as String? ?? '',
+ style: swarmChatText(15)
+ .copyWith(fontWeight: FontWeight.w600),
+ ),
+ const SizedBox(height: 2),
+ if (check['evidence'] case final String evidence)
+ ...written(evidence),
+ Text(
+ check['passedBy'] == null ? 'Not verified' : 'Verified',
+ style: quiet,
+ ),
+ ],
+ ),
+ ),
+ if (assignment?['result'] case final String result) ...[
+ const SwarmCaption('Result'),
+ ...written(result),
+ ],
+ ],
+ ),
+ );
+ }
+}
+
+/// The agent's name as the read gives it, as Desktop words one it no longer has.
+String _agentName(SuperTabSnapshot snapshot, Object? agentId) =>
+ agentId is String && snapshot.agent(agentId) != null
+ ? snapshot.agentName(agentId)
+ : 'Agent unavailable';
diff --git a/mobile/lib/swarm/swarm_you_page.dart b/mobile/lib/swarm/swarm_you_page.dart
index 1b89b034d..caa9fd63d 100644
--- a/mobile/lib/swarm/swarm_you_page.dart
+++ b/mobile/lib/swarm/swarm_you_page.dart
@@ -12,7 +12,6 @@ import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/shared/theme/app_type.dart';
import 'package:harness_mobile/theme/app_theme.dart' show AppColors;
-import 'identity.dart';
import 'model.dart';
import 'swarm_devices_page.dart';
import 'swarm_face.dart';
@@ -232,9 +231,7 @@ class _Me extends StatelessWidget {
AppTheme.watch(context);
final me = this.me;
// A Home kept for a cold start holds no email.
- final name = me == null || me.email.isEmpty
- ? 'You'
- : superTabPersonName(me.email);
+ final name = me == null || me.email.isEmpty ? 'You' : me.username;
return Padding(
padding: const EdgeInsets.fromLTRB(
AppSpace.xs,
diff --git a/mobile/test/swarm/swarm_activity_page_test.dart b/mobile/test/swarm/swarm_activity_page_test.dart
index 24d6589e9..a6888204e 100644
--- a/mobile/test/swarm/swarm_activity_page_test.dart
+++ b/mobile/test/swarm/swarm_activity_page_test.dart
@@ -123,6 +123,94 @@ void main() {
}
});
+ // Tony's phone list, task 26, as Desktop's decisions_view.dart.
+ group('Answered', () {
+ Map<String, dynamic> settled(
+ String id,
+ int minute, {
+ bool delegated = false,
+ }) => {
+ 'id': id,
+ 'projectId': 'lead',
+ 'projectName': 'Mobile',
+ 'conversationId': leadChat,
+ 'conversationTitle': 'Lead',
+ 'askerName': 'River',
+ 'question': 'Question $id?',
+ 'options': ['Merge', 'Wait'],
+ 'recommended': 0,
+ 'choice': 0,
+ if (delegated) 'delegated': true,
+ 'createdAt': DateTime.utc(2026, 10, 29, 1, minute).toIso8601String(),
+ };
+
+ testWidgets('lists the newest 5, the coordinator\'s answer never as the '
+ 'person\'s own', (tester) async {
+ final fake = activityBackend();
+ fake.routes['/api/super-tabs/$tab/decisions?state=settled'] = (_) => {
+ 'decisions': [
+ settled('a1', 1),
+ settled('a2', 2, delegated: true),
+ settled('a3', 3),
+ settled('a4', 4),
+ settled('a5', 5),
+ settled('a6', 6),
+ ],
+ };
+ await pump(tester, fake);
+ await tester.scrollUntilVisible(
+ key('swarm-answered'),
+ 200,
+ scrollable: find
+ .descendant(
+ of: find.byType(ListView).last,
+ matching: find.byType(Scrollable),
+ )
+ .first,
+ );
+ expect(find.text('Answered'), findsOneWidget);
+ expect(
+ find.text('Question a1?'),
+ findsNothing,
+ reason: 'the oldest of 6',
+ );
+ expect(find.text('Question a6?'), findsOneWidget);
+ expect(find.text('You chose: Merge'), findsNWidgets(4));
+ expect(find.text('Product Manager decided: Merge'), findsOneWidget);
+ });
+
+ testWidgets('says when it could not be read, and reads again on asking', (
+ tester,
+ ) async {
+ final fake = activityBackend();
+ var down = true;
+ fake.routes['/api/super-tabs/$tab/decisions?state=settled'] = (_) {
+ if (down) throw StateError('Offline');
+ return {
+ 'decisions': [settled('a1', 1)],
+ };
+ };
+ await pump(tester, fake);
+ expect(
+ find.text('Could not load answered decisions. Try again.'),
+ findsOneWidget,
+ );
+ down = false;
+ await tester.tap(key('swarm-answered-retry'));
+ await tester.pumpAndSettle();
+ expect(find.text('You chose: Merge'), findsOneWidget);
+ });
+
+ testWidgets('shows nothing with none answered', (tester) async {
+ final fake = activityBackend();
+ fake.routes['/api/super-tabs/$tab/decisions?state=settled'] = (_) => {
+ 'decisions': <Object>[],
+ };
+ await pump(tester, fake);
+ expect(find.text('Answered'), findsNothing);
+ });
+ });
+
testWidgets('Approve asks first, naming the option; Cancel sends nothing', (
tester,
) async {
diff --git a/mobile/test/swarm/swarm_asks_test.dart b/mobile/test/swarm/swarm_asks_test.dart
index d372e9f36..06164ddb1 100644
--- a/mobile/test/swarm/swarm_asks_test.dart
+++ b/mobile/test/swarm/swarm_asks_test.dart
@@ -339,6 +339,148 @@ void main() {
},
);
+ // Tony's phone list, task 26, as Desktop's decisions.dart.
+ group('Let the coordinator decide', () {
+ Future<
+ (
+ ({FakeSwarm swarm, SwarmReader reader, SwarmAsks asks}),
+ SuperTabDecision,
+ )
+ >
+ open({Map<String, dynamic> Function(String id)? row}) async {
+ final r = rig(decisions: 1);
+ r.swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {
+ 'decisions': [(row ?? decisionRow)('d1')],
+ };
+ await r.reader.refresh();
+ await settle();
+ return (r, r.asks.decisions.single);
+ }
+
+ test('sends a delegation, with no choice of the person\'s', () async {
+ final (r, decision) = await open();
+ Map<String, dynamic>? command;
+ r.swarm.routes['/api/super-tabs/$tab/commands'] = (body) {
+ command = (body as Map)['command'] as Map<String, dynamic>;
+ return {'ok': true};
+ };
+ expect(await r.asks.delegate(decision), isTrue);
+ expect(command, {
+ 'type': 'decision.answer',
+ 'decisionId': 'd1',
+ 'delegate': true,
+ });
+ });
+
+ test(
+ 'with its reply lost, goes again as the same delegation under the same '
+ 'receipt, never as a choice',
+ () async {
+ final (r, decision) = await open();
+ final bodies = <Map<String, dynamic>>[];
+ var lose = true;
+ r.swarm.routes['/api/super-tabs/$tab/commands'] = (body) {
+ bodies.add(body as Map<String, dynamic>);
+ if (lose) throw StateError('Offline');
+ return {'ok': true};
+ };
+ expect(await r.asks.delegate(decision), isFalse);
+ expect(r.asks.unconfirmedDelegate(decision), isTrue);
+ expect(
+ r.asks.unconfirmed(decision),
+ isNull,
+ reason: 'no option of theirs is waiting',
+ );
+ lose = false;
+ expect(await r.asks.delegate(decision), isTrue);
+ expect(bodies[1]['operationId'], bodies[0]['operationId']);
+ expect(bodies[1]['command'], bodies[0]['command']);
+ },
+ );
+
+ test('is offered only with a recommended option it can take', () async {
+ Map<String, dynamic> row(String id, Object? recommended) => {
+ ...decisionRow(id),
+ 'options': ['A', 'B'],
+ 'recommended': recommended,
+ };
+ expect((await open(row: (id) => row(id, 1))).$2.canDelegate, isTrue);
+ expect((await open(row: (id) => row(id, null))).$2.canDelegate, isFalse);
+ expect((await open(row: (id) => row(id, 2))).$2.canDelegate, isFalse);
+ });
+ });
+
+ group('the answered list', () {
+ Map<String, dynamic> answeredRow(String id, {bool delegated = false}) => {
+ ...decisionRow(id),
+ 'choice': 0,
+ if (delegated) 'delegated': true,
+ };
+
+ test('reads what the coordinator answered too', () async {
+ final r = rig();
+ r.swarm.routes['/api/super-tabs/$tab/decisions?state=settled'] = (_) => {
+ 'decisions': [answeredRow('d1', delegated: true), answeredRow('d2')],
+ };
+ await r.reader.refresh();
+ await r.asks.readAnswered();
+ expect(
+ [for (final d in r.asks.answered) (d.id, d.delegated)],
+ [('d1', true), ('d2', false)],
+ );
+ });
+
+ test('falls back on a backend from before Let PM decide, and shows none '
+ 'from one before decisions', () async {
+ final r = rig();
+ r.swarm.routes['/api/super-tabs/$tab/decisions?state=settled'] = (_) =>
+ throw const SuperTabFailure('BAD', 'Bad.', statusCode: 400);
+ r.swarm.routes['/api/super-tabs/$tab/decisions?state=answered'] = (_) => {
+ 'decisions': [answeredRow('d2')],
+ };
+ await r.reader.refresh();
+ await r.asks.readAnswered();
+ expect(r.asks.answered.single.id, 'd2');
+
+ final none = rig();
+ none.swarm.routes['/api/super-tabs/$tab/decisions?state=settled'] = (_) =>
+ throw const SuperTabFailure(
+ 'NOT_FOUND',
+ 'Not found.',
+ statusCode: 404,
+ );
+ await none.reader.refresh();
+ await none.asks.readAnswered();
+ expect(none.asks.answered, isEmpty);
+ expect(none.asks.answeredError, isNull);
+ });
+
+ test('says when it could not be read', () async {
+ final r = rig();
+ r.swarm.routes['/api/super-tabs/$tab/decisions?state=settled'] = (_) =>
+ throw StateError('Offline');
+ await r.reader.refresh();
+ await r.asks.readAnswered();
+ expect(r.asks.answeredError, isNotNull);
+ });
+
+ test(
+ 'shows nothing read before the Swarm was read again from nothing',
+ () async {
+ final r = rig();
+ r.swarm.routes['/api/super-tabs/$tab/decisions?state=settled'] = (_) =>
+ {
+ 'decisions': [answeredRow('d1')],
+ };
+ await r.reader.refresh();
+ await r.asks.readAnswered();
+ expect(r.asks.answered, hasLength(1));
+ r.reader.revoke();
+ expect(r.asks.answered, isEmpty);
+ },
+ );
+ });
+
test('a backend from before decisions has none to show', () async {
final r = rig(decisions: 1);
r.swarm.routes['/api/super-tabs/$tab/decisions'] = (_) =>
diff --git a/mobile/test/swarm/swarm_buddy_chat_test.dart b/mobile/test/swarm/swarm_buddy_chat_test.dart
index 81e10c399..aff52340d 100644
--- a/mobile/test/swarm/swarm_buddy_chat_test.dart
+++ b/mobile/test/swarm/swarm_buddy_chat_test.dart
@@ -415,6 +415,83 @@ void main() {
expect(post['recipientIds'], ['agent-lead']);
});
+ // Tony's phone list, task 26, as Desktop's decisions_view.dart.
+ group('a question here also offers', () {
+ Future<FakeSwarm> open(
+ WidgetTester tester, {
+ List<Map<String, dynamic>>? decisions,
+ }) async {
+ final fake = backend(
+ buddy: wren(),
+ page: [message('m1', 1, author: 'agent-wren')],
+ decisions: decisions ?? [decision('d1', minute: 2)],
+ );
+ await pump(tester, fake);
+ return fake;
+ }
+
+ testWidgets('its coordinator deciding, held for Undo, then sent as a '
+ 'delegation', (tester) async {
+ final fake = await open(tester);
+ await tester.tap(find.text('Let Product Manager decide'));
+ await tester.pump();
+ expect(find.text('Leaving it to Product Manager'), findsOneWidget);
+ await tester.pump(const Duration(seconds: 10));
+ await tester.pumpAndSettle();
+ expect(fake.commands.single, {
+ 'type': 'decision.answer',
+ 'decisionId': 'd1',
+ 'delegate': true,
+ });
+ });
+
+ testWidgets('and Undo takes it back, sending nothing', (tester) async {
+ final fake = await open(tester);
+ await tester.tap(find.text('Let Product Manager decide'));
+ await tester.pump();
+ await tester.tap(key('swarm-undo-d1'));
+ await tester.pump(const Duration(seconds: 10));
+ await tester.pumpAndSettle();
+ expect(fake.commands, isEmpty);
+ expect(find.text('Let Product Manager decide'), findsOneWidget);
+ });
+
+ testWidgets('not with no recommended option to take', (tester) async {
+ await open(
+ tester,
+ decisions: [
+ {...decision('d1', minute: 2), 'recommended': null},
+ ],
+ );
+ expect(find.text('Let Product Manager decide'), findsNothing);
+ expect(find.text('Not now'), findsOneWidget);
+ });
+
+ testWidgets('Not now, folding it to one line here with Show, sending '
+ 'nothing, and a question asked later still shows', (tester) async {
+ final fake = await open(
+ tester,
+ decisions: [decision('d1', minute: 2), decision('d2', minute: 3)],
+ );
+ await tester.tap(key('swarm-decision-later-d1'));
+ await tester.pumpAndSettle();
+ expect(key('swarm-ask-d1'), findsNothing);
+ expect(key('swarm-ask-d2'), findsOneWidget);
+ expect(find.text('1 decision set aside'), findsOneWidget);
+ expect(fake.commands, isEmpty);
+
+ await tester.tap(key('swarm-decision-later-d2'));
+ await tester.pumpAndSettle();
+ expect(find.text('2 decisions set aside'), findsOneWidget);
+
+ await tester.tap(key('swarm-decisions-show'));
+ await tester.pumpAndSettle();
+ expect(key('swarm-ask-d1'), findsOneWidget);
+ expect(key('swarm-ask-d2'), findsOneWidget);
+ expect(key('swarm-decisions-aside'), findsNothing);
+ });
+ });
+
testWidgets('every open question the PM asked the person in the project '
'shows here and is answered in place', (tester) async {
final fake = backend(
diff --git a/mobile/test/swarm/swarm_chat_test.dart b/mobile/test/swarm/swarm_chat_test.dart
index 85eb61c17..5c90884d0 100644
--- a/mobile/test/swarm/swarm_chat_test.dart
+++ b/mobile/test/swarm/swarm_chat_test.dart
@@ -317,7 +317,7 @@ void main() {
expect(find.text('PM'), findsOneWidget);
expect(find.text('Nova'), findsOneWidget);
expect(find.text('Dev'), findsOneWidget);
- expect(find.text('tony'), findsOneWidget);
+ expect(find.text('person-me'), findsOneWidget);
expect(find.text(time(0)), findsOneWidget);
expect(find.text(time(1)), findsNothing, reason: 'a follow-up has none');
expect(find.text(time(2)), findsOneWidget);
@@ -1208,6 +1208,28 @@ void main() {
);
});
+ testWidgets('Delete takes a Not sent post away, and sends nothing', (
+ tester,
+ ) async {
+ final fake = backend([message('m1', 1)]);
+ fake.routes[commands] = (_) =>
+ throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.');
+ await pump(tester, fake);
+ await tester.enterText(find.byType(TextField), 'Never mind');
+ await tester.pump();
+ await tester.tap(key('swarm-send'));
+ await tester.pumpAndSettle();
+ expect(find.text('Not sent'), findsOneWidget);
+ final sends = fake.commands.length;
+
+ await tester.tap(key('swarm-delete-post'));
+ await tester.pumpAndSettle();
+
+ expect(find.text('Not sent'), findsNothing);
+ expect(find.text('Never mind'), findsNothing);
+ expect(fake.commands, hasLength(sends));
+ });
+
testWidgets('a post whose answer was lost reads Not sent under it, and '
'Retry sends the same post', (tester) async {
final fake = backend([message('m1', 1)]);
diff --git a/mobile/test/swarm/swarm_decision_shots_test.dart b/mobile/test/swarm/swarm_decision_shots_test.dart
new file mode 100644
index 000000000..016d24fe1
--- /dev/null
+++ b/mobile/test/swarm/swarm_decision_shots_test.dart
@@ -0,0 +1,250 @@
+import 'dart:convert';
+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_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/theme/color_palette.dart';
+import 'package:harness_mobile/swarm/swarm_activity_page.dart';
+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+
+/// A decision's choices in the Buddy chat, and Activity's Answered list, in
+/// both phone themes, for the pull request, written to the folder
+/// `SWARM_DECISION_SHOTS` names (run this file alone, on a Mac). Scripted data
+/// only.
+final shots = Platform.environment['SWARM_DECISION_SHOTS'];
+
+void main() {
+ setUpAll(() async {
+ if (shots == null || !Platform.isMacOS) return;
+ final sf = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFont', 'Roboto']) {
+ await (FontLoader(family)..addFont(Future.value(sf))).load();
+ }
+ final mono = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFontMonospaced', 'monospace']) {
+ await (FontLoader(family)..addFont(Future.value(mono))).load();
+ }
+ final manifest =
+ jsonDecode(await rootBundle.loadString('FontManifest.json')) as List;
+ for (final entry in manifest.cast<Map<String, dynamic>>()) {
+ final loader = FontLoader(entry['family'] as String);
+ for (final font in (entry['fonts'] as List).cast<Map>()) {
+ loader.addFont(rootBundle.load(font['asset'] as String));
+ }
+ await loader.load();
+ }
+ });
+
+ testWidgets('a decision\'s choices and the answered list, both themes', (
+ tester,
+ ) async {
+ await tester.binding.setSurfaceSize(const Size(390, 844));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ const chat = 'buddy-me';
+ Map<String, dynamic> message(
+ String id,
+ int sequence,
+ String text, {
+ String? agent,
+ int minute = 0,
+ }) => {
+ 'id': id,
+ 'conversationId': chat,
+ 'text': text,
+ 'sequence': sequence,
+ 'author': switch (agent) {
+ null => {'kind': 'person', 'id': me, 'name': 'tony'},
+ 'agent-lead' => {'kind': 'agent', 'id': agent, 'name': 'River'},
+ _ => {'kind': 'agent', 'id': agent, 'name': 'Wren'},
+ },
+ 'attachments': <Object>[],
+ 'reactions': <Object>[],
+ 'createdAt': DateTime.utc(2026, 10, 29, 8, minute).toIso8601String(),
+ };
+ final page = [
+ message(
+ 'm1',
+ 1,
+ 'The phone chain installs this afternoon: drawer names, task lines '
+ 'and the Buddy chat.',
+ agent: 'agent-lead',
+ ),
+ message('m2', 2, 'Can the chat start right under the header?', minute: 2),
+ message(
+ 'm3',
+ 3,
+ 'Yes. Nothing sits between the header and your messages now.',
+ agent: 'agent-wren',
+ minute: 3,
+ ),
+ ];
+
+ Map<String, dynamic> decision(
+ String id,
+ String question,
+ List<String> options, {
+ int? choice,
+ bool delegated = false,
+ }) => {
+ 'id': id,
+ 'batchId': id,
+ 'projectId': project,
+ 'projectName': 'Mobile',
+ 'conversationId': chat,
+ 'conversationTitle': 'Buddy',
+ 'askerName': 'River',
+ 'question': question,
+ 'options': options,
+ 'recommended': 0,
+ 'unblocks': 'the release notes',
+ 'choice': ?choice,
+ if (delegated) 'delegated': true,
+ 'createdAt': DateTime.utc(2026, 10, 29, 8, 4).toIso8601String(),
+ };
+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {
+ final brightness = palette.brightness;
+ AppTheme.palette.value = palette;
+ AppTheme.brightness.value = brightness;
+ final fake = FakeSwarm();
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {
+ ...firstLoad(
+ derived: {'decisionsWaiting': 1},
+ groups: [
+ buddyChatData(
+ chat,
+ agentIds: ['agent-wren'],
+ lastMessageSequence: page.length,
+ ),
+ ],
+ agents: [
+ agent('agent-lead', name: 'Lead', displayName: 'River'),
+ buddyData('agent-wren', displayName: 'Wren'),
+ ],
+ machines: [
+ {
+ 'machineId': 'mac-1',
+ 'name': 'Studio-Mac.local',
+ 'contributorId': me,
+ 'engines': ['claude', 'codex'],
+ },
+ ],
+ ),
+ 'members': [part(me, 1, person(me))],
+ };
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>
+ changes(cursor: 'c2', derived: {'decisionsWaiting': 1});
+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {
+ 'decisions': [
+ decision('d1', 'Ship the beta on Friday?', [
+ 'Yes, Friday',
+ 'No, wait',
+ ]),
+ ],
+ };
+ fake.routes['/api/super-tabs/$tab/decisions?state=settled'] = (_) => {
+ 'decisions': [
+ decision('a1', 'Which region first?', ['Europe', 'Asia'], choice: 0),
+ decision(
+ 'a2',
+ 'Keep the old installer?',
+ ['Yes', 'No'],
+ choice: 0,
+ delegated: true,
+ ),
+ ],
+ };
+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {
+ 'mentions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$tab/conversations/$chat/messages'] = (_) =>
+ {'messages': page.reversed.toList(), 'next': null};
+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm};
+ final account = ValueNotifier<String?>(me);
+ final host = SwarmHost(
+ accountId: () => me,
+ account: account,
+ request: fake.request,
+ upload: refuseSwarmUpload,
+ notices: SilentSystemNotices(),
+ features: features,
+ // Not now keeps its choice here: in memory, never in this Mac's files.
+ readMarks: MemoryKeyValueStore(),
+ )..foreground = false;
+ final boundary = GlobalKey();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: buildAppTheme(brightness: brightness),
+ builder: (_, child) => SwarmScope(notifier: host, child: child!),
+ home: const SwarmConversationPage(
+ swarmId: tab,
+ conversationId: chat,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ Future<void> capture(String name) => tester.runAsync(() async {
+ final image =
+ await (boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 3);
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ await File('$shots/decision-$name-${brightness.name}.png')
+ .writeAsBytes(png!.buffer.asUint8List());
+ image.dispose();
+ });
+ await capture('choices');
+ await tester.tap(find.text('Let Product Manager decide'));
+ await tester.pump();
+ await capture('held');
+ await tester.tap(find.byKey(const ValueKey('swarm-undo-d1')));
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('swarm-decision-later-d1')));
+ await tester.pumpAndSettle();
+ await capture('aside');
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: buildAppTheme(brightness: brightness),
+ builder: (_, child) => SwarmScope(notifier: host, child: child!),
+ home: const SwarmActivityPage(),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await capture('answered');
+ await tester.pumpWidget(const SizedBox());
+ host.dispose();
+ account.dispose();
+ }
+ AppTheme.palette.value = HarnessPalette.graphite;
+ AppTheme.brightness.value = Brightness.dark;
+ }, skip: shots == null);
+}
diff --git a/mobile/test/swarm/swarm_decisions_aside_test.dart b/mobile/test/swarm/swarm_decisions_aside_test.dart
new file mode 100644
index 000000000..15b11b8a3
--- /dev/null
+++ b/mobile/test/swarm/swarm_decisions_aside_test.dart
@@ -0,0 +1,61 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/swarm/swarm_home_prefs.dart';
+
+import '../voice_fakes.dart';
+
+// Tony's phone list, task 26: Not now stays on this phone, as on Desktop's computer.
+void main() {
+ Future<SwarmHomePrefs> open(MemoryKeyValueStore store) async {
+ final prefs = SwarmHomePrefs(accountId: 'me', store: store);
+ addTearDown(prefs.dispose);
+ await pumpEventQueue();
+ return prefs;
+ }
+
+ test(
+ 'a decision set aside stays so after a restart, and comes back when shown',
+ () async {
+ final store = MemoryKeyValueStore();
+ final first = await open(store);
+ first.setDecisionsAside('swarm', ['d1', 'd2'], aside: true);
+ await pumpEventQueue();
+
+ final second = await open(store);
+ expect(second.decisionAside('swarm', 'd1'), isTrue);
+ expect(
+ second.decisionAside('swarm', 'd3'),
+ isFalse,
+ reason: 'asked later',
+ );
+ expect(second.decisionAside('other', 'd1'), isFalse);
+
+ second.setDecisionsAside('swarm', ['d1'], aside: false);
+ await pumpEventQueue();
+ final third = await open(store);
+ expect(third.decisionAside('swarm', 'd1'), isFalse);
+ expect(third.decisionAside('swarm', 'd2'), isTrue);
+ },
+ );
+
+ test('one answered is forgotten, a Swarm lost takes its own, and the oldest '
+ 'go past the limit', () async {
+ final prefs = await open(MemoryKeyValueStore());
+ prefs.setDecisionsAside('swarm', ['d1', 'd2'], aside: true);
+ prefs.forgetDecisionsAside('swarm', ['d1']);
+ expect(prefs.decisionAside('swarm', 'd1'), isFalse);
+ expect(prefs.decisionAside('swarm', 'd2'), isTrue);
+
+ prefs.keepOnly({'other'});
+ expect(prefs.decisionAside('swarm', 'd2'), isFalse);
+
+ prefs.keepOnly({'swarm'});
+ prefs.setDecisionsAside('swarm', [
+ for (var i = 0; i <= SwarmHomePrefs.keptAside; i++) 'n$i',
+ ], aside: true);
+ expect(prefs.decisionAside('swarm', 'n0'), isFalse);
+ expect(
+ prefs.decisionAside('swarm', 'n${SwarmHomePrefs.keptAside}'),
+ isTrue,
+ );
+ });
+}
diff --git a/mobile/test/swarm/swarm_drafts_unsent_shots_test.dart b/mobile/test/swarm/swarm_drafts_unsent_shots_test.dart
new file mode 100644
index 000000000..297ce1f2a
--- /dev/null
+++ b/mobile/test/swarm/swarm_drafts_unsent_shots_test.dart
@@ -0,0 +1,158 @@
+import 'dart:convert';
+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_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/theme/color_palette.dart';
+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';
+import 'package:harness_mobile/swarm/swarm_kept.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+
+/// Review screenshots of a Not sent post and a draft kept across a restart, in
+/// both phone themes, from made-up data only, to `SWARM_DRAFTS_SHOTS`.
+final shots = Platform.environment['SWARM_DRAFTS_SHOTS'];
+
+void main() {
+ setUpAll(() async {
+ if (shots == null || !Platform.isMacOS) return;
+ final sf = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFont', 'Roboto']) {
+ await (FontLoader(family)..addFont(Future.value(sf))).load();
+ }
+ final mono = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFontMonospaced', 'monospace']) {
+ await (FontLoader(family)..addFont(Future.value(mono))).load();
+ }
+ final manifest =
+ jsonDecode(await rootBundle.loadString('FontManifest.json')) as List;
+ for (final entry in manifest.cast<Map<String, dynamic>>()) {
+ final loader = FontLoader(entry['family'] as String);
+ for (final font in (entry['fonts'] as List).cast<Map>()) {
+ loader.addFont(rootBundle.load(font['asset'] as String));
+ }
+ await loader.load();
+ }
+ });
+
+ testWidgets('Not sent and a kept draft, in both phone themes', (
+ tester,
+ ) async {
+ await tester.binding.setSurfaceSize(const Size(390, 844));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {
+ final brightness = palette.brightness;
+ AppTheme.palette.value = palette;
+ AppTheme.brightness.value = brightness;
+ final fake = FakeSwarm();
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ fake.routes['/api/super-tabs/invitations'] = (_) => <Object>[];
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {
+ ...firstLoad(
+ groups: [
+ groupData('g1', title: 'Fix login', agentIds: const ['agent-lead']),
+ ],
+ ),
+ 'members': [part(me, 1, person(me, role: 'owner'))],
+ };
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>
+ changes(cursor: 'c2');
+ fake.routes['/api/super-tabs/$tab/conversations/g1/messages'] = (_) => {
+ 'messages': <Object>[],
+ 'before': null,
+ };
+ fake.routes['/api/super-tabs/$tab/commands'] = (_) =>
+ throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.');
+ final store = MemorySwarmKeptStore()
+ ..heldBy = me
+ ..held = {
+ 'drafts': [
+ {'tab': tab, 'chat': 'g1', 'text': 'Half a thought, still here'},
+ ],
+ 'posts': [
+ {
+ 'tab': tab,
+ 'chat': 'g1',
+ 'posts': [
+ {
+ 'body': {
+ 'operationId': 'op-1',
+ 'command': {
+ 'type': 'message.send',
+ 'conversationId': 'g1',
+ 'text': 'Ship the fix tonight?',
+ },
+ },
+ 'messageId': 'kept-1',
+ },
+ ],
+ },
+ ],
+ };
+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm};
+ final account = ValueNotifier<String?>(me);
+ final host = SwarmHost(
+ accountId: () => account.value,
+ account: account,
+ request: fake.request,
+ notices: SilentSystemNotices(),
+ features: features,
+ readMarks: MemoryKeyValueStore(),
+ kept: store,
+ )..foreground = false;
+ await host.session!.inbox.kept.ready;
+ await host.session!.inbox.refresh();
+ final boundary = GlobalKey();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: buildAppTheme(brightness: brightness),
+ builder: (_, child) => SwarmScope(notifier: host, child: child!),
+ home: const SwarmConversationPage(
+ swarmId: tab,
+ conversationId: 'g1',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Not sent'), findsOneWidget);
+ await tester.runAsync(() async {
+ final image =
+ await (boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 3);
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ await File('$shots/not-sent-${brightness.name}.png')
+ .writeAsBytes(png!.buffer.asUint8List());
+ image.dispose();
+ });
+ await tester.pumpWidget(const SizedBox());
+ host.dispose();
+ account.dispose();
+ }
+ AppTheme.palette.value = HarnessPalette.graphite;
+ AppTheme.brightness.value = Brightness.dark;
+ }, skip: shots == null);
+}
diff --git a/mobile/test/swarm/swarm_drafts_unsent_test.dart b/mobile/test/swarm/swarm_drafts_unsent_test.dart
new file mode 100644
index 000000000..3f3cd70d6
--- /dev/null
+++ b/mobile/test/swarm/swarm_drafts_unsent_test.dart
@@ -0,0 +1,581 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/swarm/swarm_conversation.dart';
+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';
+import 'package:harness_mobile/swarm/swarm_inbox.dart';
+import 'package:harness_mobile/swarm/swarm_kept.dart';
+import 'package:harness_mobile/swarm/swarm_outbox.dart';
+import 'package:harness_mobile/swarm/swarm_post_line.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+import 'package:harness_mobile/swarm/swarm_thread.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+
+/// A chat's draft and a post that did not get through stay until they are sent
+/// or cleared, across leaving the chat and a restart, for the account alone
+/// (Tony's mobile list, task 25). A phone app is killed often.
+void main() {
+ const commands = '/api/super-tabs/$tab/commands';
+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';
+
+ late MemorySwarmKeptStore store;
+ late FakeSwarm swarm;
+ setUp(() {
+ store = MemorySwarmKeptStore();
+ swarm = FakeSwarm();
+ swarm.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ swarm.routes['/api/super-tabs/invitations'] = (_) => <Object>[];
+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => {
+ ...firstLoad(
+ groups: [
+ groupData('g1', title: 'Fix login', agentIds: const ['agent-lead']),
+ ],
+ ),
+ 'members': [part(me, 1, person(me, role: 'owner'))],
+ };
+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');
+ swarm.routes[messages] = (_) => {'messages': <Object>[], 'before': null};
+ });
+
+ /// A running app: what a restart makes anew, over the same [store].
+ Future<SwarmInbox> app() async {
+ final inbox = SwarmInbox(
+ accountId: me,
+ request: swarm.request,
+ keptStore: store,
+ );
+ addTearDown(inbox.dispose);
+ await inbox.kept.ready;
+ await inbox.refresh();
+ return inbox;
+ }
+
+ Future<SwarmConversation> chat(SwarmInbox inbox) async {
+ final c = SwarmConversation(inbox.reader(tab)!, 'g1');
+ addTearDown(() {
+ if (!_gone.contains(c)) c.dispose();
+ });
+ await c.load();
+ return c;
+ }
+
+ void leave(SwarmConversation c) {
+ _gone.add(c);
+ c.dispose();
+ }
+
+ Never lost(_) =>
+ throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.');
+
+ /// A post whose answer never came.
+ Future<SwarmPost> notSent(SwarmConversation c, String text) async {
+ swarm.routes[commands] = lost;
+ c.draft = text;
+ await c.send();
+ return c.outgoing.single;
+ }
+
+ group('a draft', () {
+ test('survives leaving the chat and coming back', () async {
+ final inbox = await app();
+ final first = await chat(inbox);
+ first.draft = 'half a thought';
+ leave(first);
+ expect((await chat(inbox)).draft, 'half a thought');
+ });
+
+ test('survives a restart, its mentions with it', () async {
+ final before = await app();
+ final c = await chat(before);
+ c.draft = 'ask';
+ c.mention('agent-lead');
+ final draft = c.draft;
+ expect(draft, isNot('ask'));
+ await before.kept.flush();
+ final again = await app();
+ final after = await chat(again);
+ expect(after.draft, draft);
+ expect(again.kept.draft(tab, 'g1', null)?.mentions.keys, ['agent-lead']);
+ });
+
+ test('is kept per chat', () async {
+ final inbox = await app();
+ (await chat(inbox)).draft = 'for g1';
+ expect(
+ inbox.kept.draft(tab, 'g2', null),
+ isNull,
+ reason: 'another chat starts empty',
+ );
+ });
+
+ test('a thread reply keeps its own, across a restart', () async {
+ final before = await app();
+ final c = await chat(before);
+ final t = SwarmThread(c, 'root-1');
+ addTearDown(t.dispose);
+ t.draft = 'in the thread';
+ expect(c.draft, isEmpty);
+ await before.kept.flush();
+ final after = await chat(await app());
+ expect(after.threadDraft('root-1'), 'in the thread');
+ });
+
+ test(
+ 'goes once sent, and a kill right after brings nothing back',
+ () async {
+ swarm.routes[commands] = (_) => {
+ 'result': {'messageId': 'm9'},
+ };
+ final before = await app();
+ final c = await chat(before);
+ c.draft = 'sent now';
+ await c.send();
+ // No flush: what a send writes, it writes at once.
+ expect(store.held?['drafts'], isEmpty);
+ expect((await chat(await app())).draft, isEmpty);
+ },
+ );
+
+ test('emptied by hand, it goes', () async {
+ final before = await app();
+ final c = await chat(before);
+ c.draft = 'words';
+ c.draft = '';
+ await before.kept.flush();
+ expect((await chat(await app())).draft, isEmpty);
+ });
+ });
+
+ group('on the page', () {
+ Future<SwarmHost> open(WidgetTester tester, {required String draft}) async {
+ store
+ ..heldBy = me
+ ..held = {
+ 'drafts': [
+ {'tab': tab, 'chat': 'g1', 'text': draft},
+ ],
+ 'posts': <Object>[],
+ };
+ final account = ValueNotifier<String?>(me);
+ final host = SwarmHost(
+ accountId: () => account.value,
+ account: account,
+ request: swarm.request,
+ notices: SilentSystemNotices(),
+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm},
+ readMarks: MemoryKeyValueStore(),
+ kept: store,
+ )..foreground = false;
+ addTearDown(host.dispose);
+ await host.session!.inbox.kept.ready;
+ await host.session!.inbox.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ builder: (_, child) => SwarmScope(notifier: host, child: child!),
+ home: const SwarmConversationPage(swarmId: tab, conversationId: 'g1'),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return host;
+ }
+
+ String box(WidgetTester tester) =>
+ tester.widget<TextField>(find.byType(TextField)).controller!.text;
+
+ testWidgets('the words kept are in the box when the chat opens', (
+ tester,
+ ) async {
+ await open(tester, draft: 'half a thought');
+ expect(box(tester), 'half a thought');
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(seconds: 1));
+ });
+
+ testWidgets('what is typed then is what is kept', (tester) async {
+ final host = await open(tester, draft: 'half');
+ await tester.enterText(find.byType(TextField), 'half a thought');
+ await tester.pump();
+ expect(
+ host.session!.inbox.kept.draft(tab, 'g1', null)?.text,
+ 'half a thought',
+ );
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(seconds: 1));
+ });
+ });
+
+ group('Not sent', () {
+ test('survives a restart', () async {
+ final c = await chat(await app());
+ await notSent(c, 'did you get this?');
+ final after = await chat(await app());
+ expect(after.outgoing.single.text, 'did you get this?');
+ expect(after.outgoing.single.state, SwarmPostState.unconfirmed);
+ });
+
+ test('one caught mid-send by a kill comes back as Not sent', () async {
+ final answer = Completer<Object?>();
+ swarm.routes[commands] = (_) => answer.future;
+ final c = await chat(await app());
+ c.draft = 'on its way';
+ unawaited(c.send());
+ await Future<void>.delayed(Duration.zero);
+ expect(c.outgoing.single.state, SwarmPostState.sending);
+ final after = await chat(await app());
+ expect(after.outgoing.single.state, SwarmPostState.unconfirmed);
+ });
+
+ test('Retry after a restart sends the same receipt, once', () async {
+ final c = await chat(await app());
+ final post = await notSent(c, 'once only');
+ final after = await chat(await app());
+ swarm.routes[commands] = (_) => {
+ 'result': {'messageId': post.messageId},
+ };
+ expect(await after.retry(after.outgoing.single), isTrue);
+ final sent = swarm.calls
+ .where((call) => call.path == commands)
+ .map((call) => call.body!['operationId'])
+ .toSet();
+ expect(sent, {post.operationId});
+ });
+
+ test('Delete takes it away for good', () async {
+ final c = await chat(await app());
+ final post = await notSent(c, 'never mind');
+ c.deletePost(post);
+ expect(c.outgoing, isEmpty);
+ expect((await chat(await app())).outgoing, isEmpty);
+ });
+
+ test('a refusal after a restart puts its words back in the box', () async {
+ final c = await chat(await app());
+ await notSent(c, 'my words');
+ final after = await chat(await app());
+ swarm.routes[commands] = (_) =>
+ throw const SuperTabFailure('INVALID', 'Refused.', statusCode: 400);
+ await after.retry(after.outgoing.single);
+ expect(after.outgoing, isEmpty);
+ expect(after.draft, 'my words');
+ });
+
+ test('the first read showing it arrived drops the copy, quietly', () async {
+ final c = await chat(await app());
+ final post = await notSent(c, 'arrived after all');
+ swarm.routes[messages] = (_) => {
+ 'messages': [
+ {
+ 'id': post.messageId,
+ 'conversationId': 'g1',
+ 'text': 'arrived after all',
+ 'sequence': 1,
+ 'author': {'kind': 'person', 'id': me, 'name': 'me'},
+ 'createdAt': '2026-11-03T01:00:00.000Z',
+ },
+ ],
+ 'before': null,
+ };
+ final after = await chat(await app());
+ expect(after.outgoing, isEmpty);
+ expect(after.messages.single.id, post.messageId);
+ expect(store.held?['posts'], isEmpty);
+ });
+
+ test('a thread reply survives too, and can be deleted', () async {
+ final before = await app();
+ final c = await chat(before);
+ swarm.routes[commands] = lost;
+ final t = SwarmThread(c, 'root-1');
+ addTearDown(t.dispose);
+ t.draft = 'reply';
+ await t.send();
+ final after = await chat(await app());
+ final again = SwarmThread(after, 'root-1');
+ addTearDown(again.dispose);
+ expect(again.outgoing.single.text, 'reply');
+ again.deletePost(again.outgoing.single);
+ expect((await app()).kept.posts(tab, 'g1', 'root-1'), isEmpty);
+ });
+
+ testWidgets('its row has Retry and Delete; Sending… has neither', (
+ tester,
+ ) async {
+ var retried = 0, deleted = 0;
+ Widget line(bool sending) => MaterialApp(
+ home: Scaffold(
+ body: SwarmPostLine(
+ sending: sending,
+ onRetry: () => retried++,
+ onDelete: () => deleted++,
+ ),
+ ),
+ );
+ await tester.pumpWidget(line(false));
+ await tester.tap(find.byKey(const ValueKey('swarm-resend-post')));
+ await tester.tap(find.byKey(const ValueKey('swarm-delete-post')));
+ expect((retried, deleted), (1, 1));
+ expect(
+ tester.getSize(find.byKey(const ValueKey('swarm-delete-post'))).height,
+ greaterThanOrEqualTo(44),
+ );
+ await tester.pumpWidget(line(true));
+ expect(find.byKey(const ValueKey('swarm-delete-post')), findsNothing);
+ });
+ });
+
+ group('access', () {
+ test('a Swarm lost takes its own, and not another\'s', () async {
+ final inbox = await app();
+ final c = await chat(inbox);
+ c.draft = 'mine';
+ inbox.kept.setDraft('other', 'x', null, 'stays');
+ await inbox.kept.flush();
+ swarm.routes['/api/super-tabs/other/parts'] = (_) =>
+ firstLoad(tabId: 'other');
+ swarm.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': 'other', 'name': 'Other', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ await inbox.refresh();
+ expect(inbox.kept.draft(tab, 'g1', null), isNull);
+ expect(inbox.kept.draft('other', 'x', null)?.text, 'stays');
+ expect('${store.held}', isNot(contains('mine')));
+ });
+
+ test(
+ 'a Swarm lost while the app was closed goes at the next list',
+ () async {
+ store
+ ..heldBy = me
+ ..held = {
+ 'drafts': [
+ {'tab': 'lost', 'chat': 'x', 'text': 'lost words'},
+ {'tab': tab, 'chat': 'g1', 'text': 'kept words'},
+ ],
+ 'posts': [
+ {
+ 'tab': 'lost',
+ 'chat': 'x',
+ 'posts': [
+ {'messageId': 'lost post'},
+ ],
+ },
+ ],
+ };
+ final inbox = await app();
+ expect(inbox.kept.draft('lost', 'x', null), isNull);
+ expect(inbox.kept.posts('lost', 'x', null), isEmpty);
+ expect(inbox.kept.draft(tab, 'g1', null)?.text, 'kept words');
+ await pumpEventQueue();
+ expect('${store.held}', isNot(contains('lost')));
+ },
+ );
+
+ test('the same when what was kept reads back after the list', () async {
+ store
+ ..heldBy = me
+ ..held = {
+ 'drafts': [
+ {'tab': 'lost', 'chat': 'x', 'text': 'lost words'},
+ ],
+ 'posts': <Object>[],
+ };
+ final slow = _SlowStore(store);
+ final inbox = SwarmInbox(
+ accountId: me,
+ request: swarm.request,
+ keptStore: slow,
+ );
+ addTearDown(inbox.dispose);
+ await inbox.refresh();
+ slow.gate.complete();
+ await inbox.kept.ready;
+ await pumpEventQueue();
+ expect(inbox.kept.draft('lost', 'x', null), isNull);
+ expect('${store.held}', isNot(contains('lost words')));
+ });
+
+ test('a list that fails drops nothing', () async {
+ store
+ ..heldBy = me
+ ..held = {
+ 'drafts': [
+ {'tab': 'other', 'chat': 'x', 'text': 'stays'},
+ ],
+ 'posts': <Object>[],
+ };
+ swarm.routes['/api/super-tabs/list'] = lost;
+ final inbox = await app();
+ expect(inbox.kept.draft('other', 'x', null)?.text, 'stays');
+ });
+
+ test('a drop before what was kept reads back reaches the file', () async {
+ store
+ ..heldBy = me
+ ..held = {
+ 'drafts': [
+ {'tab': 'gone', 'chat': 'x', 'text': 'old words'},
+ {'tab': 'stays', 'chat': 'y', 'text': 'other words'},
+ ],
+ 'posts': <Object>[],
+ };
+ final slow = _SlowStore(store);
+ final kept = SwarmKept(accountId: me, store: slow);
+ addTearDown(kept.dispose);
+ kept.dropSwarm('gone');
+ slow.gate.complete();
+ await kept.ready;
+ await pumpEventQueue();
+ expect('${store.held}', isNot(contains('old words')));
+ expect('${store.held}', contains('other words'));
+ });
+
+ test('a chat lost while open takes its draft and posts', () async {
+ final inbox = await app();
+ final c = await chat(inbox);
+ await notSent(c, 'unsent');
+ c.draft = 'drafted';
+ swarm.routes[messages] = (_) =>
+ throw const SuperTabFailure('FORBIDDEN', 'No.', statusCode: 403);
+ await c.load();
+ expect(c.draft, isEmpty);
+ expect('${store.held}', isNot(contains('unsent')));
+ expect(inbox.kept.draft(tab, 'g1', null), isNull);
+ });
+
+ test('a thread draft written after the chat is lost is refused', () async {
+ final inbox = await app();
+ final c = await chat(inbox);
+ swarm.routes[messages] = (_) => throw const SuperTabFailure(
+ 'FORBIDDEN',
+ 'No.',
+ statusCode: 403,
+ );
+ await c.load();
+ c.setThreadDraft('root-1', 'too late');
+ expect(inbox.kept.draft(tab, 'g1', 'root-1'), isNull);
+ });
+
+ test('a chat lost while closed takes them, unopened', () async {
+ final before = await app();
+ before.kept.setDraft(tab, 'gone', null, 'secret words');
+ await before.kept.flush();
+ swarm.routes['/api/super-tabs/$tab/groups/gone'] = (_) =>
+ throw const SuperTabFailure('NOT_FOUND', 'No.', statusCode: 404);
+ final after = await app();
+ await pumpEventQueue();
+ expect(swarm.paths, contains('/api/super-tabs/$tab/groups/gone'));
+ expect(after.kept.draft(tab, 'gone', null), isNull);
+ expect('${store.held}', isNot(contains('secret words')));
+ });
+
+ test('a read that cannot say keeps it, and asks again', () async {
+ final before = await app();
+ before.kept.setDraft(tab, 'maybe', null, 'keep me');
+ await before.kept.flush();
+ swarm.routes['/api/super-tabs/$tab/groups/maybe'] = (_) =>
+ throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.');
+ final after = await app();
+ await pumpEventQueue();
+ expect(after.kept.draft(tab, 'maybe', null)?.text, 'keep me');
+ });
+ });
+
+ group('the account', () {
+ late ValueNotifier<String?> account;
+ late bool reading;
+ late ExperimentalFeaturesStore features;
+
+ Future<SwarmHost> host() async {
+ account = ValueNotifier<String?>(me);
+ reading = false;
+ features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm};
+ final h = SwarmHost(
+ accountId: () => account.value,
+ accountReading: () => reading,
+ account: account,
+ request: swarm.request,
+ notices: SilentSystemNotices(),
+ features: features,
+ readMarks: MemoryKeyValueStore(),
+ kept: store,
+ )..foreground = false;
+ addTearDown(h.dispose);
+ await h.session!.inbox.kept.ready;
+ h.session!.inbox.kept.setDraft(tab, 'g1', null, 'private words');
+ await h.session!.inbox.kept.flush();
+ expect('${store.held}', contains('private words'));
+ return h;
+ }
+
+ Future<void> settled() => pumpEventQueue();
+
+ test('signing out clears it', () async {
+ await host();
+ account.value = null;
+ await settled();
+ expect(store.held, isNull);
+ });
+
+ test('another account signing in clears it', () async {
+ final h = await host();
+ account.value = 'someone-else';
+ await settled();
+ expect(store.held, isNull);
+ await h.session!.inbox.kept.ready;
+ expect(h.session!.inbox.kept.draft(tab, 'g1', null), isNull);
+ });
+
+ test('Swarm turned off clears it', () async {
+ await host();
+ features.value = const {};
+ await settled();
+ expect(store.held, isNull);
+ });
+
+ test('the same account still being read keeps it', () async {
+ await host();
+ reading = true;
+ account.value = null;
+ await settled();
+ expect('${store.held}', contains('private words'));
+ });
+ });
+}
+
+final _gone = <SwarmConversation>{};
+
+/// A store whose read waits for [gate].
+class _SlowStore implements SwarmKeptStore {
+ _SlowStore(this.inner);
+ final SwarmKeptStore inner;
+ final gate = Completer<void>();
+
+ @override
+ Future<Map<String, dynamic>?> read(String accountId) async {
+ await gate.future;
+ return inner.read(accountId);
+ }
+
+ @override
+ Future<void> write(String accountId, Map<String, dynamic> kept) =>
+ inner.write(accountId, kept);
+
+ @override
+ Future<void> clear() => inner.clear();
+}
diff --git a/mobile/test/swarm/swarm_home_signed_out_test.dart b/mobile/test/swarm/swarm_home_signed_out_test.dart
index 27eb12a34..29ec282a3 100644
--- a/mobile/test/swarm/swarm_home_signed_out_test.dart
+++ b/mobile/test/swarm/swarm_home_signed_out_test.dart
@@ -2,6 +2,7 @@ import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness_mobile/phone/welcome/phone_welcome.dart';
import 'package:harness_mobile/swarm/parts.dart';
+import 'package:harness_mobile/swarm/swarm_kept.dart';
import '../phone_edge/edge_fixture.dart';
import 'swarm_fixture.dart';
@@ -12,6 +13,7 @@ import 'swarm_fixture.dart';
void main() {
testWidgets('the signed-out screen lets the Home kept go', (tester) async {
final home = memoryHomeCache();
+ final kept = MemorySwarmKeptStore()..held = {'drafts': <Object>[]};
await tester.runAsync(
() => home.write('person-me', [
(
@@ -30,12 +32,13 @@ void main() {
// On the real clock: the clear the screen starts is real file work.
await tester.runAsync(() async {
await tester.pumpWidget(
- phoneApp(PhoneWelcome(notifier: app, swarmHome: home)),
+ phoneApp(PhoneWelcome(notifier: app, swarmHome: home, swarmKept: kept)),
);
await home.read('person-me');
});
expect(home.file.existsSync(), isFalse);
+ expect(kept.held, isNull, reason: 'drafts and unsent posts go too');
expect((home.key as MemorySwarmHomeKey).value, isNull);
await tester.pumpWidget(const SizedBox());
diff --git a/mobile/test/swarm/swarm_instructions_page_test.dart b/mobile/test/swarm/swarm_instructions_page_test.dart
index 03ef218d2..84fc3e801 100644
--- a/mobile/test/swarm/swarm_instructions_page_test.dart
+++ b/mobile/test/swarm/swarm_instructions_page_test.dart
@@ -56,18 +56,23 @@ void main() {
WidgetTester tester, {
required Object? Function(Map<String, dynamic>? body) route,
int revision = 3,
+ Object? Function(Map<String, dynamic>? body)? commands,
+ String role = 'owner',
}) async {
final fake = FakeSwarm();
fake.routes['/api/super-tabs/$tab/parts'] = (_) {
final load = firstLoad(head: head(revision));
// The member's username differs from their id.
load['members'] = [
- part(me, 1, {...person(me), 'username': 'ken'}),
+ part(me, 1, {...person(me, role: role), 'username': 'ken'}),
];
return load;
};
fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');
fake.routes[path] = route;
+ if (commands != null) {
+ fake.routes['/api/super-tabs/$tab/commands'] = commands;
+ }
final reader = SwarmReader(
tabId: tab,
accountId: me,
@@ -121,7 +126,6 @@ void main() {
expect(find.byType(TextField), findsNothing);
expect(find.byType(EditableText), findsNothing);
expect(find.text('Save'), findsNothing);
- expect(find.text('Delete'), findsNothing);
expect(find.text('Restore'), findsNothing);
});
@@ -250,4 +254,86 @@ void main() {
expect(find.text('The server is busy.'), findsOneWidget);
expect(find.textContaining('Kept text'), findsOneWidget);
});
+
+ group('Delete on a note', () {
+ final notes = [note('n1', 'Do not use Codex.', '2026-10-01T10:00:00.000Z')];
+ final remove = find.byKey(const ValueKey('swarm-instructions-delete-n1'));
+
+ testWidgets('an allowed person confirms, and one delete goes', (
+ tester,
+ ) async {
+ final sent = <Map<String, dynamic>>[];
+ var kept = notes;
+ await open(
+ tester,
+ route: (_) => doc(3, 'Rules.', notes: kept),
+ commands: (body) {
+ sent.add(body!);
+ kept = [];
+ return {'result': <String, dynamic>{}};
+ },
+ );
+ expect(remove, findsOneWidget);
+ await tester.tap(remove);
+ await tester.pumpAndSettle();
+ expect(find.text('Delete this note?'), findsOneWidget);
+ expect(sent, isEmpty, reason: 'nothing goes before they confirm');
+ await tester.tap(find.text('Delete').last);
+ await tester.pumpAndSettle();
+ expect(sent, hasLength(1));
+ expect(sent.single['command'], {
+ 'type': 'note.remove',
+ 'projectId': project,
+ 'noteId': 'n1',
+ });
+ expect(sent.single['operationId'], isA<String>());
+ expect(find.text('Do not use Codex.'), findsNothing);
+ });
+
+ testWidgets('Cancel sends nothing', (tester) async {
+ final sent = <Object?>[];
+ await open(
+ tester,
+ route: (_) => doc(3, 'Rules.', notes: notes),
+ commands: (body) {
+ sent.add(body);
+ return {'result': <String, dynamic>{}};
+ },
+ );
+ await tester.tap(remove);
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Cancel'));
+ await tester.pumpAndSettle();
+ expect(sent, isEmpty);
+ expect(find.text('Do not use Codex.'), findsOneWidget);
+ });
+
+ testWidgets('a person who may not sees no Delete', (tester) async {
+ await open(
+ tester,
+ route: (_) => doc(3, 'Rules.', notes: notes),
+ role: 'viewer',
+ );
+ expect(find.text('Do not use Codex.'), findsOneWidget);
+ expect(remove, findsNothing);
+ });
+
+ testWidgets('a refusal says why and keeps the note', (tester) async {
+ await open(
+ tester,
+ route: (_) => doc(3, 'Rules.', notes: notes),
+ commands: (_) => throw const SuperTabFailure(
+ 'NOT_FOUND',
+ 'This note is unavailable.',
+ statusCode: 404,
+ ),
+ );
+ await tester.tap(remove);
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Delete').last);
+ await tester.pumpAndSettle();
+ expect(find.text('This note is unavailable.'), findsOneWidget);
+ expect(find.text('Do not use Codex.'), findsOneWidget);
+ });
+ });
}
diff --git a/mobile/test/swarm/swarm_instructions_shots_test.dart b/mobile/test/swarm/swarm_instructions_shots_test.dart
new file mode 100644
index 000000000..b8b61859c
--- /dev/null
+++ b/mobile/test/swarm/swarm_instructions_shots_test.dart
@@ -0,0 +1,154 @@
+import 'dart:convert';
+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_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/theme/color_palette.dart';
+import 'package:harness_mobile/swarm/swarm_instructions_page.dart';
+import 'package:harness_mobile/swarm/swarm_reader.dart';
+import 'package:harness_mobile/terminal/terminal_font_store.dart';
+
+import 'swarm_fixture.dart';
+
+/// Review screenshots of Delete on a note (Tony's list, task 13), on a
+/// 390-point phone in both phone themes, from made-up data only, to the folder
+/// `SWARM_INSTRUCTIONS_SHOTS` names.
+final shots = Platform.environment['SWARM_INSTRUCTIONS_SHOTS'];
+void main() {
+ setUpAll(() async {
+ if (shots == null || !Platform.isMacOS) return;
+ final sf = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in {
+ '.AppleSystemUIFont',
+ 'Roboto',
+ AppFont.sans,
+ ...AppFont.sansFallback,
+ }) {
+ await (FontLoader(family)..addFont(Future.value(sf))).load();
+ }
+ // The tab's title is set in the terminal's face.
+ final mono = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),
+ );
+ final terminal = terminalFontStore.value;
+ for (final family in {
+ '.AppleSystemUIFontMonospaced',
+ 'monospace',
+ AppFont.mono,
+ ...AppFont.monoFallback,
+ terminal.fontFamily,
+ ...terminal.fontFamilyFallback,
+ }) {
+ await (FontLoader(family)..addFont(Future.value(mono))).load();
+ }
+ final manifest =
+ jsonDecode(await rootBundle.loadString('FontManifest.json')) as List;
+ for (final entry in manifest.cast<Map<String, dynamic>>()) {
+ final loader = FontLoader(entry['family'] as String);
+ for (final font in (entry['fonts'] as List).cast<Map>()) {
+ loader.addFont(rootBundle.load(font['asset'] as String));
+ }
+ await loader.load();
+ }
+ });
+
+ testWidgets('pictures of Delete on a note', (tester) async {
+ addTearDown(tester.view.reset);
+ debugDisableShadows = false;
+ tester.view.padding = const FakeViewPadding(top: 47 * 3, bottom: 34 * 3);
+ addTearDown(tester.view.resetPadding);
+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {
+ tester.view
+ ..physicalSize = const Size(390, 844) * 3
+ ..devicePixelRatio = 3;
+ final brightness = palette.brightness;
+ AppTheme.palette.value = palette;
+ AppTheme.brightness.value = brightness;
+ final fake = FakeSwarm();
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad();
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>
+ changes(cursor: 'c2');
+ fake.routes['/api/super-tabs/$tab/projects/$project/instructions'] =
+ (_) => {
+ 'projectId': project,
+ 'revision': 12,
+ 'hash': 'h12',
+ 'text':
+ 'Every request is one task.\n\nReview and test run in '
+ 'parallel. Merge in batches.',
+ 'template': false,
+ 'coordinatorName': 'River',
+ 'notesRevision': 2,
+ 'notes': [
+ {
+ 'id': 'n1',
+ 'text': 'Do not use Codex on machine A.',
+ 'askedBy': me,
+ 'at': DateTime.now()
+ .subtract(const Duration(hours: 2))
+ .toIso8601String(),
+ 'expiresAt': null,
+ },
+ {
+ 'id': 'n2',
+ 'text': 'Ship the phone first this week.',
+ 'askedBy': me,
+ 'at': DateTime.now()
+ .subtract(const Duration(days: 1))
+ .toIso8601String(),
+ 'expiresAt': null,
+ },
+ ],
+ };
+ final reader = SwarmReader(
+ tabId: tab,
+ accountId: me,
+ request: fake.request,
+ );
+ addTearDown(reader.dispose);
+ await tester.runAsync(reader.refresh);
+ final boundary = GlobalKey();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: buildAppTheme(brightness: brightness),
+ home: SwarmInstructionsPage(reader: reader, projectId: project),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ Future<void> capture(String name) async {
+ if (shots == null) return;
+ await tester.runAsync(() async {
+ final image =
+ await (boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 3);
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ await File('$shots/instructions-delete-$name-${brightness.name}.png')
+ .writeAsBytes(png!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+
+ await capture('notes');
+ await tester.tap(
+ find.byKey(const ValueKey('swarm-instructions-delete-n1')),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Delete this note?'), findsOneWidget);
+ await capture('confirm');
+ await tester.tap(find.text('Cancel'));
+ await tester.pumpAndSettle();
+ }
+ debugDisableShadows = true;
+ }, skip: shots == null);
+}
diff --git a/mobile/test/swarm/swarm_kept_test.dart b/mobile/test/swarm/swarm_kept_test.dart
new file mode 100644
index 000000000..0b2433c91
--- /dev/null
+++ b/mobile/test/swarm/swarm_kept_test.dart
@@ -0,0 +1,235 @@
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/swarm/swarm_home_cache.dart';
+import 'package:harness_mobile/swarm/swarm_kept.dart';
+
+class _Key implements SwarmHomeKey {
+ String? value;
+ @override
+ Future<String?> read() async => value;
+ @override
+ Future<void> write(String next) async => value = next;
+ @override
+ Future<void> delete() async => value = null;
+}
+
+/// What a person wrote, kept on the phone: sealed, one account's, and gone with
+/// it (Tony's mobile list, task 25).
+void main() {
+ late Directory dir;
+ late _Key key;
+ late SealedSwarmKeptStore store;
+
+ setUp(() {
+ dir = Directory.systemTemp.createTempSync('swarm-kept');
+ key = _Key();
+ store = SealedSwarmKeptStore(key: key, file: File('${dir.path}/kept.bin'));
+ });
+ tearDown(() => dir.deleteSync(recursive: true));
+
+ const secret = 'the words only I wrote';
+ final state = {
+ 'drafts': [
+ {'tab': 't', 'chat': 'c', 'text': secret},
+ ],
+ 'posts': <Object>[],
+ };
+
+ test('reads back what it kept, for that account', () async {
+ await store.write('me', state);
+ expect((await store.read('me'))?['drafts'], state['drafts']);
+ });
+
+ test('is sealed: the words are not in the file', () async {
+ await store.write('me', state);
+ final raw = String.fromCharCodes(store.file.readAsBytesSync());
+ expect(raw, isNot(contains(secret)));
+ });
+
+ test("another account reads none, and it goes", () async {
+ await store.write('me', state);
+ expect(await store.read('you'), isNull);
+ expect(store.file.existsSync(), isFalse);
+ });
+
+ test('a clear takes the file and the key', () async {
+ await store.write('me', state);
+ await store.clear();
+ expect(store.file.existsSync(), isFalse);
+ expect(key.value, isNull);
+ expect(await store.read('me'), isNull);
+ });
+
+ test('a clear is not undone by a write just before it', () async {
+ final write = store.write('me', state);
+ final clear = store.clear();
+ await Future.wait([write, clear]);
+ expect(store.file.existsSync(), isFalse);
+ expect(await store.read('me'), isNull);
+ });
+
+ test('a damaged file, or a lost key, is none', () async {
+ await store.write('me', state);
+ store.file.writeAsBytesSync([1, 2, 3]);
+ expect(await store.read('me'), isNull);
+ await store.write('me', state);
+ key.value = null;
+ expect(await store.read('me'), isNull);
+ });
+
+ test('the device has one store, so its clears and writes keep one order', () {
+ expect(
+ identical(SealedSwarmKeptStore.device(), SealedSwarmKeptStore.device()),
+ isTrue,
+ );
+ });
+
+ group('SwarmKept', () {
+ late MemorySwarmKeptStore memory;
+
+ Future<SwarmKept> open() async {
+ final kept = SwarmKept(
+ accountId: 'me',
+ store: memory,
+ saveAfter: Duration.zero,
+ );
+ addTearDown(kept.dispose);
+ await kept.ready;
+ return kept;
+ }
+
+ setUp(() => memory = MemorySwarmKeptStore());
+
+ test(
+ 'a draft comes back in the next session, by chat and thread',
+ () async {
+ final first = await open();
+ first.setDraft('t', 'c', null, 'chat words', {'a1': '@Ann'});
+ first.setDraft('t', 'c', 'r', 'thread words');
+ first.setDraft('t', 'other', null, 'other words');
+ await first.flush();
+ final next = await open();
+ expect(next.draft('t', 'c', null)?.text, 'chat words');
+ expect(next.draft('t', 'c', null)?.mentions, {'a1': '@Ann'});
+ expect(next.draft('t', 'c', 'r')?.text, 'thread words');
+ expect(next.draft('u', 'c', null), isNull);
+ },
+ );
+
+ test('an emptied draft leaves', () async {
+ final first = await open();
+ first.setDraft('t', 'c', null, 'words');
+ first.setDraft('t', 'c', null, '');
+ await first.flush();
+ expect((await open()).draft('t', 'c', null), isNull);
+ });
+
+ test('posts come back as kept, and leave when set empty', () async {
+ final first = await open();
+ final post = {
+ 'body': {'operationId': 'op'},
+ 'messageId': 'm',
+ };
+ first.setPosts('t', 'c', null, [post]);
+ await first.flush();
+ expect((await open()).posts('t', 'c', null), [post]);
+ first.setPosts('t', 'c', null, const []);
+ await first.flush();
+ expect((await open()).posts('t', 'c', null), isEmpty);
+ });
+
+ test('a chat or a Swarm dropped takes its own only', () async {
+ final kept = await open();
+ kept
+ ..setDraft('t', 'c', null, 'a')
+ ..setDraft('t', 'c', 'r', 'b')
+ ..setDraft('t', 'd', null, 'c')
+ ..setDraft('u', 'c', null, 'd')
+ ..setPosts('t', 'c', null, [
+ {'messageId': 'm'},
+ ]);
+ kept.dropChat('t', 'c');
+ expect(kept.draft('t', 'c', null), isNull);
+ expect(kept.draft('t', 'c', 'r'), isNull);
+ expect(kept.posts('t', 'c', null), isEmpty);
+ expect(kept.draft('t', 'd', null)?.text, 'c');
+ kept.dropSwarm('t');
+ expect(kept.draft('t', 'd', null), isNull);
+ expect(kept.draft('u', 'c', null)?.text, 'd');
+ await kept.flush();
+ final next = await open();
+ expect(next.draft('t', 'd', null), isNull);
+ expect(next.draft('u', 'c', null)?.text, 'd');
+ });
+
+ test('names the chats it holds in a Swarm', () async {
+ final kept = await open();
+ kept
+ ..setDraft('t', 'c', 'r', 'a')
+ ..setPosts('t', 'd', null, [
+ {'messageId': 'm'},
+ ])
+ ..setDraft('u', 'e', null, 'b');
+ expect(kept.chats('t'), {'c', 'd'});
+ });
+
+ test('keeps the newest drafts and posts past its caps', () async {
+ final kept = await open();
+ for (var i = 0; i <= SwarmKept.maxDrafts; i++) {
+ kept.setDraft('t', 'c$i', null, 'words');
+ }
+ for (var i = 0; i <= SwarmKept.maxPosts; i++) {
+ kept.setPosts('t', 'p$i', null, [
+ {'messageId': 'm$i'},
+ ]);
+ }
+ expect(kept.draft('t', 'c0', null), isNull);
+ expect(kept.draft('t', 'c${SwarmKept.maxDrafts}', null), isNotNull);
+ expect(kept.posts('t', 'p0', null), isEmpty);
+ expect(kept.posts('t', 'p${SwarmKept.maxPosts}', null), isNotEmpty);
+ });
+
+ test('what was written before it read back is not lost', () async {
+ memory.held = {
+ 'drafts': [
+ {'tab': 't', 'chat': 'old', 'text': 'kept'},
+ {'tab': 't', 'chat': 'c', 'text': 'older'},
+ ],
+ 'posts': <Object>[],
+ };
+ final kept = SwarmKept(
+ accountId: 'me',
+ store: memory,
+ saveAfter: Duration.zero,
+ );
+ addTearDown(kept.dispose);
+ kept.setDraft('t', 'c', null, 'newer');
+ await kept.ready;
+ expect(kept.draft('t', 'c', null)?.text, 'newer');
+ expect(kept.draft('t', 'old', null)?.text, 'kept');
+ });
+
+ test('a flush after it closes writes nothing', () async {
+ final kept = SwarmKept(
+ accountId: 'me',
+ store: memory,
+ saveAfter: const Duration(hours: 1),
+ );
+ await kept.ready;
+ kept.dispose();
+ await pumpEventQueue();
+ memory.held = null;
+ await kept.flush();
+ expect(memory.held, isNull);
+ });
+
+ test('with no store, it holds for the session', () async {
+ final kept = SwarmKept(accountId: 'me');
+ addTearDown(kept.dispose);
+ kept.setDraft('t', 'c', null, 'words');
+ expect(kept.loaded, isTrue);
+ expect(kept.draft('t', 'c', null)?.text, 'words');
+ });
+ });
+}
diff --git a/mobile/test/swarm/swarm_no_lead_receipt_shots_test.dart b/mobile/test/swarm/swarm_no_lead_receipt_shots_test.dart
new file mode 100644
index 000000000..30b006efd
--- /dev/null
+++ b/mobile/test/swarm/swarm_no_lead_receipt_shots_test.dart
@@ -0,0 +1,162 @@
+import 'dart:convert';
+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_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/theme/color_palette.dart';
+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+import 'swarm_new_project_fixture.dart';
+
+/// Review screenshots of "Not sent · this chat has no Lead" and Add a Lead's
+/// machine sheet, in both phone themes, from made-up data only, to
+/// `SWARM_NO_LEAD_SHOTS`.
+final shots = Platform.environment['SWARM_NO_LEAD_SHOTS'];
+
+void main() {
+ setUpAll(() async {
+ if (shots == null || !Platform.isMacOS) return;
+ final sf = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFont', 'Roboto']) {
+ await (FontLoader(family)..addFont(Future.value(sf))).load();
+ }
+ final mono = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFontMonospaced', 'monospace']) {
+ await (FontLoader(family)..addFont(Future.value(mono))).load();
+ }
+ final manifest =
+ jsonDecode(await rootBundle.loadString('FontManifest.json')) as List;
+ for (final entry in manifest.cast<Map<String, dynamic>>()) {
+ final loader = FontLoader(entry['family'] as String);
+ for (final font in (entry['fonts'] as List).cast<Map>()) {
+ loader.addFont(rootBundle.load(font['asset'] as String));
+ }
+ await loader.load();
+ }
+ });
+
+ Map<String, dynamic> machine(String id, String name, {bool online = true}) {
+ final m = leadPool(id, name: name);
+ (m['observation'] as Map)['receivedAt'] = DateTime.now()
+ .subtract(Duration(minutes: online ? 0 : 30))
+ .millisecondsSinceEpoch;
+ return m;
+ }
+
+ testWidgets('the no-Lead line and its sheet, in both themes', (tester) async {
+ await tester.binding.setSurfaceSize(const Size(390, 844));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {
+ final brightness = palette.brightness;
+ AppTheme.palette.value = palette;
+ AppTheme.brightness.value = brightness;
+ final fake = FakeSwarm();
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ fake.routes['/api/super-tabs/invitations'] = (_) => <Object>[];
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) {
+ final load = firstLoad(
+ head: headData(
+ projects: [swarmProject(project, 'Mobile', repo: harnessRepo)],
+ ),
+ machines: [
+ machine('mac-1', 'Mac Studio'),
+ machine('mac-2', 'MacBook Pro', online: false),
+ ],
+ );
+ (load['groups'] as List).first['data'] = groupData(
+ leadChat,
+ title: 'Mobile',
+ lastMessageSequence: 1,
+ );
+ return load;
+ };
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>
+ changes(cursor: 'c2');
+ fake.routes['/api/super-tabs/$tab/conversations/$leadChat/messages'] =
+ (_) => {
+ 'messages': [
+ {
+ 'id': 'm1',
+ 'conversationId': leadChat,
+ 'text': 'Who picks this up?',
+ 'sequence': 1,
+ 'author': {'kind': 'person', 'id': me, 'name': 'tony'},
+ 'createdAt': DateTime.now().toUtc().toIso8601String(),
+ },
+ ],
+ 'next': null,
+ };
+ final account = ValueNotifier<String?>(me);
+ final host = SwarmHost(
+ accountId: () => account.value,
+ account: account,
+ request: fake.request,
+ notices: SilentSystemNotices(),
+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm},
+ readMarks: MemoryKeyValueStore(),
+ )..foreground = false;
+ await tester.runAsync(() => host.session!.inbox.refresh());
+ final boundary = GlobalKey();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: buildAppTheme(brightness: brightness),
+ builder: (_, child) => SwarmScope(notifier: host, child: child!),
+ home: const SwarmConversationPage(
+ swarmId: tab,
+ conversationId: leadChat,
+ ),
+ ),
+ ),
+ );
+ for (var i = 0; i < 5; i++) {
+ await tester.runAsync(pumpEventQueue);
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+ Future<void> capture(String name) => tester.runAsync(() async {
+ final image =
+ await (boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 3);
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ await File('$shots/no-lead-$name-${brightness.name}.png')
+ .writeAsBytes(png!.buffer.asUint8List());
+ image.dispose();
+ });
+ expect(find.text('Not sent · this chat has no Lead'), findsOneWidget);
+ await capture('line');
+ await tester.tap(find.byKey(const ValueKey('swarm-receipt-add-lead')));
+ for (var i = 0; i < 6; i++) {
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+ await capture('sheet');
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(seconds: 1));
+ host.dispose();
+ account.dispose();
+ }
+ AppTheme.palette.value = HarnessPalette.graphite;
+ AppTheme.brightness.value = Brightness.dark;
+ }, skip: shots == null);
+}
diff --git a/mobile/test/swarm/swarm_no_lead_receipt_test.dart b/mobile/test/swarm/swarm_no_lead_receipt_test.dart
new file mode 100644
index 000000000..447d14a5e
--- /dev/null
+++ b/mobile/test/swarm/swarm_no_lead_receipt_test.dart
@@ -0,0 +1,347 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/swarm/swarm_conversation.dart';
+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';
+import 'package:harness_mobile/swarm/swarm_message_receipt.dart';
+import 'package:harness_mobile/swarm/swarm_reader.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+import 'swarm_new_project_fixture.dart';
+
+/// "Not sent · this chat has no Lead" under the person's newest message, as
+/// Desktop says it (`message_receipt.dart`), and Add a Lead where the phone can
+/// start one: a project chat, through `lead.start` as a new project does
+/// (Tony's mobile list, task 29).
+void main() {
+ const commands = '/api/super-tabs/$tab/commands';
+ const line = 'Not sent · this chat has no Lead';
+
+ Map<String, dynamic> own(String chat, {bool delivered = false}) => {
+ 'id': 'm1',
+ 'conversationId': chat,
+ 'text': 'Who picks this up?',
+ 'sequence': 1,
+ 'author': {'kind': 'person', 'id': me, 'name': 'tony'},
+ if (delivered)
+ 'deliveries': [
+ {'id': 'd1', 'agentId': 'agent-lead', 'status': 'delivered'},
+ ],
+ 'createdAt': DateTime.now().toUtc().toIso8601String(),
+ };
+
+ Map<String, dynamic> machine(String id, String name, {bool online = true}) {
+ final m = leadPool(id, name: name);
+ (m['observation'] as Map)['receivedAt'] = DateTime.now()
+ .subtract(Duration(minutes: online ? 0 : 30))
+ .millisecondsSinceEpoch;
+ return m;
+ }
+
+ /// A Swarm whose chat [chat] holds the person's message; the project chat
+ /// has a Lead only when [lead]. [kind] makes [chat] a Buddy chat.
+ ({FakeSwarm swarm, SwarmReader reader}) rig({
+ String chat = leadChat,
+ bool lead = false,
+ bool delivered = false,
+ String? kind,
+ String role = 'owner',
+ bool machines = true,
+ FutureOr<Object?> Function(Map<String, dynamic>? body)? command,
+ }) {
+ final fake = FakeSwarm();
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) {
+ final load = firstLoad(
+ head: headData(
+ projects: [swarmProject(project, 'Mobile', repo: harnessRepo)],
+ ),
+ groups: [
+ if (chat != leadChat)
+ {...groupData(chat, agentIds: const []), 'kind': ?kind},
+ ],
+ machines: [
+ if (machines) ...[
+ machine('mac-1', 'Mac Studio'),
+ machine('mac-2', 'MacBook Pro', online: false),
+ ],
+ ],
+ );
+ (load['groups'] as List).first['data'] = groupData(
+ leadChat,
+ title: 'Mobile',
+ agentIds: lead ? const ['agent-lead'] : const [],
+ leadId: lead ? 'agent-lead' : null,
+ lastMessageSequence: chat == leadChat ? 1 : 0,
+ );
+ load['members'] = [part(me, 1, person(me, role: role))];
+ return load;
+ };
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');
+ fake.routes['/api/super-tabs/$tab/conversations/$chat/messages'] = (_) => {
+ 'messages': [own(chat, delivered: delivered)],
+ 'next': null,
+ };
+ fake.routes[commands] = command ?? (_) => {'result': <String, Object>{}};
+ final reader = SwarmReader(
+ tabId: tab,
+ accountId: me,
+ request: fake.request,
+ );
+ addTearDown(reader.dispose);
+ return (swarm: fake, reader: reader);
+ }
+
+ Future<SwarmConversation> show(
+ WidgetTester tester,
+ ({FakeSwarm swarm, SwarmReader reader}) r, {
+ String chat = leadChat,
+ }) async {
+ late SwarmConversation c;
+ await tester.runAsync(() async {
+ await r.reader.refresh();
+ c = SwarmConversation(r.reader, chat);
+ await c.load();
+ });
+ addTearDown(() {
+ try {
+ c.dispose();
+ } on FlutterError catch (_) {}
+ });
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: ListenableBuilder(
+ listenable: c,
+ builder: (_, _) => switch (c.latestOwn) {
+ final m? => SwarmMessageReceipt(conversation: c, message: m),
+ null => const SizedBox.shrink(),
+ },
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ return c;
+ }
+
+ List<Map<String, dynamic>> starts(FakeSwarm swarm) => [
+ for (final call in swarm.calls)
+ if (call.method == 'POST' &&
+ call.path == commands &&
+ (call.body!['command'] as Map)['type'] == 'lead.start')
+ call.body!,
+ ];
+
+ Finder addLead() => find.byKey(const ValueKey('swarm-receipt-add-lead'));
+
+ group('the line', () {
+ testWidgets('a project chat with no Lead says so, with Add a Lead', (
+ tester,
+ ) async {
+ await show(tester, rig());
+ expect(find.text(line), findsOneWidget);
+ expect(find.text('Add a Lead'), findsOneWidget);
+ });
+
+ testWidgets('none where the chat has its Lead', (tester) async {
+ await show(tester, rig(lead: true));
+ expect(find.text(line), findsNothing);
+ });
+
+ testWidgets('none for a message that went to someone', (tester) async {
+ await show(tester, rig(delivered: true));
+ expect(find.text(line), findsNothing);
+ });
+
+ testWidgets('none in a Buddy chat: its Buddy takes the message', (
+ tester,
+ ) async {
+ await show(
+ tester,
+ rig(chat: 'b1', kind: 'buddy'),
+ chat: 'b1',
+ );
+ expect(find.text(line), findsNothing);
+ });
+
+ testWidgets('a task chat says so, with nothing the phone cannot do', (
+ tester,
+ ) async {
+ await show(tester, rig(chat: 'g1', lead: true), chat: 'g1');
+ expect(find.text(line), findsOneWidget);
+ expect(addLead(), findsNothing);
+ });
+
+ testWidgets('a viewer reads it, and cannot add one', (tester) async {
+ final r = rig(role: 'viewer');
+ await show(tester, r);
+ expect(find.text(line), findsOneWidget);
+ await tester.tap(addLead(), warnIfMissed: false);
+ await tester.pumpAndSettle();
+ expect(find.text('Mac Studio'), findsNothing);
+ expect(starts(r.swarm), isEmpty);
+ });
+ });
+
+ group('Add a Lead', () {
+ testWidgets('lists the machines, and one starts the Lead there', (
+ tester,
+ ) async {
+ final r = rig();
+ await show(tester, r);
+ await tester.tap(addLead());
+ await tester.pumpAndSettle();
+ expect(find.text('Mac Studio'), findsOneWidget);
+ expect(find.text('MacBook Pro'), findsOneWidget);
+ // Offline: listed, and not picked; the sheet stays.
+ await tester.tap(find.text('MacBook Pro'));
+ await tester.pumpAndSettle();
+ expect(starts(r.swarm), isEmpty);
+ await tester.tap(find.text('Mac Studio'));
+ await tester.runAsync(pumpEventQueue);
+ await tester.pumpAndSettle();
+ final command = starts(r.swarm).single['command'] as Map;
+ expect(command, {
+ 'type': 'lead.start',
+ 'projectId': project,
+ 'machineId': 'mac-1',
+ 'engine': 'claude',
+ 'repositoryUrl': harnessRepo,
+ });
+ });
+
+ Future<void> pick(WidgetTester tester) async {
+ await tester.tap(addLead());
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Mac Studio'));
+ await tester.runAsync(pumpEventQueue);
+ await tester.pumpAndSettle();
+ }
+
+ List<String> receipts(FakeSwarm swarm) => [
+ for (final start in starts(swarm)) start['operationId'] as String,
+ ];
+
+ testWidgets('a lost answer, tried again, is the same start', (
+ tester,
+ ) async {
+ var lost = true;
+ final r = rig(
+ command: (_) => lost
+ ? throw const SuperTabFailure(
+ 'MACHINE_UNAVAILABLE',
+ 'No computer answered.',
+ statusCode: 503,
+ )
+ : {'result': <String, Object>{}},
+ );
+ await show(tester, r);
+ await pick(tester);
+ expect(find.text('No computer answered.'), findsOneWidget);
+ lost = false;
+ await pick(tester);
+ final [first, again] = receipts(r.swarm);
+ expect(again, first);
+ expect(find.text('No computer answered.'), findsNothing);
+ });
+
+ testWidgets('after a refusal, the next try is a new start', (tester) async {
+ final r = rig(
+ command: (_) => throw const SuperTabFailure(
+ 'MACHINE_BUSY',
+ 'Mac Studio has no room for another agent.',
+ statusCode: 409,
+ ),
+ );
+ await show(tester, r);
+ await pick(tester);
+ await pick(tester);
+ final [first, again] = receipts(r.swarm);
+ expect(again, isNot(first));
+ });
+
+ testWidgets('with no machine, it says so and opens no empty sheet', (
+ tester,
+ ) async {
+ final r = rig(machines: false);
+ await show(tester, r);
+ await tester.tap(addLead());
+ await tester.pumpAndSettle();
+ expect(
+ find.text(
+ 'No machine in this Swarm can run a Lead. Add one on Desktop.',
+ ),
+ findsOneWidget,
+ );
+ expect(find.text('Machine'), findsNothing);
+ expect(starts(r.swarm), isEmpty);
+ });
+
+ testWidgets('a refusal says why, in its own words', (tester) async {
+ final r = rig(
+ command: (_) => throw const SuperTabFailure(
+ 'LEAD_STARTING',
+ "This project's Product Manager is already starting.",
+ statusCode: 409,
+ ),
+ );
+ await show(tester, r);
+ await tester.tap(addLead());
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Mac Studio'));
+ await tester.runAsync(pumpEventQueue);
+ await tester.pumpAndSettle();
+ expect(
+ find.text("This project's Product Manager is already starting."),
+ findsOneWidget,
+ );
+ });
+ });
+
+ testWidgets('the chat page draws it under the newest own message', (
+ tester,
+ ) async {
+ final r = rig();
+ r.swarm.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ r.swarm.routes['/api/super-tabs/invitations'] = (_) => <Object>[];
+ final account = ValueNotifier<String?>(me);
+ final host = SwarmHost(
+ accountId: () => account.value,
+ account: account,
+ request: r.swarm.request,
+ notices: SilentSystemNotices(),
+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm},
+ readMarks: MemoryKeyValueStore(),
+ )..foreground = false;
+ addTearDown(host.dispose);
+ await tester.runAsync(() => host.session!.inbox.refresh());
+ await tester.pumpWidget(
+ MaterialApp(
+ builder: (_, child) => SwarmScope(notifier: host, child: child!),
+ home: const SwarmConversationPage(
+ swarmId: tab,
+ conversationId: leadChat,
+ ),
+ ),
+ );
+ for (var i = 0; i < 5; i++) {
+ await tester.runAsync(pumpEventQueue);
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+ expect(find.text(line), findsOneWidget);
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(seconds: 1));
+ });
+}
diff --git a/mobile/test/swarm/swarm_profile_sheet_test.dart b/mobile/test/swarm/swarm_profile_sheet_test.dart
index 62a5386ed..2c021a8b5 100644
--- a/mobile/test/swarm/swarm_profile_sheet_test.dart
+++ b/mobile/test/swarm/swarm_profile_sheet_test.dart
@@ -348,8 +348,13 @@ void main() {
});
/// The text style of the one [text] on screen.
- TextStyle styleOf(WidgetTester tester, String text) =>
- tester.widget<Text>(find.text(text)).style!;
+ TextStyle styleOf(WidgetTester tester, String text) => tester
+ .widget<Text>(
+ find.byWidgetPredicate(
+ (widget) => widget is Text && widget.data == text,
+ ),
+ )
+ .style!;
/// The padding nearest around [finder].
EdgeInsetsGeometry paddingAround(WidgetTester tester, Finder finder) => tester
@@ -394,10 +399,10 @@ void main() {
testWidgets('the title and the name are headings of 17; the status under '
'the name is a caption of 13', (tester) async {
- // A username of its own: the field holding it is not the name.
+ // A chosen username is the name and also appears in its field.
await open(tester, extra: {'username': 'pm'});
- for (final text in ['Your profile', 'person-me']) {
+ for (final text in ['Your profile', 'pm']) {
expect(styleOf(tester, text).fontSize, 17, reason: text);
expect(styleOf(tester, text).fontWeight, FontWeight.w600, reason: text);
}
diff --git a/mobile/test/swarm/swarm_usernames_test.dart b/mobile/test/swarm/swarm_usernames_test.dart
index cb0a65d40..01996faed 100644
--- a/mobile/test/swarm/swarm_usernames_test.dart
+++ b/mobile/test/swarm/swarm_usernames_test.dart
@@ -1,5 +1,6 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:harness_mobile/swarm/model.dart';
+import 'package:harness_mobile/swarm/swarm_task_status.dart';
/// How the phone names people for @, as Desktop does: the username the
/// server sends, else (an older server) the email prefix, numbered after the
@@ -33,4 +34,45 @@ void main() {
['ken.n', 'ken.n2', 'ken.n3', 'ken.n4', 'user'],
);
});
+
+ test('task names use the person username and the Desktop fallback', () {
+ SuperTabSnapshot snapshot(List<Map<String, dynamic>> people) =>
+ SuperTabSnapshot.fromJson({
+ 'version': 1,
+ 'id': 'swarm',
+ 'name': 'Swarm',
+ 'ownerId': 'owner',
+ 'people': people,
+ 'agents': const [],
+ 'conversations': const [],
+ 'invitations': const [],
+ });
+
+ String? nameFor(SuperTabSnapshot snapshot, String id) =>
+ swarmTaskPersonName(snapshot)(id);
+
+ expect(
+ nameFor(
+ snapshot([
+ {
+ 'id': 'p1',
+ 'email': '[email protected]',
+ 'role': 'collaborator',
+ 'username': 'kenji',
+ },
+ ]),
+ 'p1',
+ ),
+ 'kenji',
+ );
+ expect(
+ nameFor(
+ snapshot([
+ {'id': 'p1', 'email': '[email protected]', 'role': 'collaborator'},
+ ]),
+ 'p1',
+ ),
+ 'kentest',
+ );
+ });
}
diff --git a/mobile/test/swarm/swarm_work_details_page_test.dart b/mobile/test/swarm/swarm_work_details_page_test.dart
new file mode 100644
index 000000000..c9f2ccd0f
--- /dev/null
+++ b/mobile/test/swarm/swarm_work_details_page_test.dart
@@ -0,0 +1,234 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+import 'package:harness_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;
+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+import 'package:harness_mobile/swarm/swarm_work_details_page.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+
+/// A task's Work details on the phone (Tony's mobile list, task 31): from the
+/// chat's ⋮, where Desktop's chat menu has it, a read-only page of the task's
+/// brief, its linked steps, who has it, each acceptance check with its
+/// evidence, and the result (desktop `work_details.dart`).
+void main() {
+ const chat = 'g1';
+ const brief =
+ 'Goal:\nPeople signed out on a phone get sent back to sign-in in a loop.\n\n'
+ 'Changes:\nKeep the session through the redirect.\n\n'
+ 'Constraints:\nNo new dependency.';
+ const refused = SuperTabFailure(
+ 'FORBIDDEN',
+ 'You cannot read this Swarm.',
+ statusCode: 403,
+ );
+
+ Map<String, dynamic> task({String text = brief}) => {
+ ...groupData(
+ chat,
+ title: 'Fix the login loop',
+ number: 14,
+ status: 'review',
+ agentIds: ['agent-builder'],
+ ),
+ 'brief': text,
+ 'checks': [
+ {
+ 'id': 'check-1',
+ 'description': 'The new test fails on main and passes',
+ 'evidence': 'Failed at abc123, passes at def456.',
+ 'passedBy': 'agent-builder',
+ },
+ {'id': 'check-2', 'description': 'Tried on a real phone'},
+ ],
+ 'assignment': {
+ 'id': 'attempt-$chat',
+ 'agentId': 'agent-builder',
+ 'status': 'review',
+ 'result': 'PR 12 at def456.',
+ },
+ };
+
+ Map<String, dynamic> step() => {
+ ...groupData(
+ 'g2',
+ title: 'Review: PR 12',
+ number: 15,
+ status: 'done',
+ workerId: 'agent-lead',
+ ),
+ 'reviewOf': chat,
+ 'step': 'Review',
+ 'checks': [
+ {'id': 'check-r', 'description': 'Reads well', 'passedBy': 'agent-lead'},
+ ],
+ };
+
+ FakeSwarm backend(List<Map<String, dynamic>> groups) {
+ final fake = FakeSwarm();
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) =>
+ firstLoad(groups: groups);
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');
+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {
+ 'decisions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {
+ 'mentions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$tab/conversations'] = (_) => {
+ 'messages': <Object>[],
+ 'next': null,
+ };
+ return fake;
+ }
+
+ Future<SwarmHost> pump(
+ WidgetTester tester,
+ FakeSwarm fake, {
+ String conversationId = chat,
+ }) async {
+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm};
+ final account = ValueNotifier<String?>(me);
+ final host = SwarmHost(
+ accountId: () => account.value,
+ account: account,
+ request: fake.request,
+ upload: refuseSwarmUpload,
+ notices: SilentSystemNotices(),
+ features: features,
+ )..foreground = false;
+ addTearDown(host.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ builder: (context, child) => SwarmScope(notifier: host, child: child!),
+ home: SwarmConversationPage(
+ swarmId: tab,
+ conversationId: conversationId,
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return host;
+ }
+
+ Finder key(String value) => find.byKey(ValueKey(value));
+
+ Future<void> openDetails(WidgetTester tester) async {
+ await tester.tap(key('swarm-chat-menu'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Work details'));
+ await tester.pumpAndSettle();
+ }
+
+ testWidgets('⋮ → Work details shows the brief, the linked step, who has it, '
+ 'each check with its evidence, and the result', (tester) async {
+ await pump(tester, backend([task(), step()]));
+ await openDetails(tester);
+
+ final page = find.byType(SwarmWorkDetailsPage);
+ expect(page, findsOneWidget);
+ Finder on(String text) =>
+ find.descendant(of: page, matching: find.textContaining(text));
+ expect(on('Fix the login loop'), findsWidgets);
+ expect(on('Goal:'), findsOneWidget);
+ expect(on('sent back to sign-in in a loop'), findsOneWidget);
+ expect(on('Changes:'), findsOneWidget);
+ expect(on('Keep the session through the redirect.'), findsOneWidget);
+ expect(on('Constraints:'), findsOneWidget);
+ expect(on('No new dependency.'), findsOneWidget);
+ expect(on('Review (River): passed'), findsOneWidget);
+ expect(on('Nova · review'), findsOneWidget);
+ expect(on('Acceptance checks'), findsOneWidget);
+ expect(on('The new test fails on main and passes'), findsOneWidget);
+ expect(on('Failed at abc123, passes at def456.'), findsOneWidget);
+ expect(on('Tried on a real phone'), findsOneWidget);
+ expect(
+ find.descendant(of: page, matching: find.text('Verified')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: page, matching: find.text('Not verified')),
+ findsOneWidget,
+ );
+ expect(on('Result'), findsOneWidget);
+ expect(on('PR 12 at def456.'), findsOneWidget);
+ // Read only: the phone records no check.
+ expect(on('Record check'), findsNothing);
+ expect(
+ find.descendant(of: page, matching: find.byType(TextField)),
+ findsNothing,
+ );
+ });
+
+ testWidgets('a task with no brief says so, as Desktop does', (tester) async {
+ await pump(tester, backend([task(text: '')]));
+ await openDetails(tester);
+
+ expect(find.text('This task has no description yet.'), findsOneWidget);
+ expect(find.text('Goal:'), findsNothing);
+ });
+
+ testWidgets('offered where Desktop offers it: a task chat, never a private '
+ "conversation, a project's own chat or a Buddy chat", (tester) async {
+ final private = {
+ ...groupData('p1', title: 'Just us', audience: [me]),
+ };
+ final host = await pump(
+ tester,
+ backend([task(), private, buddyChatData('b1')]),
+ );
+ final reader = host.session!.inbox.reader(tab)!;
+
+ expect(swarmHasWorkDetails(reader, chat), isTrue);
+ expect(swarmHasWorkDetails(reader, 'p1'), isFalse);
+ expect(swarmHasWorkDetails(reader, leadChat), isFalse);
+ expect(swarmHasWorkDetails(reader, 'b1'), isFalse);
+ expect(swarmHasWorkDetails(reader, 'gone'), isFalse);
+
+ await tester.pumpWidget(const SizedBox());
+ await tester.pumpAndSettle();
+ });
+
+ testWidgets('no Work details row in a private conversation’s ⋮', (
+ tester,
+ ) async {
+ final private = {
+ ...groupData('p1', title: 'Just us', audience: [me]),
+ };
+ await pump(tester, backend([private]), conversationId: 'p1');
+ await tester.tap(key('swarm-chat-menu'));
+ await tester.pumpAndSettle();
+
+ expect(find.text('Work details'), findsNothing);
+ });
+
+ testWidgets('access lost while it is open: the page goes', (tester) async {
+ final fake = backend([task()]);
+ final host = await pump(tester, fake);
+ await openDetails(tester);
+ expect(find.byType(SwarmWorkDetailsPage), findsOneWidget);
+
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => throw refused;
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => throw refused;
+ unawaited(host.session!.inbox.reader(tab)!.refresh());
+ await tester.pumpAndSettle();
+
+ expect(find.byType(SwarmWorkDetailsPage), findsNothing);
+ expect(find.text('No new dependency.'), findsNothing);
+ });
+}
diff --git a/mobile/test/swarm/swarm_work_details_shots_test.dart b/mobile/test/swarm/swarm_work_details_shots_test.dart
new file mode 100644
index 000000000..749265164
--- /dev/null
+++ b/mobile/test/swarm/swarm_work_details_shots_test.dart
@@ -0,0 +1,196 @@
+import 'dart:convert';
+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_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/theme/color_palette.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';
+import 'package:harness_mobile/terminal/terminal_font_store.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+
+/// Review screenshots of a task's Work details on the phone (Tony's mobile
+/// list, task 31): the chat's ⋮ with Work details, and the page. On a
+/// 390-point phone in both phone themes, from made-up data only, to the folder
+/// `SWARM_WORK_DETAILS_SHOTS` names.
+final shots = Platform.environment['SWARM_WORK_DETAILS_SHOTS'];
+void main() {
+ setUpAll(() async {
+ if (shots == null || !Platform.isMacOS) return;
+ final sf = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in {
+ '.AppleSystemUIFont',
+ 'Roboto',
+ AppFont.sans,
+ ...AppFont.sansFallback,
+ }) {
+ await (FontLoader(family)..addFont(Future.value(sf))).load();
+ }
+ // The tab's title is set in the terminal's face.
+ final mono = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),
+ );
+ final terminal = terminalFontStore.value;
+ for (final family in {
+ '.AppleSystemUIFontMonospaced',
+ 'monospace',
+ AppFont.mono,
+ ...AppFont.monoFallback,
+ terminal.fontFamily,
+ ...terminal.fontFamilyFallback,
+ }) {
+ await (FontLoader(family)..addFont(Future.value(mono))).load();
+ }
+ final manifest =
+ jsonDecode(await rootBundle.loadString('FontManifest.json')) as List;
+ for (final entry in manifest.cast<Map<String, dynamic>>()) {
+ final loader = FontLoader(entry['family'] as String);
+ for (final font in (entry['fonts'] as List).cast<Map>()) {
+ loader.addFont(rootBundle.load(font['asset'] as String));
+ }
+ await loader.load();
+ }
+ });
+
+ testWidgets('the chat menu and Work details, in both phone themes', (
+ tester,
+ ) async {
+ addTearDown(tester.view.reset);
+ debugDisableShadows = false;
+ tester.view.padding = const FakeViewPadding(top: 47 * 3, bottom: 34 * 3);
+ addTearDown(tester.view.resetPadding);
+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {
+ const size = Size(390, 844);
+ tester.view
+ ..physicalSize = size * 3
+ ..devicePixelRatio = 3;
+ final brightness = palette.brightness;
+ AppTheme.palette.value = palette;
+ AppTheme.brightness.value = brightness;
+ final fake = FakeSwarm();
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'Autonomous', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => firstLoad(
+ groups: [
+ {
+ ...groupData(
+ 'g1',
+ title: 'Fix the login loop',
+ number: 14,
+ status: 'review',
+ agentIds: ['agent-builder'],
+ ),
+ 'brief':
+ 'Goal:\nPeople signed out on a phone get sent back to '
+ 'sign-in in a loop.\n\nChanges:\nKeep the session through '
+ 'the redirect.\n\nConstraints:\nNo new dependency.',
+ 'checks': [
+ {
+ 'id': 'c1',
+ 'description': 'The new test fails on main and passes',
+ 'evidence': 'Failed at abc123, passes at def456.',
+ 'passedBy': 'agent-builder',
+ },
+ {'id': 'c2', 'description': 'Tried on a real phone'},
+ ],
+ 'assignment': {
+ 'id': 'attempt-g1',
+ 'agentId': 'agent-builder',
+ 'status': 'review',
+ 'result': 'PR 12 at def456.',
+ },
+ },
+ {
+ ...groupData(
+ 'g2',
+ title: 'Review: PR 12',
+ number: 15,
+ status: 'done',
+ workerId: 'agent-lead',
+ ),
+ 'reviewOf': 'g1',
+ 'step': 'Review',
+ 'checks': [
+ {'id': 'r1', 'description': 'Reads well', 'passedBy': 'x'},
+ ],
+ },
+ ],
+ );
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>
+ changes(cursor: 'c2');
+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {
+ 'decisions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {
+ 'mentions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$tab/conversations/g1/messages'] = (_) => {
+ 'messages': <Object>[],
+ 'next': null,
+ };
+ final account = ValueNotifier<String?>(me);
+ final host = SwarmHost(
+ accountId: () => me,
+ account: account,
+ request: fake.request,
+ notices: SilentSystemNotices(),
+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm},
+ )..foreground = false;
+ final boundary = GlobalKey();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: buildAppTheme(brightness: brightness),
+ builder: (_, child) => SwarmScope(notifier: host, child: child!),
+ home: const Scaffold(
+ body: SwarmConversationPage(swarmId: tab, conversationId: 'g1'),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ Future<void> capture(String name) async {
+ if (shots == null) return;
+ await tester.runAsync(() async {
+ final image =
+ await (boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 3);
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ await File('$shots/work-details-390-$name-${brightness.name}.png')
+ .writeAsBytes(png!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+
+ await tester.tap(find.byKey(const ValueKey('swarm-chat-menu')));
+ await tester.pumpAndSettle();
+ expect(find.text('Work details'), findsOneWidget);
+ await capture('menu');
+ await tester.tap(find.text('Work details'));
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('swarm-work-details')), findsOneWidget);
+ await capture('page');
+ await tester.pumpWidget(const SizedBox());
+ host.dispose();
+ }
+ debugDisableShadows = true;
+ }, skip: shots == null);
+}