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.

Phone: send Swarm writes directly with phone sign-in (#2701)

harness-for-autonomous[bot]10c090a4521b
diff --git a/docs/plans/2026-11-03-phone-direct-swarm-writes-plan.md b/docs/plans/2026-11-03-phone-direct-swarm-writes-plan.md
new file mode 100644
index 000000000..9b77d74d7
--- /dev/null
+++ b/docs/plans/2026-11-03-phone-direct-swarm-writes-plan.md
@@ -0,0 +1,82 @@
+# Phone Direct Swarm Writes Implementation Plan
+
+> **For agentic workers:** Implement this plan task by task in the current Harness session, test first. Commit each failing test before its implementation; use independent whole-branch review and simulator testing when ready.
+
+**Goal:** A signed-in person can post and answer a Swarm decision from the phone while all their machines are offline, with retries retaining the same operation ID.
+
+**Architecture:** Reuse the phone API client's bearer authentication, refresh interceptor and Swarm response parser for POST requests. AppNotifier tries the backend before selecting a machine; write access refusals stand, while transport failures and server unavailability may fall back to the existing machine path with the unchanged body. Keep machine-specific requests and terminal transport as they are.
+
+**Tech Stack:** Flutter 3.47.2, Dart, Dio, flutter_test, existing in-memory account/socket fixtures.
+
+**Spec:** Swarm task #2303, “Phone: Swarm commands go straight to the server with the phone's own sign-in (Huy),” conversation `b847053227ae321848ae8b5d`; supporting API/state paths approved by the PM.
+
+## Global Constraints
+
+- Phone package only, plus this plan: no backend, terminal, notification or polling changes.
+- Never install on a phone or contact real accounts in tests; run on Tony's Mac with memory authentication and fake HTTP/sockets.
+- Preserve the supplied command body and operation ID through bearer refresh, machine fallback and user retry.
+- Direct write failures about authentication, access, rate limits or invalid input must not gain access through a machine.
+- Two independent security reviews (sign-in, tokens, access), simulator testing, red/green evidence in a PR comment and green CI before completion.
+- PR body starts with: Requested by [email protected] through Harness.
+- Stop only owned processes by ID; temporary files go in a directory created with mktemp -d; install nothing system-wide.
+
+## Design
+
+- Growth: No new persistent data; existing server retention and operation receipts apply.
+- Concurrency: Existing server command transaction and operation-ID deduplication remain authoritative; client retries reuse the request.
+- Read cost: No new reads or polling; reuse current refresh behavior after writes.
+- Scale: Same one POST per write, with at most one bearer refresh and existing bounded machine fallback; direct failure frequency/latency warns first at 10x traffic.
+- Compatibility: Existing backend routes and wire bodies; machine fallback remains for unavailable direct transport. Machine-specific operations still require a machine.
+- Migration + rollback: No schema migration; reverting mobile transport restores machine forwarding.
+- Audience: Backend membership and decision-target checks enforce access; definitive direct refusals never fall back.
+- Identity: Phone bearer identifies the signed-in person; no machine-owner login or identity field is substituted.
+- Failure: Preserve backend refusal details; discard replies and prevent fallback after account changes; existing UI displays unconfirmed sends and offers retry.
+- Platforms: iOS and Android share the Dart transport; test on Tony's Mac and an iPhone simulator, never a real phone.
+
+## Review Focus
+
+- A token refresh must retain the exact command and operation ID and never log credentials or message bodies.
+- A backend access/authentication refusal must not trigger a machine fallback with different privileges.
+- A reply or failure after account change must be discarded before fallback can write for a new account.
+- A lost direct reply followed by fallback or user retry must retain one operation ID; idempotence remains server-enforced.
+- A direct request must remain on the configured backend, refuse redirects, and leave machine-specific/terminal operations untouched.
+
+## Validation Plan
+
+Run focused API and Swarm transport tests for each red/green cycle, then the complete mobile Flutter suite once (two workers on this shared Mac, bounded to 15 minutes), targeted static analysis and the Swarm style check. Automatic ready-PR CI supplies the Linux component/process checks; no manual CI runs. No backend suite is required because backend code is unchanged. Independent reviewers inspect source and evidence; a Tester runs the offline post/decision flows in the simulator. Record implementation, validation, review/CI waiting and handoff durations separately; the PM owns merge/publication.
+
+### Task 1: Authenticated direct Swarm POST transport
+
+**Files:**
+- Modify: `mobile/lib/api/api_client.dart`
+- Test: `mobile/test/api/api_client_test.dart`
+
+**Interfaces:**
+- Consume: existing `AccessTokenSource`, `BearerAuthInterceptor`, Dio adapter and Swarm envelope semantics.
+- Produce: `Future<Object?> ApiClient.swarmWrite(String path, {Map<String, dynamic>? body, CancelToken? cancel})`, POST only, signed with the phone bearer, unchanged JSON, no cross-host or redirect forwarding; retain `swarmRead(String path)` for current consumers.
+
+- [ ] Add and commit failing API tests: POST message and decision payloads use the phone bearer/environment; 401 refresh replays identical JSON/operation ID with the refreshed token; missing credentials make no HTTP request; access failures retain code/status; redirects are refused; foreign absolute paths are rejected; tokens and private text stay out of logs.
+- [ ] Run `flutter test --no-pub --concurrency=2 --timeout=60s test/api/api_client_test.dart`; observe the new transport tests fail before adding production code.
+- [ ] Add `swarmWrite`, reuse the existing envelope decoder, and disable redirects for writes. Keep the shared bearer interceptor unchanged.
+- [ ] Run the API tests and commit the passing implementation; push both commits to the draft PR.
+
+### Task 2: Direct-first routing and offline phone actions
+
+**Files:**
+- Modify: `mobile/lib/state/app_state.dart`
+- Modify: `mobile/lib/swarm/swarm_outbox.dart` (transport documentation)
+- Modify: `mobile/README.md`
+- Test: `mobile/test/swarm/swarm_request_test.dart`
+- Create: `mobile/test/swarm/swarm_direct_writes_test.dart`
+
+**Interfaces:**
+- Consume: Task 1 `ApiClient.swarmWrite`, `AppNotifier.swarmRequest(String method, String path, {Map<String, dynamic>? body})`, existing `SwarmConversation`/`SwarmAsks` request injection and operation receipts.
+- Produce: same `SwarmRequest` contract; GET behavior unchanged, POST uses direct transport first, machine forwarding retains body and operation ID after unavailable transport/server responses.
+
+- [ ] Add and commit failing tests using a real ApiClient with an in-process HTTP adapter and an in-memory AppNotifier: post and decision answer with all account machines disconnected; lost response then retry retains operation ID; network/5xx fallback carries the same JSON; 400/401/403/404/426/429 refusals never reach a machine; sign-out during held success/failure drops it with no fallback; non-command writes use direct POST too.
+- [ ] Replace the old test asserting commands always use a machine with the new direct-first expectation; preserve existing GET/machine tests.
+- [ ] Run `flutter test --no-pub --concurrency=2 --timeout=60s test/swarm/swarm_direct_writes_test.dart test/swarm/swarm_request_test.dart`; record expected failures.
+- [ ] Try `swarmWrite` for POST before selecting a machine. Cancel in-flight writes on account invalidation to prevent bearer refresh after sign-out. Check the original authentication revision after each asynchronous direct result and before fallback; allow write fallback only for transport/server unavailability. Preserve GET fallback policy and machine-local requests.
+- [ ] Update README to describe direct signed-in reads/writes, bounded machine fallback and unchanged encrypted terminal transport; update stale transport comments.
+- [ ] Run focused tests, the complete mobile suite and targeted analysis/style validation; commit passing code and push.
+- [ ] Record red/green evidence in a PR comment, mark Ready, keep head stable, route two independent security reviews and a simulator Tester, then record passed acceptance checks and hand off to the PM.
diff --git a/mobile/README.md b/mobile/README.md
index 493a63212..35134129c 100644
--- a/mobile/README.md
+++ b/mobile/README.md
@@ -66,11 +66,15 @@ resolves the swarm’s harnesses for navigation.
`lib/swarm/` brings a Swarm (the desktop's collaborative tab, not the desk groups above) to the
phone: what needs the person first (decisions, the Product Manager's tags, work waiting on them),
the Swarms and their projects, a project's conversations, posting with @mentions, and decisions
-answered with one tap. The phone has no backend route of its own for it: every read and command
-goes to the Swarm read API through one of the account's machines (`AppNotifier.swarmRequest`,
-the `super_tabs` relay request, end-to-end encrypted), so who can read what is the backend's
-answer, the same as on the desktop. `model.dart` and `parts.dart` are copies of the desktop's,
-held to them by `test/swarm/desktop_parity_test.dart`.
+answered with one tap. Reads and writes go straight to the backend using the phone's own sign-in
+(`AppNotifier.swarmRequest`), so posting and answering decisions work while every account machine
+is offline. Command retries keep the same operation ID, including after a bearer refresh or a
+fallback through an account machine (`super_tabs`, end-to-end encrypted). Writes fall back only
+when the direct transport or server is unavailable; authentication, access and rate-limit refusals
+stand. The backend enforces what the signed-in person may read and change. Operations that run on
+a computer still need that computer, and regular terminals keep their end-to-end encrypted path
+through the machine. `model.dart` and `parts.dart` are copies of the desktop's, held to them by
+`test/swarm/desktop_parity_test.dart`.
- **Cost.** One `SwarmSession` per signed-in account while Swarm is on. In the foreground it reads
what needs the person every 15 seconds, and an open Swarm's changes (first load, then `/changes`)
diff --git a/mobile/lib/api/api_client.dart b/mobile/lib/api/api_client.dart
index 07403a0a5..dec4a3e16 100644
--- a/mobile/lib/api/api_client.dart
+++ b/mobile/lib/api/api_client.dart
@@ -343,7 +343,7 @@ class ApiClient {
final data = unwrapApiResponse(res) as Map<String, dynamic>;
return (data['transcript'] as String? ?? '').trim();
}
- // -- Swarm reads (the viewer's own session signs them) --
+ // -- Swarm requests (the viewer's own session signs them) --
/// One read of the Swarm ([path], `/api/super-tabs…`), straight from the
/// backend with this viewer's own sign-in, as the web build reads it
@@ -354,6 +354,37 @@ class ApiClient {
/// transport threw.
Future<Object?> swarmRead(String path) async {
final response = await _dio.get<dynamic>(path);
+ return _swarmValue(response);
+ }
+
+ /// A Swarm write signed by this phone. Keep [body], including its operation
+ /// ID, unchanged through bearer refresh and caller retries. The caller cancels
+ /// it on account change, preventing a refresh from replaying for a new account.
+ /// Never forward a command or its bearer to a redirect or another origin.
+ Future<Object?> swarmWrite(
+ String path, {
+ Map<String, dynamic>? body,
+ CancelToken? cancel,
+ }) async {
+ final uri = Uri.parse(path);
+ if (uri.hasScheme ||
+ uri.hasAuthority ||
+ !uri.path.startsWith('/api/super-tabs/') ||
+ uri.pathSegments.any((segment) => segment == '.' || segment == '..') ||
+ uri.hasQuery ||
+ uri.hasFragment) {
+ throw ArgumentError.value(path, 'path', 'Expected a Swarm backend path');
+ }
+ final response = await _dio.post<dynamic>(
+ path,
+ data: body,
+ cancelToken: cancel,
+ options: Options(followRedirects: false),
+ );
+ return _swarmValue(response);
+ }
+
+ static Object? _swarmValue(Response<dynamic> response) {
final status = response.statusCode ?? 0;
var body = response.data;
if (body is String) {
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index b7e3d7205..bf0d48d1a 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -569,6 +569,10 @@ class AppNotifier extends ChangeNotifier {
upload.cancel('account changed');
}
_swarmUploadsGoing.clear();
+ for (final write in _swarmWritesGoing) {
+ write.cancel('account changed');
+ }
+ _swarmWritesGoing.clear();
// The copies large chat files were kept in went with the chats that held them.
unawaited(clearSwarmPickerCopies());
_profileInFlight = null;
@@ -6432,9 +6436,14 @@ class AppNotifier extends ChangeNotifier {
/// refuses stands, being about this person; with no answer, or one that says nothing of them
/// ([_swarmReadTriesMachine]), the read goes on through a machine as below.
///
- /// A command, and a read going on, is forwarded by one of the account's own machines with its
- /// session (`super_tabs`, `action: backend`, cli/src/superTabs/service.ts): the machine checks
- /// that this connection is its owner's, and the backend what that account may read.
+ /// Writes also go straight to the backend with the phone's sign-in. Only unavailable transport
+ /// or server responses fall back to a machine; write refusals stand. In-flight writes are
+ /// cancelled on account change, including bearer-refresh retries. The unchanged body keeps
+ /// each command's operation ID across every path.
+ ///
+ /// A fallback uses one of the account's own machines with its session (`super_tabs`,
+ /// `action: backend`, cli/src/superTabs/service.ts): the machine checks that this connection
+ /// is its owner's, and the backend what that account may read or write.
///
/// A refusal is asked again through each other machine that is up, one after another, up to
/// [_swarmAsksPerCall] in all. One that answers shows the refusals before it were those
@@ -6461,17 +6470,17 @@ class AppNotifier extends ChangeNotifier {
String path, {
Map<String, dynamic>? body,
}) async {
- if (method == 'GET') {
- final revision = _authRevision;
- void stillThisAccount() {
- if (!_authWorkCurrent(revision)) {
- throw const SuperTabFailure(
- 'ACCOUNT_CHANGED',
- 'The account changed. Open Swarm again.',
- );
- }
+ final revision = _authRevision;
+ void stillThisAccount() {
+ if (!_authWorkCurrent(revision)) {
+ throw const SuperTabFailure(
+ 'ACCOUNT_CHANGED',
+ 'The account changed. Open Swarm again.',
+ );
}
+ }
+ if (method == 'GET') {
try {
final value = await api.swarmRead(path);
stillThisAccount();
@@ -6486,13 +6495,37 @@ class AppNotifier extends ChangeNotifier {
_swarmReadGoesOn(error);
}
}
+ if (method == 'POST') {
+ final cancel = CancelToken();
+ _swarmWritesGoing.add(cancel);
+ try {
+ final value = await api.swarmWrite(path, body: body, cancel: cancel);
+ stillThisAccount();
+ return value;
+ } on SuperTabFailure catch (refusal) {
+ stillThisAccount();
+ // A write refusal belongs to this person. Never retry an expired
+ // sign-in, denied access or rate limit with a machine's credentials.
+ if (refusal.statusCode != 0 && refusal.statusCode < 500) rethrow;
+ } catch (_) {
+ stillThisAccount();
+ } finally {
+ _swarmWritesGoing.remove(cancel);
+ }
+ appLog.warn(
+ 'swarm',
+ 'Swarm write could not reach the backend, asking a machine',
+ );
+ }
var machine = _swarmMachine() ?? await _swarmMachineBack();
+ stillThisAccount();
if (machine == null) throw _swarmNoComputer();
final asked = <MachineState>{}, refused = <MachineState>[];
SuperTabFailure? lost;
late Object failure;
late StackTrace trace;
while (machine != null) {
+ stillThisAccount();
asked.add(machine);
try {
final value = await _swarmRequestVia(machine, method, path, body);
@@ -6516,6 +6549,7 @@ class AppNotifier extends ChangeNotifier {
? await _swarmMachineBack(except: asked)
: null);
}
+ stillThisAccount();
if (lost != null) throw lost;
if (machine == null &&
failure is SuperTabFailure &&
@@ -6549,7 +6583,7 @@ class AppNotifier extends ChangeNotifier {
}
/// Sends one Swarm chat file to the backend ([SwarmUpload]): straight from this phone with its own
- /// sign-in ([ApiClient.uploadSwarmAttachment]), not through a machine as [swarmRequest] goes — the
+ /// sign-in ([ApiClient.uploadSwarmAttachment]), with no machine fallback — the
/// backend takes a chat file only from the client, and a machine forwards only JSON. An answer
/// that lands after the account changed is dropped, and a sign-out or another sign-in stops the
/// upload where it is ([_invalidateAuthWork]).
@@ -6599,6 +6633,9 @@ class AppNotifier extends ChangeNotifier {
}
}
+ /// JSON writes cancelled before another account can refresh or retry them.
+ final _swarmWritesGoing = <CancelToken>{};
+
/// The chat file uploads of this sign-in on their way ([swarmUpload]).
final _swarmUploadsGoing = <CancelToken>{};
diff --git a/mobile/lib/swarm/swarm_outbox.dart b/mobile/lib/swarm/swarm_outbox.dart
index 49853c423..c831483c0 100644
--- a/mobile/lib/swarm/swarm_outbox.dart
+++ b/mobile/lib/swarm/swarm_outbox.dart
@@ -142,8 +142,9 @@ class SwarmOutbox {
this.timeout = defaultTimeout,
});
- /// A send through the account's computers can take 30 seconds a computer
- /// (`AppNotifier.swarmRequest`): past this one, the post says Not sent and
+ /// A send goes straight to the backend; a fallback through the account's
+ /// computers can take 30 seconds a computer (`AppNotifier.swarmRequest`).
+ /// Past this timeout, the post says Not sent and
/// may be sent again, while its first answer may still land.
static const defaultTimeout = Duration(seconds: 40);
diff --git a/mobile/test/api/api_client_test.dart b/mobile/test/api/api_client_test.dart
index a96da726f..90a7d8f5c 100644
--- a/mobile/test/api/api_client_test.dart
+++ b/mobile/test/api/api_client_test.dart
@@ -1,3 +1,4 @@
+import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
@@ -50,6 +51,7 @@ class _Backend implements HttpClientAdapter {
_Headers(options.headers),
body,
host: options.uri.host,
+ followRedirects: options.followRedirects,
);
final index = requests.length;
requests.add(request);
@@ -76,8 +78,10 @@ class _Request {
this.headers,
this.body, {
this.host = '',
+ this.followRedirects = true,
});
final String method, path, host;
+ final bool followRedirects;
final Map<String, String> query;
final _Headers headers;
final List<int> body;
@@ -225,6 +229,191 @@ void main() {
});
});
+ group('a Swarm write', () {
+ const path = '/api/super-tabs/tab-1/commands';
+ const body = {
+ 'operationId': 'one-command',
+ 'command': {
+ 'type': 'message.send',
+ 'conversationId': 'chat-1',
+ 'text': 'private phone message',
+ },
+ };
+
+ test(
+ 'posts JSON as the phone with its environment and returns the result',
+ () async {
+ backend.answer = (_, _) => (
+ status: 200,
+ body: ok({
+ 'result': {'messageId': 'm1'},
+ }),
+ );
+
+ expect(
+ await client(_Tokens(['phone-token'])).swarmWrite(path, body: body),
+ {
+ 'result': {'messageId': 'm1'},
+ },
+ );
+
+ final request = backend.requests.single;
+ expect(request.method, 'POST');
+ expect(request.path, path);
+ expect(request.host, 'api.invalid');
+ expect(request.headers.value('authorization'), 'Bearer phone-token');
+ expect(request.headers.value('x-autonomous-env'), 'stag');
+ expect(jsonDecode(utf8.decode(request.body)), body);
+ expect(request.followRedirects, isFalse);
+ },
+ );
+
+ test(
+ 'refreshing a bearer retries the same decision and operation ID once',
+ () async {
+ final tokens = _Tokens(['expired-phone-token', 'fresh-phone-token']);
+ backend.answer = (_, i) => i == 0
+ ? (
+ status: 401,
+ body: {
+ 'success': false,
+ 'error': {'code': 'UNAUTHORIZED'},
+ },
+ )
+ : (
+ status: 200,
+ body: ok({
+ 'result': {'answered': true},
+ }),
+ );
+ const answer = {
+ 'operationId': 'one-answer',
+ 'command': {
+ 'type': 'decision.answer',
+ 'decisionId': 'd1',
+ 'choice': 1,
+ },
+ };
+
+ expect(await client(tokens).swarmWrite(path, body: answer), {
+ 'result': {'answered': true},
+ });
+
+ expect(backend.requests, hasLength(2));
+ expect(backend.requests.map((r) => jsonDecode(utf8.decode(r.body))), [
+ answer,
+ answer,
+ ]);
+ expect(backend.requests.map((r) => r.headers.value('authorization')), [
+ 'Bearer expired-phone-token',
+ 'Bearer fresh-phone-token',
+ ]);
+ expect(
+ tokens.asks.where((a) => a.force).single.failedToken,
+ 'expired-phone-token',
+ );
+ },
+ );
+
+ test('with no credentials never writes to the backend', () async {
+ final api = ApiClient(
+ config: const AppConfig(apiBaseUrl: 'https://api.invalid'),
+ session: AuthSession(storage: MemoryKeyValueStore()),
+ httpClientAdapter: backend,
+ );
+ await expectLater(api.swarmWrite(path, body: body), throwsStateError);
+ expect(backend.requests, isEmpty);
+ });
+
+ for (final status in [401, 403, 404, 426, 429, 503]) {
+ test('preserves a backend refusal with status $status', () async {
+ backend.answer = (_, _) => (
+ status: status,
+ body: {
+ 'success': false,
+ 'error': {'code': 'REFUSED', 'message': 'Cannot write here.'},
+ },
+ );
+ await expectLater(
+ client(_Tokens(['token'])).swarmWrite(path, body: body),
+ throwsA(
+ isA<SuperTabFailure>()
+ .having((f) => f.statusCode, 'status', status)
+ .having(
+ (f) => f.code,
+ 'code',
+ status == 426 ? 'UPDATE_REQUIRED' : 'REFUSED',
+ ),
+ ),
+ );
+ });
+ }
+
+ test('a redirect is a refusal with no command body forwarded', () async {
+ backend.answer = (_, _) => (status: 307, body: '<html>Redirect</html>');
+ await expectLater(
+ client(_Tokens(['token'])).swarmWrite(path, body: body),
+ throwsA(
+ isA<SuperTabFailure>().having((f) => f.statusCode, 'status', 307),
+ ),
+ );
+ expect(backend.requests.single.followRedirects, isFalse);
+ });
+
+ test('cancelling an in-flight write prevents a later 401 replay', () async {
+ final tokens = _Tokens(['old-account', 'new-account']);
+ final reached = Completer<void>();
+ final release = Completer<void>();
+ backend.hold = (_, _) async {
+ reached.complete();
+ await release.future;
+ };
+ backend.answer = (_, _) => (status: 401, body: {'success': false});
+ final cancel = CancelToken();
+ final writing = client(tokens)
+ .swarmWrite(path, body: body, cancel: cancel);
+ final stopped = expectLater(writing, throwsA(isA<DioException>()));
+ await reached.future;
+ cancel.cancel('account changed');
+ release.complete();
+ await stopped;
+ await Future<void>.delayed(Duration.zero);
+ expect(backend.requests, hasLength(1));
+ expect(tokens.asks.where((a) => a.force), isEmpty);
+ });
+
+ for (final path in [
+ 'https://elsewhere.invalid/api/super-tabs/t/commands',
+ '//elsewhere.invalid/api/super-tabs/t/commands',
+ '/api/super-tabs/../auth/logout',
+ '/api/super-tabs/%2e%2e/auth/logout',
+ '/api/machines',
+ ]) {
+ test('rejects an unsafe Swarm write path before using credentials: $path', () async {
+ final tokens = _Tokens(['token']);
+ await expectLater(client(tokens).swarmWrite(path, body: body), throwsArgumentError);
+ expect(tokens.asks, isEmpty);
+ expect(backend.requests, isEmpty);
+ });
+ }
+
+ test(
+ 'logs contain neither the bearer nor the private command text',
+ () async {
+ final before = appLog;
+ final log = _Log();
+ appLog = log;
+ addTearDown(() => appLog = before);
+
+ await client(_Tokens(['secret-phone-bearer']))
+ .swarmWrite(path, body: body);
+
+ expect(log.lines.join('\n'), isNot(contains('secret-phone-bearer')));
+ expect(log.lines.join('\n'), isNot(contains('private phone message')));
+ },
+ );
+ });
+
group('signing', () {
test(
'a real API call without credentials fails before transport',
diff --git a/mobile/test/swarm/swarm_direct_writes_test.dart b/mobile/test/swarm/swarm_direct_writes_test.dart
new file mode 100644
index 000000000..70e0cb625
--- /dev/null
+++ b/mobile/test/swarm/swarm_direct_writes_test.dart
@@ -0,0 +1,345 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:typed_data';
+
+import 'package:dio/dio.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/api/access_token_source.dart';
+import 'package:harness_mobile/api/api_client.dart';
+import 'package:harness_mobile/auth/auth_session.dart';
+import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/core/models.dart';
+import 'package:harness_mobile/swarm/swarm_asks.dart';
+import 'package:harness_mobile/swarm/swarm_conversation.dart';
+import 'package:harness_mobile/swarm/swarm_reader.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+
+import '../viewer_app_fixture.dart';
+import '../voice_fakes.dart' show MemoryKeyValueStore;
+import 'swarm_fixture.dart' show changes, firstLoad, groupData, me, tab;
+
+const _commands = '/api/super-tabs/$tab/commands';
+const _post = {
+ 'operationId': 'same-post',
+ 'command': {'type': 'message.send', 'conversationId': 'g1', 'text': 'Hello'},
+};
+
+class _PhoneToken implements AccessTokenSource {
+ @override
+ Future<String> accessToken({bool force = false, String? failedToken}) async =>
+ 'phone-person-token';
+}
+
+/// Only the HTTP boundary is replaced: real API serialization, authentication,
+/// routing, chat outbox and decision retry logic run above it. No real accounts.
+class _Backend implements HttpClientAdapter {
+ final writes = <Map<String, dynamic>>[];
+ final paths = <String>[];
+ final bearers = <Object?>[];
+ FutureOr<({int status, Object? body})> Function(RequestOptions)? onWrite;
+
+ @override
+ Future<ResponseBody> fetch(
+ RequestOptions options,
+ Stream<Uint8List>? stream,
+ Future<void>? cancelFuture,
+ ) async {
+ final bytes = await stream?.fold<List<int>>([], (a, b) => a..addAll(b));
+ Object? data;
+ var status = 200;
+ if (options.method == 'POST') {
+ writes.add(
+ Map<String, dynamic>.from(jsonDecode(utf8.decode(bytes!)) as Map),
+ );
+ paths.add(options.uri.path);
+ bearers.add(options.headers['authorization']);
+ final answer = await onWrite?.call(options);
+ if (answer != null) {
+ return _reply(answer.status, answer.body);
+ }
+ data = {
+ 'result': {'messageId': 'posted-1'},
+ };
+ } else if (options.uri.path.endsWith('/parts')) {
+ data = firstLoad(groups: [groupData('g1')]);
+ } else if (options.uri.path.endsWith('/changes')) {
+ data = changes(cursor: 'c2');
+ } else if (options.uri.path.endsWith('/messages')) {
+ data = {'messages': <Object>[], 'next': null};
+ } else {
+ data = <String, Object?>{};
+ }
+ return _reply(status, {'success': true, 'data': data});
+ }
+
+ ResponseBody _reply(int status, Object? body) => ResponseBody.fromString(
+ jsonEncode(body),
+ status,
+ headers: {
+ Headers.contentTypeHeader: [Headers.jsonContentType],
+ },
+ );
+
+ @override
+ void close({bool force = false}) {}
+}
+
+void main() {
+ Future<({ViewerRig rig, _Backend backend})> phone({
+ bool online = false,
+ }) async {
+ final rig = await signedInWith({'mac': []});
+ addTearDown(rig.app.dispose);
+ if (!online) {
+ rig.app.connectionStatusForTest('mac', ConnectionStatus.disconnected);
+ await settle();
+ }
+ final backend = _Backend();
+ rig.app.api = ApiClient(
+ config: const AppConfig(apiBaseUrl: 'https://phone-backend.invalid'),
+ session: AuthSession(storage: MemoryKeyValueStore()),
+ auth: _PhoneToken(),
+ httpClientAdapter: backend,
+ );
+ return (rig: rig, backend: backend);
+ }
+
+ Future<SwarmReader> reader(ViewerRig rig) async {
+ final reader = SwarmReader(
+ tabId: tab,
+ accountId: me,
+ request: rig.app.swarmRequest,
+ );
+ addTearDown(reader.dispose);
+ await reader.refresh();
+ return reader;
+ }
+
+ test('a chat posts with every account machine offline', () async {
+ final p = await phone();
+ final r = await reader(p.rig);
+ final chat = SwarmConversation(r, 'g1');
+ addTearDown(chat.dispose);
+ await chat.load();
+ chat.draft = 'A message from the offline-machine phone';
+
+ expect(await chat.send(), isTrue);
+ expect(chat.error, isNull);
+ final sent = p.backend.writes.single;
+ expect(
+ sent['operationId'],
+ isA<String>().having((s) => s.isNotEmpty, 'nonempty', isTrue),
+ );
+ expect(sent['command'], containsPair('type', 'message.send'));
+ expect(
+ sent['command'],
+ containsPair('text', 'A message from the offline-machine phone'),
+ );
+ expect(p.backend.bearers, ['Bearer phone-person-token']);
+ expect(p.rig.conn('mac').payloadsOf('super_tabs'), isEmpty);
+ });
+
+ test(
+ 'a decision answer reaches the backend with every machine offline',
+ () async {
+ final p = await phone();
+ final asks = SwarmAsks(await reader(p.rig));
+ addTearDown(asks.dispose);
+ final decision = SuperTabDecision.fromJson({
+ 'id': 'decision-1',
+ 'conversationId': 'g1',
+ 'question': 'Ship?',
+ 'options': ['Yes', 'No'],
+ });
+
+ expect(await asks.answer(decision, 1), isTrue);
+ expect(p.backend.writes.single['command'], {
+ 'type': 'decision.answer',
+ 'decisionId': 'decision-1',
+ 'choice': 1,
+ });
+ expect(p.backend.bearers, ['Bearer phone-person-token']);
+ expect(p.rig.conn('mac').payloadsOf('super_tabs'), isEmpty);
+ await settle();
+ },
+ );
+
+ for (final action in ['post', 'answer']) {
+ test(
+ 'retrying an unconfirmed $action retains its command and operation ID',
+ () async {
+ final p = await phone();
+ var lost = true;
+ p.backend.onWrite = (options) {
+ if (lost) {
+ throw DioException.connectionError(
+ requestOptions: options,
+ reason: 'reply lost',
+ );
+ }
+ return (
+ status: 200,
+ body: {
+ 'success': true,
+ 'data': {
+ 'result': {'messageId': 'posted-1'},
+ },
+ },
+ );
+ };
+ final r = await reader(p.rig);
+ if (action == 'post') {
+ final chat = SwarmConversation(r, 'g1');
+ addTearDown(chat.dispose);
+ await chat.load();
+ chat.draft = 'Send exactly once';
+ expect(await chat.send(), isFalse);
+ lost = false;
+ expect(await chat.send(), isTrue);
+ } else {
+ final asks = SwarmAsks(r);
+ addTearDown(asks.dispose);
+ final decision = SuperTabDecision.fromJson({
+ 'id': 'd1',
+ 'conversationId': 'g1',
+ });
+ expect(await asks.answer(decision, 1), isFalse);
+ lost = false;
+ // A changed tap cannot silently change an answer whose receipt is pending.
+ expect(await asks.answer(decision, 0), isTrue);
+ }
+ expect(p.backend.writes, hasLength(2));
+ expect(p.backend.writes[1], p.backend.writes[0]);
+ expect(p.backend.writes[0]['operationId'], isNotEmpty);
+ expect(p.rig.conn('mac').payloadsOf('super_tabs'), isEmpty);
+ await settle();
+ },
+ );
+ }
+
+ for (final status in [0, 500, 503]) {
+ test(
+ 'unavailable direct write ($status) falls back with the same operation ID',
+ () async {
+ final p = await phone(online: true);
+ p.backend.onWrite = (options) {
+ if (status == 0) {
+ throw DioException.connectionError(
+ requestOptions: options,
+ reason: 'offline',
+ );
+ }
+ return (
+ status: status,
+ body: {
+ 'success': false,
+ 'error': {'code': 'UNAVAILABLE'},
+ },
+ );
+ };
+ p.rig.conn('mac').answers['super_tabs'] = (_) => {
+ 'ok': true,
+ 'value': {
+ 'result': {'messageId': 'from-machine'},
+ },
+ };
+
+ expect(await p.rig.app.swarmRequest('POST', _commands, body: _post), {
+ 'result': {'messageId': 'from-machine'},
+ });
+ expect(p.backend.writes, [_post]);
+ expect(p.rig.conn('mac').payloadsOf('super_tabs').single, {
+ 'action': 'backend',
+ 'method': 'POST',
+ 'path': _commands,
+ 'body': _post,
+ });
+ },
+ );
+ }
+
+ for (final status in [400, 401, 403, 404, 426, 429]) {
+ test(
+ 'a direct write refusal ($status) cannot gain access through a machine',
+ () async {
+ final p = await phone(online: true);
+ p.backend.onWrite = (_) => (
+ status: status,
+ body: {
+ 'success': false,
+ 'error': {'code': 'REFUSED', 'message': 'Cannot write.'},
+ },
+ );
+ p.rig.conn('mac').answers['super_tabs'] = (_) => {
+ 'ok': true,
+ 'value': 'wrong privileges',
+ };
+
+ await expectLater(
+ p.rig.app.swarmRequest('POST', _commands, body: _post),
+ throwsA(
+ isA<SuperTabFailure>().having(
+ (f) => f.statusCode,
+ 'status',
+ status,
+ ),
+ ),
+ );
+ expect(p.rig.conn('mac').payloadsOf('super_tabs'), isEmpty);
+ },
+ );
+ }
+
+ for (final status in [200, 401, 503]) {
+ test(
+ 'sign-out cancels a held write ($status) and forbids fallback or token replay',
+ () async {
+ final p = await phone(online: true);
+ final reached = Completer<void>();
+ final release = Completer<void>();
+ p.backend.onWrite = (_) async {
+ reached.complete();
+ await release.future;
+ return (
+ status: status,
+ body: {
+ 'success': status == 200,
+ 'data': {'result': {}},
+ },
+ );
+ };
+ final writing = p.rig.app.swarmRequest('POST', _commands, body: _post);
+ final stopped = expectLater(
+ writing,
+ throwsA(
+ isA<SuperTabFailure>().having(
+ (f) => f.code,
+ 'code',
+ 'ACCOUNT_CHANGED',
+ ),
+ ),
+ );
+ await reached.future;
+ await p.rig.app.logout();
+ release.complete();
+ await stopped;
+ await settle();
+ expect(p.backend.writes, hasLength(1));
+ expect(p.rig.conn('mac').payloadsOf('super_tabs'), isEmpty);
+ },
+ );
+ }
+
+ test(
+ 'non-command Swarm writes also use the phone while machines are offline',
+ () async {
+ final p = await phone();
+ const path = '/api/super-tabs/$tab/conversations/g1/read';
+ await p.rig.app.swarmRequest('POST', path, body: {'sequence': 42});
+ expect(p.backend.paths, [path]);
+ expect(p.backend.writes, [
+ {'sequence': 42},
+ ]);
+ },
+ );
+}
diff --git a/mobile/test/swarm/swarm_request_test.dart b/mobile/test/swarm/swarm_request_test.dart
index 511157d94..7a2a0565b 100644
--- a/mobile/test/swarm/swarm_request_test.dart
+++ b/mobile/test/swarm/swarm_request_test.dart
@@ -20,8 +20,9 @@ import 'swarm_fixture.dart' show changes, firstLoad, groupData, me, tab;
/// How the phone reaches the Swarm: a read goes straight to the backend with
/// the phone's own sign-in, as the web build's does, and on through a machine
-/// when that says nothing of the person. A command, and a read going on, is
-/// forwarded by one of the account's own machines with its session
+/// when that says nothing of the person. A command uses the phone too, with
+/// a machine fallback for unavailable transport. These fixtures have no write
+/// credentials, so their commands are forwarded by an account machine with its session
/// (`super_tabs`, `action: backend` in cli/src/superTabs/service.ts). The tests
/// outside the first group have no sign-in to read with (`FakeApi.swarmRead`),
/// so their reads all go on through the machines.
@@ -72,7 +73,7 @@ void main() {
expect(rig.api.swarmReads, ['/api/super-tabs/t/changes?cursor=c1']);
});
- test('a command never does: a machine forwards it', () async {
+ test('without phone write credentials a machine forwards a command', () async {
final rig = await signedInWith({'m': []});
addTearDown(rig.app.dispose);
rig.api.onSwarmRead = (_) async => fail('a command is not a read');