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-05 b0010: #3049 #3052 #3050 #3027 (#3053)

0xken1553f924f1d7d8
diff --git a/mobile/lib/phone/phone_shell.dart b/mobile/lib/phone/phone_shell.dart
index 0bff3e686..f26cc49a0 100644
--- a/mobile/lib/phone/phone_shell.dart
+++ b/mobile/lib/phone/phone_shell.dart
@@ -5,6 +5,7 @@ import 'package:flutter/material.dart';
import 'package:harness_mobile/state/app_state.dart';
+import '../demo/sample_mode.dart' show SampleMode;
import '../notify/system_notices.dart';
import '../p2p/phone_terminal_p2p.dart';
import '../swarm/swarm_activity_page.dart' show swarmActivityRoute;
@@ -588,6 +589,11 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {
swarm: (_) => SwarmTabsPage(
onSettings: (context) =>
openPhoneSettings(context, widget.notifier, swarm: true),
+ // You's Notifications, not in the sample, as Settings leaves
+ // it out there: its notices go nowhere.
+ notices: SampleMode.ofNotifier(widget.notifier) == null
+ ? widget.notifier.agentNotices.system
+ : null,
),
),
),
diff --git a/mobile/lib/phone/settings_page.dart b/mobile/lib/phone/settings_page.dart
index ea4cafdd4..5004e9292 100644
--- a/mobile/lib/phone/settings_page.dart
+++ b/mobile/lib/phone/settings_page.dart
@@ -26,7 +26,6 @@ import 'package:harness_mobile/swarm/swarm_style.dart'
SwarmBackButton,
SwarmCaption,
SwarmRowGlyph,
- SwarmSegments,
SwarmTopBar;
import 'package:harness_mobile/terminal/terminal_font_store.dart';
import 'package:harness_mobile/terminal/terminal_theme_store.dart';
@@ -105,7 +104,8 @@ class SettingsPage extends StatelessWidget {
/// Drawn as Swarm's pages are ([SettingsSwarmLook]): opened from Swarm's You. Swarm's top bar
/// then stands in for the big title, whatever [large] says, and the list is Swarm's shorter one —
- /// every setting still there, fewer rows and captions (`docs/design/2026-11-03-swarm-settings.md`).
+ /// fewer rows and captions (`docs/design/2026-11-03-swarm-settings.md`). Notifications and Theme
+ /// are not in it: they sit on You itself, one tap nearer (Tony 2026-11-04, `SwarmYouPage`).
final bool swarm;
/// What Experimental switches: [experimentalFeaturesStore] unless a test hands in its own, so a
@@ -287,12 +287,9 @@ class _Body extends StatelessWidget {
const SettingsCaption('Appearance'),
SettingsGroup(
children: [
- // Swarm's Settings asks light or dark — System, Dark, Light — where the terminal's offers
- // the eight palettes. The terminal's own page stays dark under either answer.
- if (SettingsSwarmLook.of(context))
- _ThemeRow(store: appearance)
- else
- _PaletteRow(store: appearance),
+ // The terminal's Settings offers the eight palettes. Swarm's asks light or dark instead,
+ // on You itself (its Theme), so its Appearance is the text size alone.
+ if (!SettingsSwarmLook.of(context)) _PaletteRow(store: appearance),
_TextSizeRow(),
],
),
@@ -395,8 +392,8 @@ class _Body extends StatelessWidget {
SampleMode.maybeOf(context) ?? SampleMode.ofNotifier(notifier);
/// The account's rows as Swarm splits You's, in cards with no caption (prototype A lean,
- /// 2026-11-03, `docs/design/2026-11-03-swarm-settings.md`): you and what you use and hear of;
- /// your computers; this phone.
+ /// 2026-11-03, `docs/design/2026-11-03-swarm-settings.md`): you and what you use; your computers;
+ /// this phone. Notifications is on You, one level up (2026-11-04).
List<Widget> _swarmAccount(BuildContext context) => [
if (_sample(context) != null)
const SwarmCaption('Sample', first: true)
@@ -406,7 +403,6 @@ class _Body extends StatelessWidget {
children: [
_accountRow(context),
buildUsageSettingsRow(context, notifier),
- ?_notificationsRow(context),
?_privacyRow(context),
],
),
@@ -535,8 +531,9 @@ class _Body extends StatelessWidget {
);
/// Not in the sample, whose notices go nowhere.
- Widget? _notificationsRow(BuildContext context) =>
- _sample(context) == null ? _NotificationsRow(notifier: notifier) : null;
+ Widget? _notificationsRow(BuildContext context) => _sample(context) == null
+ ? NotificationsSettingsRow(notices: notifier.agentNotices.system)
+ : null;
/// Who is signed in — or, in sample mode, which has no account to show or sign out of, the
/// way back out of it.
@@ -807,20 +804,24 @@ class _VoiceLanguageRow extends StatelessWidget {
/// asks once; Android stops after a refusal or two) the answer is still no, so the way to the
/// phone's own switch is offered. On, a tap goes straight to that switch. Read again on the way back
/// from Settings. No value at all where the answer cannot be read (a stand-in notice centre).
-class _NotificationsRow extends StatefulWidget {
- const _NotificationsRow({required this.notifier});
+///
+/// In the terminal's Settings, and on Swarm's You ([SettingsSwarmLook] around it there), whose
+/// Settings leaves it out.
+class NotificationsSettingsRow extends StatefulWidget {
+ const NotificationsSettingsRow({super.key, required this.notices});
- final AppNotifier notifier;
+ /// The phone's notice centre (`AgentAnnouncer.system`).
+ final SystemNotices notices;
@override
- State<_NotificationsRow> createState() => _NotificationsRowState();
+ State<NotificationsSettingsRow> createState() => _NotificationsSettingsRowState();
}
-class _NotificationsRowState extends State<_NotificationsRow>
+class _NotificationsSettingsRowState extends State<NotificationsSettingsRow>
with WidgetsBindingObserver {
bool? _on;
- SystemNotices get _notices => widget.notifier.agentNotices.system;
+ SystemNotices get _notices => widget.notices;
@override
void initState() {
@@ -1177,7 +1178,7 @@ class _TerminalThemeRow extends StatelessWidget {
/// writes — so the preview IS the app behind the sheet, at full size, which no swatch can beat.
///
/// Under Dark and Light captions, because a light palette is the whole of light mode in the
-/// terminal's Settings: Swarm's Settings asks light or dark instead ([_ThemeRow]).
+/// terminal's Settings: Swarm asks light or dark instead, with the Theme on its You.
///
/// It names the palette on screen — which Swarm's Theme may have chosen (Paper, under Light) — and
/// a pick here hands light and dark back to the palette ([AppearancePrefsStore.setPalette]).
@@ -1228,48 +1229,6 @@ class _PaletteRow extends StatelessWidget {
);
}
-/// Light or dark, in Settings opened from Swarm: System | Dark | Light, in App colors' place.
-///
-/// One tap, and every screen turns at once — the page behind is the preview — except the
-/// terminal's page, which keeps the dark side ([AppearancePrefs.terminalPalette]). Dark and Light
-/// keep the palette App colors chose while it is on their side, else Graphite and Paper. System
-/// follows the phone as it turns. Until it is touched, the control shows the side the palette is
-/// on, which is what that answer would draw.
-class _ThemeRow extends StatelessWidget {
- const _ThemeRow({required this.store});
-
- final AppearancePrefsStore store;
-
- @override
- Widget build(BuildContext context) => ValueListenableBuilder<AppearancePrefs>(
- valueListenable: store,
- builder: (context, prefs, _) {
- AppTheme.watch(context);
- return SettingsRow(
- key: const ValueKey('settings-theme'),
- title: 'Theme',
- glyph: LucideIcons.sunMoon300,
- // A little over half the row, so the title keeps its word at the largest text size; past
- // that the control shrinks rather than pushing the row over its edge.
- trailing: ConstrainedBox(
- constraints: BoxConstraints(
- maxWidth: MediaQuery.sizeOf(context).width * .55,
- ),
- child: FittedBox(
- fit: BoxFit.scaleDown,
- child: SwarmSegments<AppThemeMode>(
- values: AppThemeMode.values,
- selected: prefs.shownThemeMode,
- label: (mode) => mode.label,
- onSelected: (mode) => unawaited(store.setThemeMode(mode)),
- ),
- ),
- ),
- );
- },
- );
-}
-
/// The app's own text size — everything that is not the terminal.
class _TextSizeRow extends StatelessWidget {
@override
diff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dart
index c4ae784c1..cb9bf856b 100644
--- a/mobile/lib/swarm/model.dart
+++ b/mobile/lib/swarm/model.dart
@@ -227,7 +227,8 @@ class SuperTabAgent {
/// A Product Manager's switch to another engine or account that is asked for
/// and not yet done (backend `switchRequest`), as the desktop's model reads
- /// it; null otherwise. Not drawn on the phone yet.
+ /// it; null otherwise. While set, the PM reads "Switching…" and Switch PM…
+ /// is not offered (swarm_switch_pm.dart).
final Map<String, dynamic>? switchRequest;
/// The model on the Swarm's grid it runs on; null on its own subscription
@@ -242,7 +243,7 @@ class SuperTabAgent {
/// The account on its machine it runs in; `default` when none is chosen.
/// Null until the backend reports it: the engine's default account. As the
- /// desktop's model reads it; not drawn on the phone yet.
+ /// desktop's model reads it; Switch PM marks it Current.
final String? profileId;
/// Since when its machine has reported its session gone, or its host confirmed a stop (backend machines.ts). Null
diff --git a/mobile/lib/swarm/swarm_attachment_store.dart b/mobile/lib/swarm/swarm_attachment_store.dart
index 1d9c6aae5..288108e9d 100644
--- a/mobile/lib/swarm/swarm_attachment_store.dart
+++ b/mobile/lib/swarm/swarm_attachment_store.dart
@@ -381,7 +381,8 @@ class SwarmAttachmentKeeper {
/// The cache's fetch of a chat file: `HttpFileService`'s, with a redirect
/// refused, so a picture comes only from the host its message names and
-/// nothing from another host is kept or drawn.
+/// nothing from another host is kept or drawn. Kept under the extension
+/// [swarmKeptExtension] gives it.
class SwarmFileFetch extends FileService {
SwarmFileFetch({http.Client? client}) : _client = client ?? http.Client();
@@ -395,6 +396,93 @@ class SwarmFileFetch extends FileService {
final request = http.Request('GET', Uri.parse(url))
..followRedirects = false;
if (headers != null) request.headers.addAll(headers);
- return HttpGetResponse(await _client.send(request));
+ final response = await _client.send(request);
+ return _Named(
+ HttpGetResponse(response),
+ response.headers['content-disposition'],
+ request.url,
+ );
+ }
+}
+
+/// The extension, with its dot, a fetched file is kept under: its type's
+/// ([typed], the cache's reading of `Content-Type`), but for one served as
+/// bare bytes (`.bin`, as the backend serves every file but a picture:
+/// superTabs/attachments.ts `served`) its own name's, the one the answer
+/// gives ([disposition], `Content-Disposition`), else the last part of
+/// [url]. An iPhone's player goes by the extension: a voice message kept as
+/// .bin does not play there, where Android's reads what is in the file.
+@visibleForTesting
+String swarmKeptExtension(
+ String typed, {
+ String? disposition,
+ required Uri url,
+}) {
+ if (typed.isNotEmpty && typed != '.bin') return typed;
+ return _extensionOf(_dispositionName(disposition)) ??
+ _extensionOf(url.pathSegments.lastOrNull) ??
+ typed;
+}
+
+/// The file name a `Content-Disposition` gives: its `filename*` (RFC 6266),
+/// else its `filename`; null when it gives none that can be read.
+String? _dispositionName(String? disposition) {
+ if (disposition == null) return null;
+ final encoded = RegExp(
+ r"""filename\*\s*=\s*[^']*'[^']*'([^;\s]+)""",
+ caseSensitive: false,
+ ).firstMatch(disposition);
+ if (encoded != null) {
+ try {
+ return Uri.decodeComponent(encoded.group(1)!);
+ } on Object {
+ // Badly encoded (a stray %, or bytes that are not UTF-8): the plain
+ // name, if there is one.
+ }
}
+ return RegExp(
+ r'''filename\s*=\s*"?([^";]+)"?''',
+ caseSensitive: false,
+ ).firstMatch(disposition)?.group(1);
+}
+
+/// [name]'s extension, lower case with its dot, when it is a plain one:
+/// letters and digits, at most 10 of them. Null for any other.
+String? _extensionOf(String? name) {
+ if (name == null) return null;
+ final dot = name.lastIndexOf('.');
+ if (dot <= 0) return null;
+ final extension = name.substring(dot).toLowerCase();
+ return RegExp(r'^\.[a-z0-9]{1,10}$').hasMatch(extension) ? extension : null;
+}
+
+/// [HttpGetResponse], kept under [swarmKeptExtension]'s extension.
+class _Named implements FileServiceResponse {
+ _Named(this._response, this._disposition, this._url);
+
+ final HttpGetResponse _response;
+ final String? _disposition;
+ final Uri _url;
+
+ @override
+ Stream<List<int>> get content => _response.content;
+
+ @override
+ int? get contentLength => _response.contentLength;
+
+ @override
+ int get statusCode => _response.statusCode;
+
+ @override
+ DateTime get validTill => _response.validTill;
+
+ @override
+ String? get eTag => _response.eTag;
+
+ @override
+ String get fileExtension => swarmKeptExtension(
+ _response.fileExtension,
+ disposition: _disposition,
+ url: _url,
+ );
}
diff --git a/mobile/lib/swarm/swarm_buddy_chat.dart b/mobile/lib/swarm/swarm_buddy_chat.dart
index 61fcfe0ef..1aa4162f0 100644
--- a/mobile/lib/swarm/swarm_buddy_chat.dart
+++ b/mobile/lib/swarm/swarm_buddy_chat.dart
@@ -1,5 +1,6 @@
import 'dart:async';
+import 'package:clock/clock.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
@@ -18,6 +19,7 @@ import 'model.dart';
import 'swarm_buddy.dart';
import 'swarm_chat_menu.dart' show swarmNotifySection;
import 'swarm_conversation_page.dart';
+import 'swarm_message_receipt.dart' show swarmMachineOffline;
import 'swarm_reader.dart';
import 'swarm_request.dart';
import 'swarm_row.dart';
@@ -63,7 +65,10 @@ Future<String?> openSwarmBuddy(
/// may write: the chat is there before any Buddy. Under all of it, what went
/// wrong with the last start or removal. Nothing for a viewer with no Buddy,
/// nor while a Buddy runs on the person's own machine: the chat is the
-/// screen, and its messages start under the header (Tony, 10-29).
+/// screen, and its messages start under the header (Tony, 10-29). Nor that
+/// a Buddy is down while its computer is offline: the line under the message
+/// sent to it says that computer is offline, and nothing starts there until
+/// it is back (Tony, 11-04).
class SwarmBuddyBar extends StatelessWidget {
const SwarmBuddyBar({super.key, required this.actions});
@@ -73,7 +78,13 @@ class SwarmBuddyBar extends StatelessWidget {
Widget build(BuildContext context) {
AppTheme.watch(context);
return ListenableBuilder(
- listenable: Listenable.merge([actions.reader, actions]),
+ // Every read, changed or not: a computer goes offline by its reading
+ // growing old, which no change to the Swarm announces.
+ listenable: Listenable.merge([
+ actions.reader,
+ actions.reader.reads,
+ actions,
+ ]),
builder: (context, _) {
final reader = actions.reader;
final canWrite = swarmCanWrite(reader);
@@ -124,11 +135,18 @@ class SwarmBuddyBar extends StatelessWidget {
/// On someone else's machine, "Claude on Dee Studio · dee can see its
/// terminal" (a Buddy from before the server kept Buddies to their owner's
- /// machines, 10-28); and, while it is down, that it is offline with Start
- /// again. Null on the person's own machine while it runs.
+ /// machines, 10-28); and, while it is down on a computer that is online,
+ /// that it is offline with Start again. Null on the person's own machine
+ /// while it runs, or while it is down there and that computer is offline.
Widget? _running(SwarmReader reader, SuperTabAgent agent, bool canWrite) {
final shared = agent.machineOwnerId != reader.accountId;
- if (!shared && agent.downSince == null) return null;
+ final down =
+ agent.downSince != null &&
+ !swarmMachineOffline(
+ reader.snapshot?.pool(agent.machineId),
+ clock.now(),
+ );
+ if (!shared && !down) return null;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
@@ -142,7 +160,7 @@ class SwarmBuddyBar extends StatelessWidget {
key: const ValueKey('swarm-buddy-where'),
lines: 2,
),
- if (agent.downSince != null)
+ if (down)
_Line(
key: const ValueKey('swarm-buddy-offline'),
text:
diff --git a/mobile/lib/swarm/swarm_message_receipt.dart b/mobile/lib/swarm/swarm_message_receipt.dart
index 1a40af37f..4a772f0ca 100644
--- a/mobile/lib/swarm/swarm_message_receipt.dart
+++ b/mobile/lib/swarm/swarm_message_receipt.dart
@@ -28,6 +28,25 @@ const swarmQueuedNotice = Duration(minutes: 2);
/// desktop's `kSuperTabMachineOfflineAfter`.
const _machineOfflineAfter = Duration(seconds: 35);
+/// When [machine], a Swarm's pool row, last reported, if it ever did.
+DateTime? _readingAt(Map<String, dynamic>? machine) {
+ final observation = machine?['observation'];
+ final receivedAt = observation is Map ? observation['receivedAt'] : null;
+ return receivedAt is num
+ ? DateTime.fromMillisecondsSinceEpoch(receivedAt.toInt())
+ : null;
+}
+
+/// Whether [machine], a Swarm's pool row, is offline at [now] as a message's
+/// line calls it "computer is offline": listed, with no reading or one older
+/// than [_machineOfflineAfter]. A machine the Swarm does not list (null) is
+/// no answer, so not offline.
+bool swarmMachineOffline(Map<String, dynamic>? machine, DateTime now) {
+ if (machine == null) return false;
+ final at = _readingAt(machine);
+ return at == null || now.difference(at) >= _machineOfflineAfter;
+}
+
/// The line under the person's newest message while its delivery is queued and
/// not getting in, or when its computer could not confirm it: the desktop's
/// `SuperTabMessageReceipt` for those cases, its words and rule. Queued is in
@@ -168,15 +187,8 @@ class _SwarmMessageReceiptState extends State<SwarmMessageReceipt>
return _unconfirmed(context, c, message, delivery, agent, name);
}
final machine = snapshot.pool(agent.machineId);
- final observation = machine?['observation'];
- final receivedAt = observation is Map ? observation['receivedAt'] : null;
- final readingAt = receivedAt is num
- ? DateTime.fromMillisecondsSinceEpoch(receivedAt.toInt())
- : null;
- final offline =
- machine != null &&
- (readingAt == null ||
- now.difference(readingAt) >= _machineOfflineAfter);
+ final readingAt = _readingAt(machine);
+ final offline = swarmMachineOffline(machine, now);
final failingSince = delivery.claimFailingSince;
final failingAt = failingSince?.add(swarmClaimFailingNotice);
final queuedAt = message.createdAt?.add(swarmQueuedNotice);
diff --git a/mobile/lib/swarm/swarm_project_settings.dart b/mobile/lib/swarm/swarm_project_settings.dart
index 7ce2a887d..53362d0ee 100644
--- a/mobile/lib/swarm/swarm_project_settings.dart
+++ b/mobile/lib/swarm/swarm_project_settings.dart
@@ -17,6 +17,7 @@ import 'swarm_reader.dart';
import 'swarm_request.dart';
import 'swarm_row.dart';
import 'swarm_style.dart';
+import 'swarm_switch_pm.dart';
/// Whether the person may rename [projectId] and change its sharing: its
/// owner, while they may write (the desktop's `editable && owner`; the
@@ -94,10 +95,11 @@ const _notAllowed = 'Only the project owner can manage this project.';
const _notSent = 'Could not reach this Swarm. Try again.';
/// The project menu's Project settings… (the desktop's `showProjectSettings`):
-/// Rename project for its owner who may write, and Project details
-/// ([onDetails]) for everyone who reads it. Each runs once the sheet has
-/// closed. [onShown] is handed its route, for the page to take it down with
-/// the project.
+/// Rename project for its owner who may write, Project details ([onDetails])
+/// for everyone who reads it, and Switch PM… for whoever may switch its
+/// Product Manager while no switch is under way ([swarmCanSwitchPm]). Each
+/// runs once the sheet has closed. [onShown] is handed its route, for the
+/// page to take it down with the project.
Future<void> showSwarmProjectSettings(
BuildContext context,
SwarmReader reader,
@@ -108,7 +110,8 @@ Future<void> showSwarmProjectSettings(
context,
title: 'Project settings',
onShown: onShown,
- // Made the owner's, or no longer, on another device meanwhile.
+ // Made the owner's, or no longer, on another device meanwhile; its PM
+ // switched, or being switched.
rebuildOn: reader,
rows: () => (
actions: [
@@ -125,6 +128,13 @@ Future<void> showSwarmProjectSettings(
chevron: true,
onTap: onDetails,
),
+ if (swarmCanSwitchPm(reader, projectId))
+ PhoneSheetAction(
+ icon: LucideIcons.arrowLeftRight300,
+ label: 'Switch PM…',
+ onTap: () =>
+ unawaited(showSwarmSwitchPm(context, reader, projectId)),
+ ),
],
sections: const <PhoneSheetSection>[],
),
diff --git a/mobile/lib/swarm/swarm_special_rows.dart b/mobile/lib/swarm/swarm_special_rows.dart
index cda0322a7..6b5a03158 100644
--- a/mobile/lib/swarm/swarm_special_rows.dart
+++ b/mobile/lib/swarm/swarm_special_rows.dart
@@ -3,7 +3,6 @@ import 'dart:async';
import 'package:flutter/material.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
-import 'package:harness_mobile/core/relative_time.dart';
import 'package:harness_mobile/shared/theme/app_space.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
@@ -11,6 +10,7 @@ import 'model.dart';
import 'swarm_message_row.dart' show SwarmMessageFrame, swarmChatText;
import 'swarm_reader.dart';
import 'swarm_session.dart';
+import 'swarm_switch_pm.dart';
// The notes in a chat that are not chat from their author, drawn as Desktop
// draws them: a routing note (route_row.dart), a note about a terminal
@@ -41,7 +41,7 @@ const EdgeInsets _inset = EdgeInsets.fromLTRB(
/// A quiet action beside a note, a finger's size.
class _NoteAction extends StatelessWidget {
- const _NoteAction({required this.label, required this.onTap});
+ const _NoteAction({super.key, required this.label, required this.onTap});
final String label;
final VoidCallback onTap;
@@ -210,8 +210,9 @@ class _SwarmRouteRowState extends State<SwarmRouteRow> {
}
/// A Lead's typing into a worker's terminal, or a machine's alert about one
-/// (Desktop's `SuperTabTerminalRow`). Desktop's Switch PM… on a PM's limit
-/// note waits for the phone's Switch PM screen.
+/// (Desktop's `SuperTabTerminalRow`). A Product Manager's usage-limit note
+/// offers Switch PM… as Desktop's does ([swarmLimitNoteSwitchPm]), following
+/// the Swarm as it is read again.
class SwarmTerminalRow extends StatelessWidget {
const SwarmTerminalRow({super.key, required this.message});
final SuperTabMessage message;
@@ -237,12 +238,51 @@ class SwarmTerminalRow extends StatelessWidget {
@override
Widget build(BuildContext context) {
AppTheme.watch(context);
+ // A row kept as it was is not built again: the PM's limit note follows
+ // the Swarm itself, as the ship card does.
+ final inbox = message.leadLimitAgentId == null
+ ? null
+ : SwarmScope.of(context)?.inbox;
+ if (inbox == null) return _row(null);
+ return ListenableBuilder(
+ listenable: inbox,
+ builder: (context, _) {
+ final reader = swarmReaderOf(context, message.conversationId);
+ final projectId = reader == null
+ ? null
+ : swarmLimitNoteSwitchPm(reader, message);
+ return _row(
+ projectId == null
+ ? null
+ : _NoteAction(
+ key: const ValueKey('swarm-limit-switch-pm'),
+ label: 'Switch PM…',
+ onTap: () => unawaited(
+ showSwarmSwitchPm(context, reader!, projectId),
+ ),
+ ),
+ );
+ },
+ );
+ }
+
+ Widget _row(Widget? action) {
final alert = message.source['kind'] != 'terminal-input';
final style = _quiet();
// Only the coordinator's: a worker's note says its time in its own words.
final until = message.leadLimitAgentId != null
? DateTime.tryParse(message.source['limitedUntil'] as String? ?? '')
: null;
+ final text = Text.rich(
+ TextSpan(
+ children: [
+ typed(message.text, style),
+ if (until != null)
+ TextSpan(text: ' until ${swarmSwitchPmTime(until)}'),
+ ],
+ ),
+ style: style,
+ );
return Padding(
padding: EdgeInsets.fromLTRB(
AppSpace.s,
@@ -251,7 +291,11 @@ class SwarmTerminalRow extends StatelessWidget {
_inset.bottom,
),
child: Row(
- crossAxisAlignment: CrossAxisAlignment.start,
+ // Beside an action a finger's size, the mark and the words sit on
+ // its middle.
+ crossAxisAlignment: action == null
+ ? CrossAxisAlignment.start
+ : CrossAxisAlignment.center,
children: [
SizedBox(
width: SwarmMessageFrame.column,
@@ -270,15 +314,9 @@ class SwarmTerminalRow extends StatelessWidget {
),
),
Expanded(
- child: Text.rich(
- TextSpan(
- children: [
- typed(message.text, style),
- if (until != null) TextSpan(text: ' until ${_time(until)}'),
- ],
- ),
- style: style,
- ),
+ child: action == null
+ ? text
+ : Row(children: [Flexible(child: text), action]),
),
],
),
@@ -286,18 +324,6 @@ class SwarmTerminalRow extends StatelessWidget {
}
}
-/// The time when [at] is today, else the date and time, in local time.
-String _time(DateTime at) {
- final local = at.toLocal(), today = DateTime.now();
- if (local.year == today.year &&
- local.month == today.month &&
- local.day == today.day) {
- String two(int n) => n.toString().padLeft(2, '0');
- return '${two(local.hour)}:${two(local.minute)}';
- }
- return fullDateTime(at);
-}
-
/// The quiet line a terminal's answer starts with, and the one under a
/// response that was cut short (Desktop's view.dart).
Widget? swarmTerminalNote(SuperTabMessage message) =>
diff --git a/mobile/lib/swarm/swarm_switch_pm.dart b/mobile/lib/swarm/swarm_switch_pm.dart
new file mode 100644
index 000000000..384ec4cf1
--- /dev/null
+++ b/mobile/lib/swarm/swarm_switch_pm.dart
@@ -0,0 +1,966 @@
+import 'dart:async';
+import 'dart:convert' show utf8;
+
+import 'package:flutter/material.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import 'package:harness_mobile/core/relative_time.dart';
+import 'package:harness_mobile/e2ee/primitives.dart' show sha256;
+import 'package:harness_mobile/shared/theme/app_icon_size.dart';
+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 'package:harness_mobile/shared/widgets/touch_target.dart';
+import 'package:harness_mobile/theme/app_theme.dart' show AppColors;
+
+import 'model.dart';
+import 'swarm_buddy.dart' show swarmBuddyMachineName, swarmCanWrite;
+import 'swarm_new_project_sheet.dart'
+ show swarmLeadEngineLabel, swarmLeadEngines;
+import 'swarm_reader.dart';
+import 'swarm_request.dart';
+import 'swarm_style.dart';
+
+// Switch PM (Desktop's switch_pm.dart, spec
+// 2026-11-02-pm-switch-engine-account-design.md): move a project's Product
+// Manager to another engine or account on the machine it runs on. The
+// machine's host does the switch; the phone sends `lead.switch` and shows a
+// refusal, as Desktop does. The project's owner may also move it to another
+// machine of the Swarm, which starts it there; and any model of the Swarm's
+// catalog may be asked for (backend commands.ts `lead.switch`).
+
+/// A machine reading this old is offline (Desktop's
+/// `kSuperTabMachineOfflineAfter`).
+const _offlineAfter = Duration(seconds: 35);
+
+/// "18:05" when [at] is today, else the date and time ("4 Nov 2026, 18:05"),
+/// in local time (Desktop's `switchPmTime`, in the phone's clock).
+String swarmSwitchPmTime(DateTime at) {
+ final local = at.toLocal(), today = DateTime.now();
+ if (local.year == today.year &&
+ local.month == today.month &&
+ local.day == today.day) {
+ String two(int n) => n.toString().padLeft(2, '0');
+ return '${two(local.hour)}:${two(local.minute)}';
+ }
+ return fullDateTime(at);
+}
+
+/// One account of a machine as its report lists it (backend
+/// `observation.profiles`, Desktop's `SuperTabProfile`): opaque id, a label
+/// with no path or email, and what is left of its allowance when known.
+typedef SuperTabProfile = ({
+ String engine,
+ String id,
+ String label,
+ int? leftPercent,
+ DateTime? resetsAt,
+});
+
+/// The accounts [pool] reports; empty from a machine that reports none
+/// (Desktop's `superTabProfilesOf`).
+List<SuperTabProfile> superTabProfilesOf(Map<String, dynamic>? pool) {
+ final observation = pool?['observation'];
+ final rows = observation is Map ? observation['profiles'] : null;
+ return [
+ for (final p in rows is List ? rows : const [])
+ if (p is Map &&
+ p['engine'] is String &&
+ p['id'] is String &&
+ p['label'] is String)
+ (
+ engine: p['engine'] as String,
+ id: p['id'] as String,
+ label: p['label'] as String,
+ leftPercent: (p['leftPercent'] as num?)?.toInt(),
+ resetsAt: DateTime.tryParse(p['resetsAt'] as String? ?? ''),
+ ),
+ ];
+}
+
+/// A Swarm profile (an engine account of a machine), as the CLI, the backend
+/// and Desktop name it: the first 16 hex characters of
+/// sha256(`<machineId>:<engine>:<realpath>`), or `...:default` for the
+/// engine's default account (Desktop's `swarmProfileId`).
+String swarmProfileId(String machineId, String engine, String pathOrDefault) {
+ final digest = sha256(utf8.encode('$machineId:$engine:$pathOrDefault'));
+ return [for (final byte in digest) byte.toRadixString(16).padLeft(2, '0')]
+ .join()
+ .substring(0, 16);
+}
+
+/// [projectId]'s Product Manager, while it has one (Desktop's `leadOf`).
+SuperTabAgent? swarmLeadOf(SuperTabSnapshot? snapshot, String projectId) {
+ if (snapshot == null) return null;
+ final chat = snapshot.projectById(projectId)?.leadConversationId;
+ final id = chat == null ? null : snapshot.conversation(chat)?.leadId;
+ return id == null ? null : snapshot.agent(id);
+}
+
+/// Whether [accountId] may switch [projectId]'s Product Manager: the
+/// project's owner, or the owner of the machine it runs on, never a lent
+/// machine's borrower (Desktop's `maySwitchLead`; the backend decides again).
+bool swarmMaySwitchLead(
+ SuperTabSnapshot? snapshot,
+ String projectId,
+ String? accountId,
+) {
+ final lead = swarmLeadOf(snapshot, projectId);
+ return lead != null &&
+ accountId != null &&
+ (snapshot!.projectById(projectId)?.ownerId == accountId ||
+ lead.machineOwnerId == accountId);
+}
+
+/// Whether [reader]'s person is offered Switch PM… for [projectId] now, as
+/// Desktop offers it: one who may write and may switch it, while no switch
+/// of it is under way.
+bool swarmCanSwitchPm(SwarmReader reader, String projectId) =>
+ !reader.accessRevoked &&
+ swarmCanWrite(reader) &&
+ swarmMaySwitchLead(reader.snapshot, projectId, reader.accountId) &&
+ swarmLeadOf(reader.snapshot, projectId)?.switchRequest == null;
+
+/// The project whose Product Manager the usage-limit note [message] offers
+/// Switch PM… for: while that PM's machine still alerts about the limit (as a
+/// prompt note stops saying anything once answered) and [swarmCanSwitchPm].
+/// Null for every other note (Desktop's `SuperTabTerminalRow._canSwitch`).
+String? swarmLimitNoteSwitchPm(SwarmReader reader, SuperTabMessage message) {
+ final id = message.leadLimitAgentId, snapshot = reader.snapshot;
+ if (id == null || snapshot == null) return null;
+ final lead = snapshot.agent(id), project = snapshot.leadProjectForAgent(id);
+ if (lead == null || project == null || !lead.alerting.contains('limit')) {
+ return null;
+ }
+ return swarmCanSwitchPm(reader, project.id) ? project.id : null;
+}
+
+/// Why [projectId]'s Product Manager cannot be switched now, as Desktop's
+/// dialog says it before Switch is pressed: no fresh reading from its
+/// machine, or a Harness there too old to switch one (backend
+/// `MACHINE_OFFLINE`, `HOST_OUTDATED`). Null when it can, and without a PM.
+String? swarmSwitchPmRefusal(
+ SwarmReader reader,
+ String projectId, {
+ DateTime? now,
+}) {
+ final lead = swarmLeadOf(reader.snapshot, projectId);
+ if (lead == null) return null;
+ final pool = reader.snapshot!.pool(lead.machineId);
+ if (!_fresh(pool, now ?? DateTime.now())) {
+ return 'Wait for a fresh reading from the PM’s machine.';
+ }
+ final capabilities = (pool!['observation'] as Map)['capabilities'];
+ if (capabilities is List && capabilities.contains('leadSwitch')) {
+ return null;
+ }
+ final name = _poolName(reader, pool, 'the PM’s machine');
+ return 'Update Harness on $name to switch this Product Manager.';
+}
+
+/// Whether [pool]'s last reading is under [_offlineAfter] old at [now]
+/// (Desktop's `fresh`).
+bool _fresh(Map<String, dynamic>? pool, DateTime now) {
+ final observation = pool?['observation'];
+ final at = observation is Map ? observation['receivedAt'] : null;
+ return at is num &&
+ now.difference(DateTime.fromMillisecondsSinceEpoch(at.toInt())) <
+ _offlineAfter;
+}
+
+/// [pool]'s name without its `.local`, or [fallback] for one with none.
+String _poolName(
+ SwarmReader reader,
+ Map<String, dynamic> pool,
+ String fallback,
+) => switch ((pool['name'], pool['machineId'])) {
+ (final String named, final String id) when named.isNotEmpty =>
+ swarmBuddyMachineName(reader, id),
+ _ => fallback,
+};
+
+/// One machine Switch PM lists in its Machine row: the one the PM runs on
+/// ([current]), or another it could move to, with why it cannot now
+/// ([unavailable]; null when it can).
+typedef SwarmSwitchPmMachine = ({
+ String id,
+ String name,
+ bool current,
+ String? unavailable,
+});
+
+/// Why [projectId]'s Product Manager cannot move to machine [pool] now, as
+/// Desktop's Machine row says it; null when it can, and for the machine it
+/// runs on. Only the project's owner moves it (backend `lead.switch`, a new
+/// start: `placeLead`), to a fresh machine whose Harness both starts and
+/// switches one, that is theirs or takes this project's work, and that is
+/// neither being removed nor paused.
+String? swarmSwitchPmMachineRefusal(
+ SwarmReader reader,
+ String projectId,
+ Map<String, dynamic> pool, {
+ DateTime? now,
+}) {
+ final snapshot = reader.snapshot;
+ final lead = swarmLeadOf(snapshot, projectId);
+ if (pool['machineId'] == lead?.machineId) return null;
+ final name = _poolName(reader, pool, 'Mac');
+ if (snapshot?.projectById(projectId)?.ownerId != reader.accountId) {
+ return 'Only the project’s owner moves its PM to another machine.';
+ }
+ if (!_fresh(pool, now ?? DateTime.now())) return '$name is offline.';
+ final observation = pool['observation'];
+ final capabilities = observation is Map ? observation['capabilities'] : null;
+ if (capabilities is! List ||
+ !capabilities.contains('leadSwitch') ||
+ !capabilities.contains('leadStart')) {
+ return 'Update Harness on $name to move a Product Manager there.';
+ }
+ final teamWork = pool['teamWork'];
+ final mayUse =
+ pool['contributorId'] == reader.accountId ||
+ (teamWork is Map && teamWork['allowed'] == true);
+ if (!mayUse) {
+ return teamWork is Map && teamWork['reason'] is String
+ ? teamWork['reason'] as String
+ : 'This machine cannot take this project’s work.';
+ }
+ if (pool['removal'] != null || pool['paused'] == true) {
+ return '$name is unavailable in this Swarm.';
+ }
+ return null;
+}
+
+/// The machines Switch PM's Machine row lists for [projectId]'s Product
+/// Manager, in the Swarm's order, as Desktop's does: every machine of the
+/// Swarm but a Harness Team account read on its Mac, unless the PM runs
+/// there. The one it runs on is marked [SwarmSwitchPmMachine.current].
+List<SwarmSwitchPmMachine> swarmSwitchPmMachines(
+ SwarmReader reader,
+ String projectId, {
+ DateTime? now,
+}) {
+ final snapshot = reader.snapshot;
+ final lead = swarmLeadOf(snapshot, projectId);
+ if (snapshot == null || lead == null) return const [];
+ return [
+ for (final pool in snapshot.machines)
+ if (pool['machineId'] case final String id
+ when pool['hostMachineId'] == null || id == lead.machineId)
+ (
+ id: id,
+ name: _poolName(reader, pool, 'Mac'),
+ current: id == lead.machineId,
+ unavailable: swarmSwitchPmMachineRefusal(
+ reader,
+ projectId,
+ pool,
+ now: now,
+ ),
+ ),
+ ];
+}
+
+/// One account Switch PM lists, and whether the PM runs in it now.
+typedef SwarmSwitchPmChoice = ({SuperTabProfile profile, bool current});
+
+/// The accounts Switch PM lists for [projectId]'s Product Manager on
+/// [machineId] (by default the machine it runs on), as Desktop's dialog
+/// does: the accounts that machine reports, or, from a machine that reports
+/// none, each engine it offers in its default account (the PM's own engine
+/// on its own machine, when it says nothing of its engines); in the engines'
+/// order, the one it runs in marked.
+List<SwarmSwitchPmChoice> swarmSwitchPmChoices(
+ SuperTabSnapshot snapshot,
+ String projectId, {
+ String? machineId,
+}) {
+ final lead = swarmLeadOf(snapshot, projectId);
+ if (lead == null) return const [];
+ final on = machineId ?? lead.machineId;
+ final pool = snapshot.pool(on);
+ var profiles = superTabProfilesOf(pool);
+ final reported = profiles.isNotEmpty;
+ if (!reported) {
+ final offered = (pool?['engines'] as List?)?.whereType<String>();
+ profiles = [
+ for (final engine in swarmLeadEngines)
+ if (offered?.contains(engine) ??
+ (on == lead.machineId && engine == lead.engine))
+ (
+ engine: engine,
+ id: 'default',
+ label: 'Default',
+ leftPercent: null,
+ resetsAt: null,
+ ),
+ ];
+ }
+ // By engine, each engine's accounts in the order the machine lists them.
+ final ordered = [...profiles.indexed]
+ ..sort((a, b) {
+ final engine = swarmLeadEngines
+ .indexOf(a.$2.engine)
+ .compareTo(swarmLeadEngines.indexOf(b.$2.engine));
+ return engine != 0 ? engine : a.$1.compareTo(b.$1);
+ });
+ // A PM that reports no account (or the literal default) runs its engine's
+ // default one.
+ final stored = lead.profileId;
+ final currentId = stored != null && stored != 'default'
+ ? stored
+ : reported
+ ? swarmProfileId(lead.machineId, lead.engine, 'default')
+ : 'default';
+ return [
+ for (final (_, p) in ordered)
+ (
+ profile: p,
+ current:
+ on == lead.machineId &&
+ p.engine == lead.engine &&
+ p.id == currentId,
+ ),
+ ];
+}
+
+/// Whether [choice] may be picked: not the account the PM runs in, nor one
+/// with nothing left.
+bool swarmSwitchPmPickable(SwarmSwitchPmChoice choice) =>
+ !choice.current && choice.profile.leftPercent != 0;
+
+/// "Codex · Work", as Desktop's dialog names an account.
+String swarmSwitchPmLabel(SuperTabProfile p) =>
+ '${swarmLeadEngineLabel(p.engine)} · ${p.label}';
+
+/// "Current · 40% left · resets 18:05", leaving out what is not known.
+String swarmSwitchPmDetail(SwarmSwitchPmChoice choice) => [
+ if (choice.current) 'Current',
+ if (choice.profile.leftPercent case final left?) '$left% left',
+ if (choice.profile.resetsAt case final at?) 'resets ${swarmSwitchPmTime(at)}',
+].join(' · ');
+
+/// One model of the Swarm's catalog (backend catalog.ts `CatalogModel`).
+typedef SwarmSwitchPmModel = ({String engine, String model});
+
+/// The models the tab's routing-policy read offers ([answer]'s
+/// `catalog.models`), as Desktop's dialog keeps them: each row with an
+/// engine and a model that is not marked `offered: false`. Empty from an
+/// answer without a catalog.
+List<SwarmSwitchPmModel> swarmSwitchPmCatalog(Object? answer) {
+ final catalog = answer is Map ? answer['catalog'] : null;
+ final rows = catalog is Map ? catalog['models'] : null;
+ return [
+ for (final row in rows is List ? rows : const [])
+ if (row is Map &&
+ row['engine'] is String &&
+ row['model'] is String &&
+ row['offered'] != false)
+ (engine: row['engine'] as String, model: row['model'] as String),
+ ];
+}
+
+/// The models Switch PM's Model row offers [engine] after Default, each
+/// once, in the catalog's order (Desktop's `offeredModels`). The catalog's
+/// own `default` row is Default itself (catalog.ts: it keeps the engine's
+/// own model), so it is not listed twice.
+List<String> swarmSwitchPmModels(
+ List<SwarmSwitchPmModel> catalog,
+ String engine,
+) => {
+ for (final row in catalog)
+ if (row.engine == engine && row.model != 'default') row.model,
+}.toList();
+
+/// The `lead.switch` command Switch PM sends (backend commands.ts): the
+/// engine and account picked, the machine only when it is not the one the
+/// PM runs on, and the model only when one other than Default is picked.
+Map<String, dynamic> swarmSwitchPmCommand({
+ required String projectId,
+ required ({String engine, String id}) picked,
+ required String currentMachineId,
+ required String machineId,
+ String? model,
+}) => {
+ 'type': 'lead.switch',
+ 'projectId': projectId,
+ 'engine': picked.engine,
+ 'profileId': picked.id,
+ if (machineId != currentMachineId) 'machineId': machineId,
+ 'model': ?model,
+};
+
+/// Opens Switch PM for [projectId]'s Product Manager ([SwarmSwitchPmDialog]),
+/// when [reader]'s person is still offered it ([swarmCanSwitchPm]).
+Future<void> showSwarmSwitchPm(
+ BuildContext context,
+ SwarmReader reader,
+ String projectId,
+) async {
+ if (!context.mounted || !swarmCanSwitchPm(reader, projectId)) return;
+ await showDialog<void>(
+ context: context,
+ builder: (_) => SwarmSwitchPmDialog(reader: reader, projectId: projectId),
+ );
+}
+
+const _notSent = 'Could not reach this Swarm. Try again.';
+
+/// Switch PM, as Desktop's dialog: the machine it runs on, or another to
+/// move it to ([swarmSwitchPmMachines]); that machine's accounts to pick one
+/// of; the model it starts on, Default or one of the Swarm's catalog (read
+/// once as it opens: unread, Default alone); what a switch does; and
+/// Switch, which is the confirmation — it stops the PM's session and starts
+/// another in the account picked. Another machine forgets the account and
+/// model picked, and another account the model. While its machine cannot
+/// switch it ([swarmSwitchPmRefusal]), or no account can be picked, it says
+/// so under the list and Switch waits. A refusal stays under the list. It
+/// follows the Swarm while open, and goes once the PM can no longer be
+/// switched from here: access lost, a viewer now, another PM, or a switch
+/// asked for elsewhere.
+class SwarmSwitchPmDialog extends StatefulWidget {
+ const SwarmSwitchPmDialog({
+ super.key,
+ required this.reader,
+ required this.projectId,
+ });
+
+ final SwarmReader reader;
+ final String projectId;
+
+ @override
+ State<SwarmSwitchPmDialog> createState() => _SwarmSwitchPmDialogState();
+}
+
+class _SwarmSwitchPmDialogState extends State<SwarmSwitchPmDialog> {
+ /// The PM it opened on: another one there meanwhile closes it.
+ late final String? _pmId = swarmLeadOf(
+ widget.reader.snapshot,
+ widget.projectId,
+ )?.id;
+
+ /// The machine whose accounts it lists: the PM's own until another is
+ /// chosen.
+ late String? _machineId = swarmLeadOf(
+ widget.reader.snapshot,
+ widget.projectId,
+ )?.machineId;
+ ({String engine, String id})? _picked;
+
+ /// The model picked; null is Default.
+ String? _model;
+ List<SwarmSwitchPmModel> _catalog = const [];
+ bool _busy = false, _closed = false;
+ String? _error;
+
+ /// This ask's receipt: kept while its answer may have been lost on the
+ /// way, so trying again is the same command; a new one once the server
+ /// refused it, or for another ask.
+ String _operationId = superTabOperationId();
+
+ /// The command [_operationId] last carried.
+ Map<String, dynamic>? _asked;
+
+ bool get _holds =>
+ _pmId != null &&
+ swarmCanSwitchPm(widget.reader, widget.projectId) &&
+ swarmLeadOf(widget.reader.snapshot, widget.projectId)?.id == _pmId;
+
+ @override
+ void initState() {
+ super.initState();
+ widget.reader.addListener(_moved);
+ unawaited(_readCatalog());
+ }
+
+ @override
+ void dispose() {
+ widget.reader.removeListener(_moved);
+ super.dispose();
+ }
+
+ /// The Swarm's model catalog, as Desktop's dialog reads it once; a read
+ /// that fails leaves Default alone.
+ Future<void> _readCatalog() async {
+ final reader = widget.reader;
+ try {
+ final answer = await reader.request(
+ 'GET',
+ '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}/routing-policy',
+ );
+ final catalog = swarmSwitchPmCatalog(answer);
+ if (mounted) setState(() => _catalog = catalog);
+ } catch (_) {
+ // The engine's own model, Default, is still there to pick.
+ }
+ }
+
+ void _moved() {
+ if (!mounted || _closed) return;
+ // While its own ask is out, its answer decides.
+ if (_busy || _holds) {
+ setState(() {});
+ return;
+ }
+ _close();
+ }
+
+ /// Goes once this frame is done: not while the reader tells its listeners.
+ void _close() {
+ if (_closed) return;
+ _closed = true;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted) return;
+ final route = ModalRoute.of(context);
+ if (route != null && route.isActive) route.navigator?.removeRoute(route);
+ });
+ }
+
+ Future<void> _switch(Map<String, dynamic> command) async {
+ if (_busy || _closed) return;
+ final reader = widget.reader;
+ // An answer lost on the way is asked for again by the same receipt; a
+ // different ask is a new one.
+ if (_asked != null && !_same(_asked!, command)) {
+ _operationId = superTabOperationId();
+ }
+ _asked = command;
+ setState(() {
+ _busy = true;
+ _error = null;
+ });
+ String? error;
+ try {
+ await reader.request(
+ 'POST',
+ '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}/commands',
+ body: {'operationId': _operationId, 'command': command},
+ );
+ } on SuperTabFailure catch (failure) {
+ error = failure.message;
+ if (failure.statusCode >= 400 && failure.statusCode < 500) {
+ _operationId = superTabOperationId();
+ _asked = null;
+ }
+ } catch (_) {
+ // A call lost on the way (a timeout, a socket dropped) is no answer.
+ error = _notSent;
+ }
+ // Switching… once the Swarm is read again.
+ if (error == null) unawaited(reader.refresh());
+ if (!mounted || _closed) return;
+ if (error == null) {
+ _closed = true;
+ Navigator.of(context).pop();
+ return;
+ }
+ setState(() {
+ _busy = false;
+ _error = error;
+ });
+ if (!_holds) _close();
+ }
+
+ static bool _same(Map<String, dynamic> a, Map<String, dynamic> b) =>
+ a.length == b.length && a.keys.every((k) => b[k] == a[k]);
+
+ Widget _row(SwarmSwitchPmChoice choice, bool picked, bool machineOpen) {
+ final p = choice.profile;
+ final pickable = machineOpen && swarmSwitchPmPickable(choice);
+ final detail = swarmSwitchPmDetail(choice);
+ return Semantics(
+ selected: picked,
+ child: InkWell(
+ key: ValueKey('swarm-switch-pm-${p.engine}-${p.id}'),
+ borderRadius: BorderRadius.circular(AppControl.radius),
+ onTap: pickable && !_busy
+ ? () => setState(() {
+ _picked = (engine: p.engine, id: p.id);
+ _model = null;
+ _error = null;
+ })
+ : null,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(minHeight: minTouchTarget),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(vertical: AppSpace.xs),
+ child: Row(
+ children: [
+ Expanded(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ swarmSwitchPmLabel(p),
+ style: AppType.body(
+ color: pickable
+ ? AppPalette.textPrimary
+ : AppPalette.textFaint,
+ ),
+ ),
+ if (detail.isNotEmpty)
+ Text(
+ detail,
+ style: AppType.caption(
+ color: AppPalette.textSecondary,
+ ),
+ ),
+ ],
+ ),
+ ),
+ if (picked)
+ Padding(
+ padding: const EdgeInsets.only(left: AppSpace.s),
+ child: Icon(
+ LucideIcons.check300,
+ size: 18,
+ color: AppPalette.accentOnSurface,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _quiet(String text, {Key? key, double top = AppSpace.s}) => Padding(
+ padding: EdgeInsets.only(top: top),
+ child: Text(
+ text,
+ key: key,
+ style: AppType.caption(color: AppPalette.textSecondary),
+ ),
+ );
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final reader = widget.reader;
+ final snapshot = reader.snapshot;
+ final lead = swarmLeadOf(snapshot, widget.projectId);
+ final now = DateTime.now();
+ final machines = swarmSwitchPmMachines(reader, widget.projectId, now: now);
+ // A machine chosen that left the list: back to the PM's own, with
+ // nothing picked on it (Desktop's).
+ if (lead != null &&
+ _machineId != lead.machineId &&
+ !machines.any((m) => m.id == _machineId)) {
+ _machineId = lead.machineId;
+ _picked = null;
+ _model = null;
+ }
+ final machineId = _machineId ?? lead?.machineId;
+ final active = machines.where((m) => m.id == machineId).firstOrNull;
+ final activePool = machineId == null ? null : snapshot?.pool(machineId);
+ final machineOpen = active != null && active.unavailable == null;
+ List<SwarmSwitchPmChoice> choicesOn(String id) => snapshot == null
+ ? const <SwarmSwitchPmChoice>[]
+ : swarmSwitchPmChoices(snapshot, widget.projectId, machineId: id);
+ final choices = machineId == null
+ ? const <SwarmSwitchPmChoice>[]
+ : choicesOn(machineId);
+ bool isPicked(SuperTabProfile p) =>
+ _picked?.engine == p.engine && _picked?.id == p.id;
+ // A pick that can no longer be made (it ran out meanwhile) is none.
+ final picked =
+ machineOpen &&
+ choices.any((c) => swarmSwitchPmPickable(c) && isPicked(c.profile))
+ ? _picked
+ : null;
+ final models = swarmSwitchPmModels(
+ _catalog,
+ picked?.engine ?? lead?.engine ?? '',
+ );
+ if (_model != null && !models.contains(_model)) _model = null;
+ final others = [
+ for (final m in machines)
+ if (!m.current && m.unavailable == null) m,
+ ];
+ final noChoice =
+ !(machineOpen && choices.any(swarmSwitchPmPickable)) &&
+ !others.any(
+ (m) => choicesOn(m.id).any((c) => c.profile.leftPercent != 0),
+ );
+ final refusal = swarmSwitchPmRefusal(reader, widget.projectId, now: now);
+ final note =
+ refusal ??
+ (!noChoice
+ ? null
+ : others.isEmpty
+ ? 'No other machine or account can run a Product Manager right '
+ 'now.'
+ : 'No engine or account can run a Product Manager right now.');
+ final command = picked == null || lead == null || machineId == null
+ ? null
+ : swarmSwitchPmCommand(
+ projectId: widget.projectId,
+ picked: picked,
+ currentMachineId: lead.machineId,
+ machineId: machineId,
+ model: _model,
+ );
+ return PopScope(
+ // Its ask out, its answer decides whether it goes.
+ canPop: !_busy,
+ child: AlertDialog(
+ title: Text(
+ 'Switch PM',
+ style: AppType.heading(color: AppPalette.textPrimary),
+ ),
+ content: SizedBox(
+ width: double.maxFinite,
+ child: SingleChildScrollView(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ _SwitchPmPicker<String>(
+ key: const ValueKey('swarm-switch-pm-machine'),
+ label: 'Machine',
+ value: machineId,
+ options: [
+ for (final m in machines)
+ (
+ value: m.id,
+ key: 'swarm-switch-pm-machine-${m.id}',
+ label: [m.name, if (m.current) 'Current'].join(' · '),
+ detail: m.unavailable,
+ enabled: m.unavailable == null,
+ ),
+ ],
+ onChanged: _busy
+ ? null
+ : (id) => setState(() {
+ _machineId = id;
+ _picked = null;
+ _model = null;
+ _error = null;
+ }),
+ ),
+ if (choices.isEmpty)
+ _quiet(
+ active?.unavailable ??
+ 'No engine or account is available on this machine.',
+ ),
+ for (final choice in choices)
+ _row(
+ choice,
+ picked != null && isPicked(choice.profile),
+ machineOpen,
+ ),
+ _SwitchPmPicker<String?>(
+ key: const ValueKey('swarm-switch-pm-model'),
+ label: 'Model',
+ value: _model,
+ options: [
+ (
+ value: null,
+ key: 'swarm-switch-pm-model-default',
+ label: 'Default',
+ detail: null,
+ enabled: true,
+ ),
+ for (final model in models)
+ (
+ value: model,
+ key: 'swarm-switch-pm-model-$model',
+ label: model,
+ detail: null,
+ enabled: true,
+ ),
+ ],
+ onChanged: _busy
+ ? null
+ : (model) => setState(() => _model = model),
+ ),
+ if (note != null)
+ _quiet(
+ note,
+ key: const ValueKey('swarm-switch-pm-no-choice'),
+ ),
+ if (activePool != null &&
+ activePool['contributorId'] != reader.accountId)
+ _quiet('Only accounts its owner offered are listed.'),
+ Padding(
+ padding: const EdgeInsets.only(top: AppSpace.m),
+ child: Text(
+ 'The new session starts fresh and reads a handoff note. '
+ 'Tasks and chat stay.',
+ style: AppType.body(color: AppPalette.textSecondary),
+ ),
+ ),
+ if (_error case final error?)
+ Padding(
+ padding: const EdgeInsets.only(top: AppSpace.s),
+ child: Text(
+ error,
+ key: const ValueKey('swarm-switch-pm-error'),
+ style: AppType.caption(color: AppColors.danger),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ actions: [
+ SwarmButton(
+ key: const ValueKey('swarm-switch-pm-cancel'),
+ label: 'Cancel',
+ style: SwarmButtonStyle.link,
+ onPressed: _busy
+ ? null
+ : () {
+ _closed = true;
+ Navigator.of(context).pop();
+ },
+ ),
+ SwarmButton(
+ key: const ValueKey('swarm-switch-pm-confirm'),
+ label: 'Switch',
+ style: SwarmButtonStyle.fill,
+ busy: _busy,
+ busyLabel: 'Switching…',
+ onPressed: _busy || command == null || refusal != null || noChoice
+ ? null
+ : () => unawaited(_switch(command)),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+/// One choice of a [_SwitchPmPicker]: its value, its row's key, its words,
+/// and, for one that cannot be chosen, why under them.
+typedef _SwitchPmOption<T> = ({
+ T value,
+ String key,
+ String label,
+ String? detail,
+ bool enabled,
+});
+
+/// Switch PM's Machine and Model rows, as Desktop's select fields: [label]
+/// at its start, the choice made at its end with a chevron, and a tap opens
+/// a menu of [options] on the design system's menu surface, the choice
+/// made ticked, one that cannot be chosen dimmed with why under it. Fixed
+/// while [onChanged] is null.
+class _SwitchPmPicker<T> extends StatelessWidget {
+ const _SwitchPmPicker({
+ super.key,
+ required this.label,
+ required this.value,
+ required this.options,
+ required this.onChanged,
+ });
+
+ final String label;
+ final T? value;
+ final List<_SwitchPmOption<T>> options;
+ final ValueChanged<T>? onChanged;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final shown = options.where((o) => o.value == value).firstOrNull?.label;
+ final enabled = onChanged != null;
+ // As wide as the phone allows, so a machine's why wraps inside it.
+ final widest = MediaQuery.sizeOf(context).width - 2 * AppSpace.screenInset;
+ return MenuAnchor(
+ style: AppMenu.style(maxWidth: widest),
+ // Held to [widest], so long words wrap rather than run off the phone.
+ crossAxisUnconstrained: false,
+ alignmentOffset: const Offset(0, AppSpace.xs),
+ menuChildren: [
+ for (final option in options)
+ MenuItemButton(
+ key: ValueKey(option.key),
+ style: ButtonStyle(
+ minimumSize: const WidgetStatePropertyAll(
+ Size(AppSpace.xl * 6, minTouchTarget),
+ ),
+ foregroundColor: WidgetStateProperty.resolveWith(
+ (states) => states.contains(WidgetState.disabled)
+ ? AppPalette.textFaint
+ : AppPalette.textPrimary,
+ ),
+ textStyle: WidgetStatePropertyAll(AppType.body()),
+ ),
+ onPressed: option.enabled && enabled
+ ? () => onChanged!(option.value)
+ : null,
+ trailingIcon: option.value == value
+ ? Icon(
+ LucideIcons.check300,
+ size: AppIconSize.besideText,
+ color: AppPalette.accentOnSurface,
+ )
+ : null,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(vertical: AppSpace.xs),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(option.label),
+ if (option.detail case final detail?)
+ Text(
+ detail,
+ style: AppType.caption(color: AppPalette.textSecondary),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ],
+ builder: (context, menu, _) => Semantics(
+ button: true,
+ enabled: enabled,
+ label: '$label: ${shown ?? ''}',
+ excludeSemantics: true,
+ child: InkWell(
+ borderRadius: BorderRadius.circular(AppControl.radius),
+ onTap: enabled
+ ? () => menu.isOpen ? menu.close() : menu.open()
+ : null,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(minHeight: minTouchTarget),
+ child: Row(
+ children: [
+ Text(
+ label,
+ style: AppType.label(color: AppPalette.textSecondary),
+ ),
+ const SizedBox(width: AppSpace.m),
+ // Two lines before it is cut: "Ken's MacBook Pro · Current"
+ // whole on a narrow phone.
+ Expanded(
+ child: Text(
+ shown ?? '',
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ textAlign: TextAlign.end,
+ style: AppType.label(
+ color: enabled
+ ? AppPalette.textPrimary
+ : AppPalette.textSecondary,
+ ),
+ ),
+ ),
+ const SizedBox(width: AppSpace.xs),
+ Icon(
+ LucideIcons.chevronDown300,
+ size: AppIconSize.besideText,
+ color: AppPalette.textSecondary,
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/swarm/swarm_tabs.dart b/mobile/lib/swarm/swarm_tabs.dart
index e517d078e..1cac94010 100644
--- a/mobile/lib/swarm/swarm_tabs.dart
+++ b/mobile/lib/swarm/swarm_tabs.dart
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
+import 'package:harness_mobile/notify/system_notices.dart';
import 'package:harness_mobile/phone/out_of_sight.dart';
import 'package:harness_mobile/phone/tty.dart';
import 'package:harness_mobile/shared/theme/app_space.dart';
@@ -116,11 +117,14 @@ bool showSwarmTab(
/// Back on another tab goes to Home first; at Home, and while Harness covers
/// the tabs, back is not the tabs'.
class SwarmTabsPage extends StatefulWidget {
- const SwarmTabsPage({super.key, this.onSettings, this.tabs});
+ const SwarmTabsPage({super.key, this.onSettings, this.notices, this.tabs});
/// The phone's Settings, from You ([SwarmYouSettings]).
final void Function(BuildContext context)? onSettings;
+ /// The phone's notice centre, for You's Notifications ([SwarmYouSettings]).
+ final SystemNotices? notices;
+
/// The tabs, in the bar's order; [swarmTabs] when null.
final List<SwarmTabEntry>? tabs;
@@ -212,6 +216,7 @@ class _SwarmTabsPageState extends State<SwarmTabsPage> {
asks: _activityAsks,
child: SwarmYouSettings(
onSettings: widget.onSettings,
+ notices: widget.notices,
onOpened: _youOpened,
child: Scaffold(
backgroundColor: Tty.of(context).ground,
diff --git a/mobile/lib/swarm/swarm_voice_bubble.dart b/mobile/lib/swarm/swarm_voice_bubble.dart
index 9853153bc..326110b0c 100644
--- a/mobile/lib/swarm/swarm_voice_bubble.dart
+++ b/mobile/lib/swarm/swarm_voice_bubble.dart
@@ -7,6 +7,7 @@ import 'package:flutter/services.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:video_player/video_player.dart';
+import 'package:harness_mobile/logging/app_log.dart';
import 'package:harness_mobile/phone/tty.dart';
import 'package:harness_mobile/shared/theme/app_icon_size.dart';
import 'package:harness_mobile/shared/theme/app_ink.dart';
@@ -41,7 +42,13 @@ Future<File?> _cachedCopy(BuildContext context, SwarmFileRef ref) async {
final link = await swarmOpenableLink(context, ref, stale: stale);
if (link == null) return null;
try {
- return await swarmAttachments.file(link, key: 'voice:${ref.file.id}');
+ // Not the `voice:` copies kept until 11-04: those were kept as .bin,
+ // which an iPhone does not play (swarmKeptExtension). Unopened, they go
+ // after swarmAttachmentStale.
+ return await swarmAttachments.file(
+ link,
+ key: 'voice-clip:${ref.file.id}',
+ );
} on Object {
// The link may have run out in between: once more with a fresh one.
}
@@ -119,7 +126,13 @@ class _SwarmVoiceBubbleState extends State<SwarmVoiceBubble> {
made.addListener(_changed);
_player = made;
await made.play();
- } on Object {
+ } on Object catch (error, stack) {
+ appLog.failure(
+ 'swarm',
+ 'A voice message could not be played',
+ error: error,
+ stackTrace: stack,
+ );
unawaited(made.dispose());
if (mounted) _problem = "Couldn't play it · tap to try again";
}
diff --git a/mobile/lib/swarm/swarm_you_page.dart b/mobile/lib/swarm/swarm_you_page.dart
index 5e6605013..b31e71a7d 100644
--- a/mobile/lib/swarm/swarm_you_page.dart
+++ b/mobile/lib/swarm/swarm_you_page.dart
@@ -4,14 +4,18 @@ import 'package:clock/clock.dart';
import 'package:flutter/material.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
+import 'package:harness_mobile/notify/system_notices.dart';
import 'package:harness_mobile/phone/out_of_sight.dart';
import 'package:harness_mobile/phone/phone_navigation.dart';
+import 'package:harness_mobile/phone/settings_page.dart'
+ show NotificationsSettingsRow;
+import 'package:harness_mobile/phone/settings_row.dart' show SettingsSwarmLook;
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 'package:harness_mobile/shared/theme/app_type.dart';
+import 'package:harness_mobile/shared/theme/appearance_prefs_store.dart';
import 'package:harness_mobile/shared/widgets/touch_target.dart';
-import 'package:harness_mobile/theme/app_theme.dart' show AppColors;
import 'model.dart';
import 'swarm_devices_page.dart';
@@ -24,33 +28,42 @@ import 'swarm_session.dart';
import 'swarm_start.dart';
import 'swarm_style.dart';
-/// Where You's Settings row goes: the shell's, handed down by Swarm's tabs to
-/// whatever opens You from under them ([openSwarmYou]); and the tabs told of
-/// each You opened over them ([onOpened]), to take it with them when they go.
+/// Where You's Settings row goes, and the notice centre its Notifications
+/// reads: the shell's, handed down by Swarm's tabs to whatever opens You from
+/// under them ([openSwarmYou]); and the tabs told of each You opened over them
+/// ([onOpened]), to take it with them when they go.
class SwarmYouSettings extends InheritedWidget {
const SwarmYouSettings({
super.key,
required this.onSettings,
+ this.notices,
this.onOpened,
required super.child,
});
final void Function(BuildContext context)? onSettings;
+ /// The phone's notice centre, for You's Notifications; null where it has
+ /// none to turn on (the sample).
+ final SystemNotices? notices;
+
/// A You opened over the tabs: it goes with them.
final ValueChanged<Route<void>>? onOpened;
@override
bool updateShouldNotify(SwarmYouSettings oldWidget) =>
- onSettings != oldWidget.onSettings || onOpened != oldWidget.onOpened;
+ onSettings != oldWidget.onSettings ||
+ notices != oldWidget.notices ||
+ onOpened != oldWidget.onOpened;
}
-/// Opens You over [context]'s page, its Settings the tabs' ([SwarmYouSettings]),
-/// and tells the tabs, which take it with them when they go.
+/// Opens You over [context]'s page, its Settings and notices the tabs'
+/// ([SwarmYouSettings]), and tells the tabs, which take it with them when they
+/// go.
void openSwarmYou(BuildContext context) {
final scope = context.getInheritedWidgetOfExactType<SwarmYouSettings>();
final route = phoneRoute(
- (_) => SwarmYouPage(onSettings: scope?.onSettings),
+ (_) => SwarmYouPage(onSettings: scope?.onSettings, notices: scope?.notices),
listensForItself: true,
);
scope?.onOpened?.call(route);
@@ -126,20 +139,36 @@ class SwarmYouButton extends StatelessWidget {
/// You, as Tony's prototype C4 draws it (2026-10-30), opened from the avatar
/// on Home and Activity since it stopped being a tab (2026-11-03):
/// who they are in the Swarm Home shows — their face, their name and that
-/// Swarm — then their name with their status under it in one row ([_Profile]),
-/// and their username, each with Change for their profile, where it is set
-/// ([showSwarmProfile]); Your models, with how many of their own machines'
-/// models the Swarms can use now, and Your devices, with how many of their
-/// own computers are online; and Settings. Only what is theirs counts: not a
-/// teammate's, not one shared with them, not a Harness Team account's (#2253's
-/// review). Each count comes from what Home already reads, and none shows
-/// before it is read.
+/// Swarm — which opens their profile, where name, username, picture and status
+/// are set ([showSwarmProfile]); Your models, with how many of their own
+/// machines' models the Swarms can use now, and Your devices, with how many of
+/// their own computers are online; then Notifications and Theme, out of
+/// Settings, and Settings. Only what is theirs counts: not a teammate's, not
+/// one shared with them, not a Harness Team account's (#2253's review). Each
+/// count comes from what Home already reads, and none shows before it is read.
+///
+/// Tony 2026-11-04: the Profile and Username rows under the header opened the
+/// same sheet the header now does, so they went; Notifications and Theme came
+/// up out of Settings, one tap nearer.
class SwarmYouPage extends StatelessWidget {
- const SwarmYouPage({super.key, this.onSettings, this.now = DateTime.now});
+ const SwarmYouPage({
+ super.key,
+ this.onSettings,
+ this.notices,
+ this.appearance,
+ this.now = DateTime.now,
+ });
/// The phone's Settings over the tabs.
final void Function(BuildContext context)? onSettings;
+ /// The phone's notice centre, for Notifications; none shows without it.
+ final SystemNotices? notices;
+
+ /// What Theme changes: [appearancePrefsStore] unless a test hands in its
+ /// own, so a tap there never writes to the developer's own state file.
+ final AppearancePrefsStore? appearance;
+
/// What a model's reading is fresh against.
final DateTime Function() now;
@@ -205,38 +234,16 @@ class SwarmYouPage extends StatelessWidget {
void open(Widget page) => unawaited(
navigator.push(phoneRoute((_) => page, listensForItself: true)),
);
- final profile = me == null
- ? null
- : () => unawaited(showSwarmProfile(context, swarmId: you!.id));
+ final notices = this.notices;
return [
_Me(
key: const ValueKey('swarm-you-me'),
me: me,
swarm: me == null ? null : you!.name,
- ),
- const SwarmCaption('Profile'),
- SwarmGroup(
- children: [
- _Profile(
- key: const ValueKey('swarm-you-profile'),
- me: me,
- onTap: profile,
- ),
- ],
- ),
- const SwarmCaption('Username'),
- SwarmGroup(
- children: [
- SwarmRow(
- key: const ValueKey('swarm-you-username'),
- leading: const SwarmRowGlyph(LucideIcons.atSign300),
- // How the Swarm tags them, as the server keeps it; nothing of a
- // Swarm before it is read, or once it is taken away.
- title: me?.username ?? 'Username',
- trailing: profile == null ? null : const _Change(),
- onTap: profile,
- ),
- ],
+ // Nothing to set before the Swarm is read, or once it is taken away.
+ onTap: me == null
+ ? null
+ : () => unawaited(showSwarmProfile(context, swarmId: you!.id)),
),
const SizedBox(height: AppSpace.l),
SwarmGroup(
@@ -267,6 +274,18 @@ class SwarmYouPage extends StatelessWidget {
const SizedBox(height: AppSpace.l),
SwarmGroup(
children: [
+ // The terminal Settings' own row, drawn as Swarm's ([SettingsSwarmLook]).
+ if (notices != null)
+ SettingsSwarmLook(
+ child: NotificationsSettingsRow(
+ key: const ValueKey('swarm-you-notifications'),
+ notices: notices,
+ ),
+ ),
+ _Theme(
+ key: const ValueKey('swarm-you-theme'),
+ store: appearance ?? appearancePrefsStore,
+ ),
SwarmRow(
key: const ValueKey('swarm-you-settings'),
leading: const SwarmRowGlyph(LucideIcons.settings300),
@@ -323,24 +342,34 @@ class SwarmYouPage extends StatelessWidget {
}
/// The person at the top of You: their face, their name and the Swarm it is
-/// in; "You" alone before a Swarm is read with them in it.
+/// in; "You" alone before a Swarm is read with them in it. A tap ([onTap])
+/// opens their profile, and a chevron says so; none before they are read.
class _Me extends StatelessWidget {
- const _Me({super.key, required this.me, required this.swarm});
+ const _Me({
+ super.key,
+ required this.me,
+ required this.swarm,
+ required this.onTap,
+ });
final SuperTabPerson? me;
final String? swarm;
+ final VoidCallback? onTap;
@override
Widget build(BuildContext context) {
AppTheme.watch(context);
final me = this.me;
+ final onTap = this.onTap;
// A Home kept for a cold start holds no email.
final name = me == null || me.email.isEmpty ? 'You' : me.shownName;
- return Padding(
+ final header = Padding(
+ // On the right as far in as a card's rows, so its chevron stands over
+ // theirs.
padding: const EdgeInsets.fromLTRB(
AppSpace.xs,
AppSpace.s,
- AppSpace.xs,
+ AppSpace.l,
AppSpace.xs,
),
child: Row(
@@ -376,76 +405,74 @@ class _Me extends StatelessWidget {
],
),
),
+ if (onTap != null) ...[
+ const SizedBox(width: AppSpace.m),
+ Icon(
+ LucideIcons.chevronRight300,
+ size: 18,
+ color: AppPalette.textFaint,
+ ),
+ ],
],
),
);
+ if (onTap == null) return header;
+ return Semantics(
+ button: true,
+ child: Material(
+ color: Colors.transparent,
+ child: InkWell(
+ borderRadius: BorderRadius.circular(AppCard.radius),
+ onTap: onTap,
+ child: header,
+ ),
+ ),
+ );
}
}
-/// The person's name and status in one row, both set in their profile
-/// (Tony 2026-11-04: a Status row and a Name row opened the same sheet). The
-/// name the Swarm shows them by, "Add your name" until they set one; under it
-/// their status after a dot, Active while none is set; Change for their
-/// profile. "Name" and "Set a status", with no way in, before they are read.
-class _Profile extends StatelessWidget {
- const _Profile({super.key, required this.me, required this.onTap});
+/// Light or dark: System | Dark | Light (#2920), on You since 2026-11-04,
+/// out of Swarm's Settings.
+///
+/// One tap, and every screen turns at once — the page behind is the preview —
+/// except the terminal's page, which keeps the dark side
+/// ([AppearancePrefs.terminalPalette]). Dark and Light keep the palette the
+/// terminal Settings' App colors chose while it is on their side, else
+/// Graphite and Paper. System follows the phone as it turns. Until it is
+/// touched, the control shows the side the palette is on, which is what that
+/// answer would draw.
+class _Theme extends StatelessWidget {
+ const _Theme({super.key, required this.store});
- final SuperTabPerson? me;
- final VoidCallback? onTap;
+ final AppearancePrefsStore store;
@override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- final me = this.me;
- Widget row(String status, {required bool known}) => SwarmRow(
- leading: const SwarmRowGlyph(LucideIcons.user300),
- // Nothing of a Swarm before it is read, or once it is taken away.
- title: me == null ? 'Name' : me.name ?? 'Add your name',
- detail: Row(
- key: const ValueKey('swarm-you-status'),
- children: [
- Container(
- width: 8,
- height: 8,
- decoration: BoxDecoration(
- shape: BoxShape.circle,
- color: known ? AppColors.success : AppPalette.textFaint,
+ Widget build(BuildContext context) => ValueListenableBuilder<AppearancePrefs>(
+ valueListenable: store,
+ builder: (context, prefs, _) {
+ AppTheme.watch(context);
+ return SwarmRow(
+ leading: const SwarmRowGlyph(LucideIcons.sunMoon300),
+ title: 'Theme',
+ // A little over half the row, so the title keeps its word at the
+ // largest text size; past that the control shrinks rather than
+ // pushing the row over its edge.
+ trailing: ConstrainedBox(
+ constraints: BoxConstraints(
+ maxWidth: MediaQuery.sizeOf(context).width * .55,
+ ),
+ child: FittedBox(
+ fit: BoxFit.scaleDown,
+ child: SwarmSegments<AppThemeMode>(
+ values: AppThemeMode.values,
+ selected: prefs.shownThemeMode,
+ label: (mode) => mode.label,
+ onSelected: (mode) => unawaited(store.setThemeMode(mode)),
),
),
- const SizedBox(width: AppSpace.s),
- Flexible(child: SwarmRow.line(status)),
- ],
- ),
- trailing: onTap == null ? null : const _Change(),
- onTap: onTap,
- );
- if (me == null) return row('Set a status', known: false);
- return SwarmUntil(
- until: me.status?.until,
- builder: (context) =>
- row(me.statusAt(clock.now())?.label ?? 'Active', known: true),
- );
- }
-}
-
-/// "Change ›", at the end of a row that opens the person's profile.
-class _Change extends StatelessWidget {
- const _Change();
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- return Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Text('Change', style: AppType.label(color: AppPalette.textSecondary)),
- const SizedBox(width: AppSpace.xs),
- Icon(
- LucideIcons.chevronRight300,
- size: 18,
- color: AppPalette.textFaint,
),
- ],
- );
- }
+ onTap: null,
+ );
+ },
+ );
}
diff --git a/mobile/lib/swarm/team_glance.dart b/mobile/lib/swarm/team_glance.dart
index b3595ddf0..8ada779d8 100644
--- a/mobile/lib/swarm/team_glance.dart
+++ b/mobile/lib/swarm/team_glance.dart
@@ -173,6 +173,11 @@ SwarmAgentGlance _glance(
String two(int n) => n.toString().padLeft(2, '0');
// The desktop's order, less what only the agent's computer can say.
final (state, label) = switch (null) {
+ // A PM being moved to another engine or account (Switch PM).
+ _ when agent.switchRequest != null => (
+ SwarmAgentState.working,
+ 'Switching…',
+ ),
_ when work == 'lost' => (SwarmAgentState.down, 'Lost'),
_ when agent.downSince != null => (SwarmAgentState.down, 'Down'),
_ when until != null && until.isAfter(at) => (
diff --git a/mobile/test/phone/phone_shell_swarm_home_test.dart b/mobile/test/phone/phone_shell_swarm_home_test.dart
index 682fb5b32..2082a9b7a 100644
--- a/mobile/test/phone/phone_shell_swarm_home_test.dart
+++ b/mobile/test/phone/phone_shell_swarm_home_test.dart
@@ -145,6 +145,37 @@ void main() {
);
});
+ testWidgets("You's Notifications asks the phone's own notice centre, and "
+ "Settings under it has none of its own", (tester) async {
+ await open(tester);
+ await openYou(tester);
+
+ expect(
+ tester
+ .widget<NotificationsSettingsRow>(
+ find.descendant(
+ of: find.byType(SwarmYouPage),
+ matching: find.byType(NotificationsSettingsRow),
+ ),
+ )
+ .notices,
+ same(app.agentNotices.system),
+ );
+
+ await tester.ensureVisible(key('swarm-you-settings'));
+ await tester.pump();
+ await tester.tap(key('swarm-you-settings'));
+ await frames(tester);
+ expect(find.byType(SettingsPage), findsOneWidget);
+ expect(
+ find.descendant(
+ of: find.byType(SettingsPage),
+ matching: find.byType(NotificationsSettingsRow),
+ ),
+ findsNothing,
+ );
+ });
+
testWidgets('an agent explicitly opened puts the terminal at the root; '
'back goes to Swarm Home; each keeps the other out of sight', (
tester,
diff --git a/mobile/test/phone_edge/settings_swarm_look_test.dart b/mobile/test/phone_edge/settings_swarm_look_test.dart
index d3cc29a42..22f810253 100644
--- a/mobile/test/phone_edge/settings_swarm_look_test.dart
+++ b/mobile/test/phone_edge/settings_swarm_look_test.dart
@@ -6,6 +6,7 @@ import 'package:harness_mobile/phone/settings_page.dart';
import 'package:harness_mobile/phone/settings_row.dart';
import 'package:harness_mobile/phone/tty.dart';
import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/shared/theme/appearance_prefs_store.dart';
import 'package:harness_mobile/state/app_state.dart';
import 'package:harness_mobile/swarm/swarm_row.dart';
import 'package:harness_mobile/swarm/swarm_style.dart';
@@ -17,10 +18,10 @@ import 'edge_fixture.dart';
/// Settings opened from Swarm's You wears Swarm's pages (prototype A lean, 2026-11-03,
/// `docs/design/2026-11-03-swarm-settings.md`): Swarm's top bar, sentence-case captions, cards of
-/// Swarm rows each led by a glyph, in the app's face; the account's rows in three cards;
-/// Notifications and Swarm with no line under them; Language in Terminal's card; Help and About
-/// one row each, opening a sheet of what they held. Opened from anywhere else, it keeps the
-/// phone's own look.
+/// Swarm rows each led by a glyph, in the app's face; the account's rows in three cards; Swarm
+/// with no line under it; Language in Terminal's card; Help and About one row each, opening a
+/// sheet of what they held; no Notifications or Theme, which are on You (2026-11-04). Opened from
+/// anywhere else, it keeps the phone's own look.
///
/// No choice is made in any sheet or stepper: those write through stores whose home is the real
/// state file (see `settings_behavior_test.dart`).
@@ -149,7 +150,6 @@ void main() {
// Top to bottom, as the list goes: it builds only what it shows.
for (final (title, glyph) in [
('Usage', LucideIcons.gauge300),
- ('Notifications', LucideIcons.bell300),
('Privacy', LucideIcons.shield300),
('Computers', LucideIcons.laptop300),
('Connectors', LucideIcons.plug300),
@@ -160,7 +160,6 @@ void main() {
('Size', LucideIcons.aLargeSmall300),
('Colors', LucideIcons.palette300),
('Language', LucideIcons.mic300),
- ('Theme', LucideIcons.sunMoon300),
('Text size', LucideIcons.aLargeSmall300),
('Swarm', LucideIcons.flaskConical300),
('Help', LucideIcons.circleHelp300),
@@ -203,7 +202,7 @@ void main() {
'use, your computers, this phone', (tester) async {
final app = await openSettings(tester, swarm: true);
- for (final row in ['Usage', 'Notifications', 'Privacy']) {
+ for (final row in ['Usage', 'Privacy']) {
expect(inCard('Ada Lovelace', row), findsOneWidget, reason: row);
}
expect(inCard('Usage', 'Computers'), findsNothing);
@@ -314,13 +313,21 @@ void main() {
await close(tester, app);
});
- testWidgets('Notifications says on or off, with no line under it', (
- tester,
- ) async {
+ testWidgets('no Notifications and no Theme: they are on You, one tap '
+ 'nearer (2026-11-04)', (tester) async {
final app = await openSettings(tester, swarm: true);
- expect(rowOf('Notifications'), findsOneWidget);
- expect(find.textContaining('a harness finishes'), findsNothing);
+ expect(inCard('Ada Lovelace', 'Usage'), findsOneWidget);
+ expect(find.text('Notifications'), findsNothing);
+ expect(
+ find.byKey(const ValueKey('settings-notifications')),
+ findsNothing,
+ );
+
+ await reveal(tester, find.text('Text size'));
+ expect(find.text('Theme'), findsNothing);
+ expect(find.byType(SwarmSegments<AppThemeMode>), findsNothing);
+ expect(find.text('App colors'), findsNothing, reason: 'nor the palettes');
await close(tester, app);
});
diff --git a/mobile/test/phone_edge/settings_theme_test.dart b/mobile/test/phone_edge/settings_theme_test.dart
index 8650c6973..71d9ec052 100644
--- a/mobile/test/phone_edge/settings_theme_test.dart
+++ b/mobile/test/phone_edge/settings_theme_test.dart
@@ -12,16 +12,17 @@ import 'package:harness_mobile/shared/theme/color_palette.dart';
import 'package:harness_mobile/state/app_state.dart';
import 'package:harness_mobile/swarm/swarm_row.dart';
import 'package:harness_mobile/swarm/swarm_style.dart';
+import 'package:harness_mobile/swarm/swarm_you_page.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:package_info_plus/package_info_plus.dart';
import '../voice_fakes.dart' show MemoryKeyValueStore;
import 'edge_fixture.dart';
-/// Settings opened from Swarm asks light or dark — Theme: System | Dark | Light — in App colors'
-/// place, and every screen turns on the tap; the terminal keeps the dark side. Settings opened from
-/// the terminal keeps App colors, which names the palette on screen and, picked, hands light and
-/// dark back to the palette.
+/// Swarm asks light or dark — Theme: System | Dark | Light — on its You (in its Settings, in App
+/// colors' place, until 2026-11-04), and every screen turns on the tap; the terminal keeps the dark
+/// side. Settings opened from the terminal keeps App colors, which names the palette on screen and,
+/// picked, hands light and dark back to the palette.
void main() {
setUpAll(
() => PackageInfo.setMockInitialValues(
@@ -39,12 +40,12 @@ void main() {
AppTheme.terminalPaletteOverride.value = null;
});
- /// Settings pushed over a page, in an app built as `HarnessApp` builds it: on [store]'s
+ /// [page] pushed over a page, in an app built as `HarnessApp` builds it: on the store's
/// appearance ([AppearanceBuilder]), its brightness set from the palette as `_GridTokenScope`
- /// sets it — so a choice here repaints the whole app, as it does on a phone.
- Future<(AppNotifier, AppearancePrefsStore, MemoryKeyValueStore)> openSettings(
- WidgetTester tester, {
- required bool swarm,
+ /// sets it — so a choice there repaints the whole app, as it does on a phone.
+ Future<(AppNotifier, AppearancePrefsStore, MemoryKeyValueStore)> open(
+ WidgetTester tester,
+ Widget Function(AppNotifier app, AppearancePrefsStore store) page, {
AppearancePrefs prefs = const AppearancePrefs(),
Phone phone = largePhone,
double textScale = 1,
@@ -58,13 +59,7 @@ void main() {
name: 'Ada Lovelace',
);
- final page = SettingsPage(
- notifier: app,
- large: false,
- swarm: swarm,
- experiments: ExperimentalFeaturesStore(storage: MemoryKeyValueStore()),
- appearance: store,
- );
+ final shown = page(app, store);
await tester.pumpWidget(
AppearanceBuilder(
store: store,
@@ -75,7 +70,7 @@ void main() {
builder: (context) => TextButton(
onPressed: () =>
Navigator.of(context)
- .push(MaterialPageRoute<void>(builder: (_) => page)),
+ .push(MaterialPageRoute<void>(builder: (_) => shown)),
child: const Text('open'),
),
),
@@ -90,6 +85,37 @@ void main() {
return (app, store, storage);
}
+ /// Settings, opened from Swarm's You ([swarm]) or from the terminal.
+ Future<(AppNotifier, AppearancePrefsStore, MemoryKeyValueStore)> openSettings(
+ WidgetTester tester, {
+ required bool swarm,
+ AppearancePrefs prefs = const AppearancePrefs(),
+ }) => open(
+ tester,
+ (app, store) => SettingsPage(
+ notifier: app,
+ large: false,
+ swarm: swarm,
+ experiments: ExperimentalFeaturesStore(storage: MemoryKeyValueStore()),
+ appearance: store,
+ ),
+ prefs: prefs,
+ );
+
+ /// Swarm's You, where its Theme is.
+ Future<(AppNotifier, AppearancePrefsStore, MemoryKeyValueStore)> openYou(
+ WidgetTester tester, {
+ AppearancePrefs prefs = const AppearancePrefs(),
+ Phone phone = largePhone,
+ double textScale = 1,
+ }) => open(
+ tester,
+ (_, store) => SwarmYouPage(appearance: store),
+ prefs: prefs,
+ phone: phone,
+ textScale: textScale,
+ );
+
Future<void> close(WidgetTester tester, AppNotifier app) async {
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(seconds: 3));
@@ -120,22 +146,22 @@ void main() {
)
.color;
- /// The ground Settings is drawn on.
- Color? ground(WidgetTester tester) => tester
+ /// The ground [page] is drawn on: Settings, or Swarm's You.
+ Color? ground(WidgetTester tester, [Type page = SettingsPage]) => tester
.widget<Scaffold>(
find
.descendant(
- of: find.byType(SettingsPage),
+ of: find.byType(page),
matching: find.byType(Scaffold),
)
.first,
)
.backgroundColor;
- group('opened from Swarm', () {
- testWidgets("Theme stands in App colors' place: System, Dark, Light — "
- 'Dark, for the shipped Graphite', (tester) async {
- final (app, _, _) = await openSettings(tester, swarm: true);
+ group("on Swarm's You", () {
+ testWidgets('Theme: System, Dark, Light — Dark, for the shipped Graphite — '
+ 'in the card with Settings', (tester) async {
+ final (app, _, _) = await openYou(tester);
await reveal(tester, find.text('Theme'));
expect(find.text('App colors'), findsNothing);
@@ -152,10 +178,10 @@ void main() {
of: find.text('Theme'),
matching: find.byType(SwarmGroup),
),
- matching: find.text('Text size'),
+ matching: find.text('Settings'),
),
findsOneWidget,
- reason: "in Appearance's card",
+ reason: "in Settings' card",
);
for (final label in ['System', 'Dark', 'Light']) {
expect(segment(label), findsOneWidget, reason: label);
@@ -176,7 +202,7 @@ void main() {
testWidgets('a screen reader changes the theme: each segment not chosen '
'takes a tap, the chosen one none (review of #2920)', (tester) async {
- final (app, store, storage) = await openSettings(tester, swarm: true);
+ final (app, store, storage) = await openYou(tester);
await reveal(tester, find.text('Theme'));
expect(
tester.getSemantics(find.bySemanticsLabel('Light')),
@@ -200,8 +226,8 @@ void main() {
testWidgets("Light turns the app light at once and is kept; the terminal's "
'colours stay Graphite', (tester) async {
- final (app, store, storage) = await openSettings(tester, swarm: true);
- expect(ground(tester), HarnessPalette.graphite.background);
+ final (app, store, storage) = await openYou(tester);
+ expect(ground(tester, SwarmYouPage), HarnessPalette.graphite.background);
await reveal(tester, find.text('Theme'));
await tester.tap(segment('Light'));
@@ -210,23 +236,23 @@ void main() {
expect(store.value.themeMode, AppThemeMode.light);
expect(storage.values['app_theme_mode'], 'light');
expect(AppTheme.palette.value, HarnessPalette.paper);
- expect(ground(tester), HarnessPalette.paper.background, reason: 'now');
+ expect(
+ ground(tester, SwarmYouPage),
+ HarnessPalette.paper.background,
+ reason: 'now',
+ );
expect(fillOf(tester, 'Light'), AppPalette.textPrimary);
expect(fillOf(tester, 'Dark'), Colors.transparent);
-
- await reveal(tester, find.text('Colors'));
expect(
- find.descendant(of: rowOf('Colors'), matching: find.text('Graphite')),
- findsOneWidget,
+ AppTheme.terminalPalette,
+ HarnessPalette.graphite,
reason: 'the terminal keeps the dark side',
);
- expect(AppTheme.terminalPalette, HarnessPalette.graphite);
- await reveal(tester, find.text('Theme'));
await tester.tap(segment('Dark'));
await frames(tester);
expect(AppTheme.palette.value, HarnessPalette.graphite);
- expect(ground(tester), HarnessPalette.graphite.background);
+ expect(ground(tester, SwarmYouPage), HarnessPalette.graphite.background);
await close(tester, app);
});
@@ -235,7 +261,7 @@ void main() {
) async {
addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue);
tester.platformDispatcher.platformBrightnessTestValue = Brightness.light;
- final (app, store, _) = await openSettings(tester, swarm: true);
+ final (app, store, _) = await openYou(tester);
expect(
AppTheme.palette.value,
HarnessPalette.graphite,
@@ -246,11 +272,11 @@ void main() {
await tester.tap(segment('System'));
await frames(tester);
expect(store.value.themeMode, AppThemeMode.system);
- expect(ground(tester), HarnessPalette.paper.background);
+ expect(ground(tester, SwarmYouPage), HarnessPalette.paper.background);
tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
await frames(tester);
- expect(ground(tester), HarnessPalette.graphite.background);
+ expect(ground(tester, SwarmYouPage), HarnessPalette.graphite.background);
expect(fillOf(tester, 'System'), AppPalette.textPrimary);
await close(tester, app);
});
@@ -258,9 +284,8 @@ void main() {
testWidgets('a palette chosen in App colors stays on its side', (
tester,
) async {
- final (app, _, _) = await openSettings(
+ final (app, _, _) = await openYou(
tester,
- swarm: true,
prefs: const AppearancePrefs(palette: HarnessPalette.midnight),
);
@@ -279,11 +304,7 @@ void main() {
testWidgets("draws a compact control with a control's words", (
tester,
) async {
- final (app, _, _) = await openSettings(
- tester,
- swarm: true,
- phone: smallPhone,
- );
+ final (app, _, _) = await openYou(tester, phone: smallPhone);
await reveal(tester, find.text('Theme'));
// The test font draws every glyph an em wide, so widths here are not a
@@ -307,9 +328,8 @@ void main() {
tester,
) async {
final errors = await collectErrors(() async {
- final (app, _, _) = await openSettings(
+ final (app, _, _) = await openYou(
tester,
- swarm: true,
phone: smallPhone,
textScale: AppearancePrefs.uiSizeMax / AppearancePrefs.uiSizeDefault,
);
@@ -323,6 +343,19 @@ void main() {
});
});
+ group('Settings opened from Swarm', () {
+ testWidgets('has no Theme and no App colors: Appearance is the text size '
+ 'alone', (tester) async {
+ final (app, _, _) = await openSettings(tester, swarm: true);
+
+ await reveal(tester, find.text('Text size'));
+ expect(find.text('Theme'), findsNothing);
+ expect(find.text('App colors'), findsNothing);
+ expect(find.byType(SwarmSegments<AppThemeMode>), findsNothing);
+ await close(tester, app);
+ });
+ });
+
group('opened from the terminal', () {
testWidgets('keeps App colors and no Theme; it names the palette on '
'screen', (tester) async {
diff --git a/mobile/test/swarm/swarm_attachment_fetch_test.dart b/mobile/test/swarm/swarm_attachment_fetch_test.dart
index 9596feec5..c8d871dab 100644
--- a/mobile/test/swarm/swarm_attachment_fetch_test.dart
+++ b/mobile/test/swarm/swarm_attachment_fetch_test.dart
@@ -42,6 +42,22 @@ class _Hosts extends http.BaseClient {
);
}
+/// Harness's file storage answering every fetch with [headers], as the
+/// backend serves a chat file (superTabs/attachments.ts `served`).
+class _Serving extends http.BaseClient {
+ _Serving(this.headers);
+
+ final Map<String, String> headers;
+
+ @override
+ Future<http.StreamedResponse> send(http.BaseRequest request) async =>
+ http.StreamedResponse(
+ Stream.value(pixelPng),
+ HttpStatus.ok,
+ headers: headers,
+ );
+}
+
void main() {
late Directory root;
final link = Uri.parse('https://cdn.harness.autonomous.ai/a1/a.png');
@@ -80,4 +96,90 @@ void main() {
expect(hosts.sent.single.followRedirects, isFalse);
});
}
+
+ group('the extension a file is kept under', () {
+ final voice = Uri.parse(
+ 'https://storage.googleapis.com/harness-cdn/super-tabs/t/abc/'
+ 'Voice_message.wav?X-Goog-Signature=sig',
+ );
+
+ Future<File> kept(Uri url, Map<String, String> headers) async {
+ final store = storeIn(root, SwarmFileFetch(client: _Serving(headers)));
+ await store.keepOnly('person-me');
+ return store.file(url);
+ }
+
+ test("a file served as bare bytes is kept under its name's, so an "
+ "iPhone's player opens a voice message", () async {
+ final file = await kept(voice, {
+ 'content-type': 'application/octet-stream',
+ 'content-disposition':
+ "attachment; filename*=UTF-8''Voice%20message.wav",
+ });
+ expect(file.path, endsWith('.wav'));
+ expect(await file.readAsBytes(), pixelPng);
+ });
+
+ test("with no name in the answer, under its link's", () async {
+ final file = await kept(voice, {
+ 'content-type': 'application/octet-stream',
+ });
+ expect(file.path, endsWith('.wav'));
+ });
+
+ test("a picture is kept under its type's, whatever its name", () async {
+ final file = await kept(
+ Uri.parse('https://storage.googleapis.com/b/t/abc/photo.jpeg'),
+ {
+ 'content-type': 'image/png',
+ 'content-disposition': "inline; filename*=UTF-8''photo.jpeg",
+ },
+ );
+ expect(file.path, endsWith('.png'));
+ });
+
+ test('bare bytes with no extension in their name stay .bin', () async {
+ final file = await kept(
+ Uri.parse('https://storage.googleapis.com/b/t/abc/HANDOFF'),
+ {
+ 'content-type': 'application/octet-stream',
+ 'content-disposition': "attachment; filename*=UTF-8''HANDOFF",
+ },
+ );
+ expect(file.path, endsWith('.bin'));
+ });
+ });
+
+ test('reads the name however the answer gives it, and takes only a plain '
+ 'extension', () {
+ final bare = Uri.parse('https://storage.googleapis.com/b/t/abc/file');
+ String named(String disposition) =>
+ swarmKeptExtension('.bin', disposition: disposition, url: bare);
+
+ expect(named("attachment; filename*=UTF-8''Voice%20message.WAV"), '.wav');
+ expect(named('attachment; filename="clip.m4a"'), '.m4a');
+ expect(named('attachment; FILENAME=notes.txt'), '.txt');
+ // Badly encoded: its plain name instead, or the link's.
+ expect(
+ named("attachment; filename*=UTF-8''%A.wav; filename=\"clip.ogg\""),
+ '.ogg',
+ );
+ expect(named("attachment; filename*=UTF-8''%E0.wav"), '.bin');
+ // Not a plain extension: neither a folder in it, nor a name that is one.
+ expect(named("attachment; filename*=UTF-8''a.w%2Fav"), '.bin');
+ expect(named("attachment; filename*=UTF-8''.wav"), '.bin');
+ expect(named("attachment; filename*=UTF-8''a.waveform-long"), '.bin');
+ expect(
+ swarmKeptExtension('', url: Uri.parse('https://h.test/a/clip.wav?x=1')),
+ '.wav',
+ );
+ expect(
+ swarmKeptExtension(
+ '.png',
+ disposition: "inline; filename*=UTF-8''a.wav",
+ url: bare,
+ ),
+ '.png',
+ );
+ });
}
diff --git a/mobile/test/swarm/swarm_buddy_chat_shots_test.dart b/mobile/test/swarm/swarm_buddy_chat_shots_test.dart
index 3429a845e..371b5178d 100644
--- a/mobile/test/swarm/swarm_buddy_chat_shots_test.dart
+++ b/mobile/test/swarm/swarm_buddy_chat_shots_test.dart
@@ -2,6 +2,7 @@ import 'dart:convert';
import 'dart:io';
import 'dart:ui' as ui;
+import 'package:clock/clock.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
@@ -17,9 +18,10 @@ import 'package:harness_mobile/swarm/swarm_session.dart';
import '../voice_fakes.dart';
import 'swarm_fixture.dart';
-/// The person's Buddy chat with its Buddy running, in both phone themes, for
-/// the pull request, written to the folder `SWARM_BUDDY_CHAT_SHOTS` names
-/// (run this file alone, on a Mac). Scripted data only.
+/// The person's Buddy chat with its Buddy running, and with it down while its
+/// computer is offline or online, in both phone themes, for the pull request,
+/// written to the folder `SWARM_BUDDY_CHAT_SHOTS` names (run this file alone,
+/// on a Mac). Scripted data only.
final shots = Platform.environment['SWARM_BUDDY_CHAT_SHOTS'];
void main() {
@@ -181,4 +183,165 @@ void main() {
AppTheme.palette.value = HarnessPalette.graphite;
AppTheme.brightness.value = Brightness.dark;
}, skip: shots == null);
+
+ // Tony, 11-04: with its computer offline, the line under the message sent
+ // says so and the bar under the header says nothing; with it online, the
+ // bar keeps Start again.
+ testWidgets('the Buddy chat with its Buddy down, its computer offline or '
+ 'online, both themes', (tester) async {
+ await tester.binding.setSurfaceSize(const Size(390, 844));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ const chat = 'buddy-me';
+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {
+ final brightness = palette.brightness;
+ AppTheme.palette.value = palette;
+ AppTheme.brightness.value = brightness;
+ for (final computer in ['offline', 'online']) {
+ final now = clock.now();
+ DateTime ago(Duration age) => now.subtract(age);
+ final page = [
+ {
+ 'id': 'm1',
+ 'conversationId': chat,
+ 'text':
+ 'Tony, the phone tests wait for the Mac to sign in again. '
+ 'Nothing else is needed tonight.',
+ 'sequence': 1,
+ 'author': {'kind': 'agent', 'id': 'agent-lead', 'name': 'River'},
+ 'attachments': <Object>[],
+ 'reactions': <Object>[],
+ 'createdAt': ago(const Duration(minutes: 40))
+ .toUtc()
+ .toIso8601String(),
+ },
+ {
+ 'id': 'm2',
+ 'conversationId': chat,
+ 'text': 'Hi',
+ 'sequence': 2,
+ 'author': {'kind': 'person', 'id': me, 'name': 'tony'},
+ 'attachments': <Object>[],
+ 'reactions': <Object>[],
+ 'deliveries': [
+ {'id': 'd1', 'agentId': 'agent-wren', 'status': 'queued'},
+ ],
+ 'createdAt': ago(const Duration(minutes: 3))
+ .toUtc()
+ .toIso8601String(),
+ },
+ ];
+ 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: [
+ buddyChatData(
+ chat,
+ agentIds: ['agent-wren'],
+ lastMessageSequence: page.length,
+ ),
+ ],
+ agents: [
+ agent('agent-lead', name: 'Lead', displayName: 'River'),
+ {
+ ...buddyData('agent-wren', displayName: 'Wren'),
+ 'downSince': ago(const Duration(hours: 4))
+ .toUtc()
+ .toIso8601String(),
+ },
+ ],
+ machines: [
+ {
+ 'machineId': 'mac-1',
+ 'name': 'Studio-Mac.local',
+ 'contributorId': me,
+ 'engines': ['claude', 'codex'],
+ 'observation': {
+ 'receivedAt':
+ (computer == 'offline'
+ ? ago(const Duration(hours: 4))
+ : now)
+ .millisecondsSinceEpoch,
+ },
+ },
+ ],
+ ),
+ 'members': [part(me, 1, person(me))],
+ };
+ 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/$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,
+ )..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();
+ // A read with the message on screen, as the line under it needs.
+ await host.session!.inbox.reader(tab)!.refresh();
+ await tester.pumpAndSettle();
+ expect(
+ find.byKey(const ValueKey('swarm-buddy-bar')),
+ computer == 'offline' ? findsNothing : findsOneWidget,
+ );
+ expect(
+ find.text("Wren's computer is offline"),
+ computer == 'offline' ? findsOneWidget : findsNothing,
+ );
+ expect(tester.takeException(), isNull);
+ 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/buddy-chat-down-computer-$computer-${brightness.name}.png',
+ ).writeAsBytes(png!.buffer.asUint8List());
+ image.dispose();
+ });
+ await tester.pumpWidget(const SizedBox());
+ host.dispose();
+ account.dispose();
+ await tester.pump(const Duration(minutes: 1));
+ }
+ }
+ AppTheme.palette.value = HarnessPalette.graphite;
+ AppTheme.brightness.value = Brightness.dark;
+ }, skip: shots == null);
}
diff --git a/mobile/test/swarm/swarm_buddy_chat_test.dart b/mobile/test/swarm/swarm_buddy_chat_test.dart
index d28e71dae..0b56a58a4 100644
--- a/mobile/test/swarm/swarm_buddy_chat_test.dart
+++ b/mobile/test/swarm/swarm_buddy_chat_test.dart
@@ -1,5 +1,6 @@
import 'dart:async';
+import 'package:clock/clock.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness_mobile/notify/system_notices.dart';
@@ -67,13 +68,21 @@ void main() {
'createdAt': DateTime.utc(2026, 10, 29, 1, minute).toIso8601String(),
};
- Map<String, dynamic> machine(String id, String name, {String owner = me}) => {
+ Map<String, dynamic> machine(
+ String id,
+ String name, {
+ String owner = me,
+ Duration ago = Duration.zero,
+ }) => {
'machineId': id,
'name': name,
'contributorId': owner,
'engines': ['claude', 'codex'],
- // Reporting now: in no account list here, so only this says it is up.
- 'observation': {'receivedAt': DateTime.now().millisecondsSinceEpoch},
+ // Reporting [ago] (now by default): in no account list here, so only this
+ // says it is up.
+ 'observation': {
+ 'receivedAt': clock.now().subtract(ago).millisecondsSinceEpoch,
+ },
};
Map<String, dynamic> wren({String? downSince}) => {
@@ -576,6 +585,126 @@ void main() {
]);
});
+ // Tony, 11-04: while its computer is offline, the line under the message
+ // sent to it says so, and nothing starts there until it is back.
+ group('down on a computer that is offline', () {
+ testWidgets('shows no bar under the header, and the chat stays', (
+ tester,
+ ) async {
+ await pump(
+ tester,
+ backend(
+ buddy: wren(downSince: offline),
+ machines: [
+ machine(
+ 'mac-1',
+ 'Tonys-MacBook-Pro',
+ ago: const Duration(hours: 4),
+ ),
+ ],
+ ),
+ );
+
+ expect(key('swarm-buddy-bar'), findsNothing);
+ expect(find.text('Wren is offline. Your chat stays.'), findsNothing);
+ expect(key('swarm-buddy-start-again'), findsNothing);
+ expect(find.byType(TextField), findsOneWidget);
+ });
+
+ testWidgets('one that never reported is offline too', (tester) async {
+ await pump(
+ tester,
+ backend(
+ buddy: wren(downSince: offline),
+ machines: [
+ {...machine('mac-1', 'Tonys-MacBook-Pro')}..remove('observation'),
+ ],
+ ),
+ );
+
+ expect(key('swarm-buddy-bar'), findsNothing);
+ });
+
+ testWidgets('the message sent says its computer is offline instead', (
+ tester,
+ ) async {
+ final host = await pump(
+ tester,
+ backend(
+ buddy: wren(downSince: offline),
+ machines: [
+ machine(
+ 'mac-1',
+ 'Tonys-MacBook-Pro',
+ ago: const Duration(hours: 4),
+ ),
+ ],
+ page: [
+ {
+ ...message('m1', 1, author: me, text: 'Hi'),
+ 'deliveries': [
+ {'id': 'd1', 'agentId': 'agent-wren', 'status': 'queued'},
+ ],
+ },
+ ],
+ ),
+ );
+ await readAgain(tester, host);
+
+ expect(find.text("Wren's computer is offline"), findsOneWidget);
+ expect(
+ find.text(
+ 'Tonys-MacBook-Pro was last seen 4 h ago. '
+ "Your message goes in when it's back online.",
+ ),
+ findsOneWidget,
+ );
+ expect(key('swarm-buddy-bar'), findsNothing);
+ });
+
+ testWidgets('its offline line goes at the next read once the computer '
+ 'stops reporting', (tester) async {
+ final host = await pump(
+ tester,
+ backend(
+ buddy: wren(downSince: offline),
+ machines: [machine('mac-1', 'Tonys-MacBook-Pro')],
+ ),
+ );
+ expect(find.text('Wren is offline. Your chat stays.'), findsOneWidget);
+
+ await tester.pump(const Duration(seconds: 36));
+ await readAgain(tester, host);
+
+ expect(key('swarm-buddy-bar'), findsNothing);
+ });
+
+ testWidgets("on someone else's machine, only who can see its terminal "
+ 'stays', (tester) async {
+ await pump(
+ tester,
+ backend(
+ buddy: {
+ ...wren(downSince: offline),
+ 'machineOwnerId': 'person-dee',
+ },
+ machines: [
+ machine(
+ 'mac-1',
+ 'Dee Studio',
+ owner: 'person-dee',
+ ago: const Duration(hours: 4),
+ ),
+ ],
+ ),
+ );
+
+ expect(key('swarm-buddy-where'), findsOneWidget);
+ expect(key('swarm-buddy-offline'), findsNothing);
+ expect(key('swarm-buddy-start-again'), findsNothing);
+ });
+ });
+
testWidgets('⋮ has Find in chat, which opens the find field (#2826)', (
tester,
) async {
diff --git a/mobile/test/swarm/swarm_display_name_shots_test.dart b/mobile/test/swarm/swarm_display_name_shots_test.dart
index 28b3e768c..a6e0233d5 100644
--- a/mobile/test/swarm/swarm_display_name_shots_test.dart
+++ b/mobile/test/swarm/swarm_display_name_shots_test.dart
@@ -19,11 +19,10 @@ import '../voice_fakes.dart';
import 'swarm_fixture.dart';
/// Review screenshots of the name a person sets (plan
-/// 2026-11-03-person-display-name, Task 6): You with its Profile row
-/// (name and status) above Username, and a chat whose author and tag read by that name beside one
-/// who set none. On a 390-point
-/// phone in both phone themes, from made-up data only, to the folder
-/// `SWARM_DISPLAY_NAME_SHOTS` names.
+/// 2026-11-03-person-display-name, Task 6): You headed by that name, and a
+/// chat whose author and tag read by it beside one who set none. On a
+/// 390-point phone in both phone themes, from made-up data only, to the
+/// folder `SWARM_DISPLAY_NAME_SHOTS` names.
final shots = Platform.environment['SWARM_DISPLAY_NAME_SHOTS'];
void main() {
setUpAll(() async {
diff --git a/mobile/test/swarm/swarm_display_name_test.dart b/mobile/test/swarm/swarm_display_name_test.dart
index ee4a73c27..974a3b492 100644
--- a/mobile/test/swarm/swarm_display_name_test.dart
+++ b/mobile/test/swarm/swarm_display_name_test.dart
@@ -406,7 +406,7 @@ void main() {
}
Future<void> openProfile(WidgetTester tester) async {
- await tester.tap(key('swarm-you-profile'));
+ await tester.tap(key('swarm-you-me'));
await tester.pumpAndSettle();
expect(key('swarm-name-field'), findsOneWidget);
}
@@ -422,18 +422,16 @@ void main() {
await settle(tester);
}
- testWidgets('with a name: You heads with it, the Profile row above '
- 'Username shows it with Change, and Username keeps the handle', (
- tester,
- ) async {
+ testWidgets('with a name: You heads with it, once, and the handle is the '
+ "profile's", (tester) async {
await pump(tester, name: 'Minh Nguyen');
expect(inside('swarm-you-me', find.text('Minh Nguyen')), findsOne);
- expect(inside('swarm-you-profile', find.text('Minh Nguyen')), findsOne);
- expect(inside('swarm-you-profile', find.text('Change')), findsOne);
- expect(inside('swarm-you-username', find.text('tony')), findsOne);
+ expect(find.text('Minh Nguyen'), findsOne, reason: 'no row repeats it');
+ expect(find.text('tony'), findsNothing);
+ await openProfile(tester);
expect(
- tester.getTopLeft(key('swarm-you-profile')).dy,
- lessThan(tester.getTopLeft(key('swarm-you-username')).dy),
+ tester.widget<TextField>(key('swarm-username-field')).controller!.text,
+ 'tony',
);
});
@@ -442,8 +440,7 @@ void main() {
) async {
await pump(tester);
expect(inside('swarm-you-me', find.text('tony')), findsOne);
- expect(inside('swarm-you-username', find.text('tony')), findsOne);
- expect(inside('swarm-you-profile', find.text('Change')), findsOne);
+ expect(find.text('tony'), findsOne, reason: 'no row repeats it');
});
testWidgets('the Name field sits above Username, and a name saves '
@@ -472,7 +469,6 @@ void main() {
await tester.tap(key('swarm-profile-close'));
await tester.pumpAndSettle();
expect(inside('swarm-you-me', find.text('Minh Nguyen')), findsOne);
- expect(inside('swarm-you-profile', find.text('Minh Nguyen')), findsOne);
});
testWidgets('an emptied field clears it with null, and the username '
diff --git a/mobile/test/swarm/swarm_message_receipt_test.dart b/mobile/test/swarm/swarm_message_receipt_test.dart
index 132ae75e1..c62894e97 100644
--- a/mobile/test/swarm/swarm_message_receipt_test.dart
+++ b/mobile/test/swarm/swarm_message_receipt_test.dart
@@ -113,6 +113,35 @@ void main() {
int reads(FakeSwarm swarm) =>
swarm.paths.where((path) => path.startsWith(exact)).length;
+ group('swarmMachineOffline', () {
+ final now = DateTime.utc(2026, 11, 4, 9);
+
+ test('a machine the Swarm does not list is no answer, so not offline', () {
+ expect(swarmMachineOffline(null, now), isFalse);
+ });
+
+ test('a listed machine that never reported is offline', () {
+ expect(swarmMachineOffline(machine('mac-1'), now), isTrue);
+ expect(
+ swarmMachineOffline({
+ 'machineId': 'mac-1',
+ 'observation': {'receivedAt': 'soon'},
+ }, now),
+ isTrue,
+ reason: 'a reading with no time is none',
+ );
+ });
+
+ test('a reading goes offline at 35 seconds, as the desktop calls it', () {
+ bool readAgo(Duration age) =>
+ swarmMachineOffline(machine('mac-1', readAt: now.subtract(age)), now);
+ expect(readAgo(Duration.zero), isFalse);
+ expect(readAgo(const Duration(seconds: 34)), isFalse);
+ expect(readAgo(const Duration(seconds: 35)), isTrue);
+ expect(readAgo(const Duration(hours: 4)), isTrue);
+ });
+ });
+
group('reading the newest own message again', () {
late DateTime now;
late Clock moved;
diff --git a/mobile/test/swarm/swarm_models_devices_test.dart b/mobile/test/swarm/swarm_models_devices_test.dart
index 2784cf31a..9f9e06580 100644
--- a/mobile/test/swarm/swarm_models_devices_test.dart
+++ b/mobile/test/swarm/swarm_models_devices_test.dart
@@ -121,7 +121,7 @@ void main() {
double y(WidgetTester tester, String k) => tester.getTopLeft(key(k)).dy;
group('from You', () {
- testWidgets('lists Your models and Your devices under the status', (
+ testWidgets('lists Your models and Your devices under who you are', (
tester,
) async {
await pump(
@@ -140,7 +140,7 @@ void main() {
findsOneWidget,
);
expect(
- y(tester, 'swarm-you-profile'),
+ y(tester, 'swarm-you-me'),
lessThan(y(tester, 'swarm-you-models')),
);
expect(
diff --git a/mobile/test/swarm/swarm_profile_ways_test.dart b/mobile/test/swarm/swarm_profile_ways_test.dart
index e69e864e9..014fafb16 100644
--- a/mobile/test/swarm/swarm_profile_ways_test.dart
+++ b/mobile/test/swarm/swarm_profile_ways_test.dart
@@ -11,8 +11,8 @@ import 'swarm_fixture.dart';
const other = 'person-tony';
-/// The ways to a profile: the "You" row at the top of the menu opens one's
-/// own, and a person's face in a chat opens theirs — one's own with Edit.
+/// The ways to a profile: who one is at the top of You opens one's own, and a
+/// person's face in a chat opens theirs — one's own with Edit.
void main() {
const messages = '/api/super-tabs/$tab/conversations/g1/messages';
@@ -93,22 +93,18 @@ void main() {
Finder inside(String value, Finder finder) =>
find.descendant(of: key(value), matching: finder);
- testWidgets('You starts with you, and its profile row opens your profile', (
- tester,
- ) async {
+ testWidgets('You starts with you, and a tap on you opens your profile, '
+ 'status and all', (tester) async {
await pump(tester, const SwarmYouPage());
expect(inside('swarm-you-me', find.text('🦊')), findsOneWidget);
expect(
- inside('swarm-you-status', find.text('🎯 Focusing')),
- findsOneWidget,
- );
- expect(
- tester.getSize(key('swarm-you-profile')).height,
+ tester.getSize(key('swarm-you-me')).height,
greaterThanOrEqualTo(44),
);
- await tester.tap(key('swarm-you-profile'));
+ await tester.tap(key('swarm-you-me'));
await frames(tester);
expect(find.text('Your profile'), findsOneWidget);
+ expect(find.text('🎯 Focusing'), findsWidgets, reason: 'set in there');
});
testWidgets("a person's face in a chat opens who they are", (tester) async {
diff --git a/mobile/test/swarm/swarm_switch_pm_shots_test.dart b/mobile/test/swarm/swarm_switch_pm_shots_test.dart
new file mode 100644
index 000000000..1e90d39bd
--- /dev/null
+++ b/mobile/test/swarm/swarm_switch_pm_shots_test.dart
@@ -0,0 +1,257 @@
+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_project_page.dart';
+import 'package:harness_mobile/swarm/swarm_project_tabs.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+import 'package:harness_mobile/swarm/swarm_switch_pm.dart' show swarmProfileId;
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+
+/// Review screenshots of Switch PM on the phone, as Desktop's dialog has it:
+/// Project settings… with its Switch PM… row, then the dialog with its
+/// Machine and Model rows, an account and a model picked, and each row's
+/// menu open — the machines with why one cannot take the PM, the Swarm's
+/// models. On a 390-point phone in both phone themes, from made-up data
+/// only, to the folder `SWARM_SWITCH_PM_SHOTS` names.
+final shots = Platform.environment['SWARM_SWITCH_PM_SHOTS'];
+
+void main() {
+ setUpAll(() async {
+ if (shots == null || !Platform.isMacOS) return;
+ final sf = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ // Every name the app's text asks for; one left out draws as blocks.
+ for (final family in {
+ '.AppleSystemUIFont',
+ 'Roboto',
+ AppFont.sans,
+ ...AppFont.sansFallback,
+ }) {
+ 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',
+ AppFont.mono,
+ ...AppFont.monoFallback,
+ }) {
+ 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('Switch PM with Machine and Model, 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 read = DateTime.now().millisecondsSinceEpoch;
+ Map<String, dynamic> machine(
+ String id,
+ String name, {
+ String contributorId = me,
+ int? readAt,
+ List<Map<String, dynamic>> profiles = const [],
+ List<String> engines = const ['claude', 'codex'],
+ }) => {
+ 'machineId': id,
+ 'name': name,
+ 'contributorId': contributorId,
+ 'engines': engines,
+ 'observation': {
+ 'receivedAt': readAt ?? read,
+ 'capabilities': ['leadStart', 'leadSwitch'],
+ 'profiles': profiles,
+ },
+ };
+ Map<String, dynamic> account(
+ String engine,
+ String id,
+ String label,
+ int left,
+ ) => {
+ 'engine': engine,
+ 'id': id,
+ 'label': label,
+ 'leftPercent': left,
+ 'resetsAt': null,
+ };
+ 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(
+ head: headData(
+ projects: [
+ {
+ 'id': project,
+ 'name': 'openharness',
+ 'ownerId': me,
+ 'leadConversationId': leadChat,
+ 'visibility': 'public',
+ 'members': <Object>[],
+ 'updateMinutes': 5,
+ },
+ ],
+ ),
+ agents: [
+ {
+ ...agent('agent-lead', name: 'Lead', displayName: 'River'),
+ 'machineOwnerId': me,
+ },
+ ],
+ machines: [
+ machine(
+ 'mac-1',
+ 'Team Mac.local',
+ profiles: [
+ // The account River runs in now.
+ account(
+ 'claude',
+ swarmProfileId('mac-1', 'claude', 'default'),
+ 'Default',
+ 40,
+ ),
+ account('claude', 'aaaaaaaaaaaaaaaa', 'Work', 0),
+ account('codex', 'bbbbbbbbbbbbbbbb', 'Side', 70),
+ ],
+ ),
+ machine(
+ 'mac-2',
+ 'Studio.local',
+ engines: ['codex'],
+ profiles: [account('codex', 'cccccccccccccccc', 'Studio', 55)],
+ ),
+ machine('mac-3', 'Ken’s MacBook Pro', contributorId: 'person-ken'),
+ machine('mac-4', 'Old Mac', readAt: read - 600000),
+ ],
+ );
+ 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,
+ };
+ fake.routes['/api/super-tabs/$tab/routing-policy'] = (_) => {
+ 'catalog': {
+ 'models': [
+ for (final (engine, model) in const [
+ ('claude', 'opus'),
+ ('codex', 'default'),
+ ('codex', 'gpt-6.1-sol'),
+ ('codex', 'gpt-6-astra'),
+ ('claude', 'sonnet'),
+ ])
+ {'engine': engine, 'model': model, 'offered': true},
+ ],
+ },
+ };
+ final host = SwarmHost(
+ accountId: () => me,
+ account: ValueNotifier<String?>(me),
+ request: fake.request,
+ notices: SilentSystemNotices(),
+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm},
+ 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 SwarmProjectPage(
+ swarmId: tab,
+ projectId: project,
+ tabs: SwarmProjectTab.homeC,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ Finder key(String value) => find.byKey(ValueKey(value));
+ Future<void> capture(String name) => tester.runAsync(() async {
+ expect(tester.takeException(), isNull);
+ final image =
+ await (boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 3);
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(shots!).create(recursive: true);
+ await File(
+ '$shots/phone-swarm-switch-pm-$name-${brightness.name}-390.png',
+ ).writeAsBytes(png!.buffer.asUint8List());
+ image.dispose();
+ });
+ await tester.tap(key('swarm-project-menu'));
+ await tester.pumpAndSettle();
+ await tester.tap(key('swarm-project-menu-settings'));
+ await tester.pumpAndSettle();
+ await capture('settings');
+ await tester.tap(find.text('Switch PM…'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Codex · Side'));
+ await tester.pumpAndSettle();
+ await tester.tap(key('swarm-switch-pm-model'));
+ await tester.pumpAndSettle();
+ await capture('model-menu');
+ await tester.tap(key('swarm-switch-pm-model-gpt-6.1-sol'));
+ await tester.pumpAndSettle();
+ await capture('dialog');
+ await tester.tap(key('swarm-switch-pm-machine'));
+ await tester.pumpAndSettle();
+ await capture('machine-menu');
+ await tester.tap(key('swarm-switch-pm-machine-mac-2'));
+ await tester.pumpAndSettle();
+ await capture('other-machine');
+ await tester.pumpWidget(const SizedBox());
+ host.dispose();
+ }
+ debugDisableShadows = true;
+ }, skip: shots == null);
+}
diff --git a/mobile/test/swarm/swarm_switch_pm_test.dart b/mobile/test/swarm/swarm_switch_pm_test.dart
new file mode 100644
index 000000000..7ebfee687
--- /dev/null
+++ b/mobile/test/swarm/swarm_switch_pm_test.dart
@@ -0,0 +1,1670 @@
+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/shared/widgets/touch_target.dart';
+import 'package:harness_mobile/swarm/model.dart';
+import 'package:harness_mobile/swarm/swarm_project_page.dart';
+import 'package:harness_mobile/swarm/swarm_project_tabs.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 'package:harness_mobile/swarm/swarm_style.dart' show SwarmButton;
+import 'package:harness_mobile/swarm/swarm_switch_pm.dart';
+import 'package:harness_mobile/swarm/team_glance.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+
+/// Switch PM on the phone (Desktop's switch_pm.dart, spec
+/// 2026-11-02-pm-switch-engine-account-design.md section 8): who is offered
+/// it in the project's ⋮ › Project settings…, as Desktop's project menu has
+/// it, and on the PM's limit note, what its dialog lists — the machines to
+/// move it to, their accounts and the Swarm's models — when its machine
+/// cannot switch it, what Switch sends, a refusal, and the PM reading
+/// Switching… after.
+void main() {
+ // sha256('mac-1:claude:default') and sha256('mac-1:codex:default'), first
+ // 16 hex: the ids the machine reports its default accounts by.
+ final claudeDefault = swarmProfileId('mac-1', 'claude', 'default');
+ final codexDefault = swarmProfileId('mac-1', 'codex', 'default');
+ const changesPath = '/api/super-tabs/$tab/changes';
+ const commandsPath = '/api/super-tabs/$tab/commands';
+ const ken = 'person-ken';
+
+ Map<String, dynamic> switching() => {
+ 'id': 'sw1',
+ 'engine': 'codex',
+ 'profileId': 'bbbbbbbbbbbbbbbb',
+ 'requestedBy': me,
+ 'at': '2026-11-03T08:00:00.000Z',
+ };
+
+ /// River, the project's PM, on mac-1, which [me] owns unless [over] says.
+ Map<String, dynamic> pmData([Map<String, dynamic> over = const {}]) => {
+ ...agent('agent-lead', name: 'Lead', displayName: 'River'),
+ 'machineOwnerId': me,
+ ...over,
+ };
+
+ /// mac-1, read just now by a Harness that switches a PM, unless told
+ /// otherwise.
+ Map<String, dynamic> machineData({
+ bool profiles = true,
+ List<String> engines = const ['claude', 'codex'],
+ DateTime? readAt,
+ List<String> capabilities = const ['leadStart', 'leadSwitch'],
+ String contributorId = me,
+ }) => {
+ 'machineId': 'mac-1',
+ 'name': 'Team Mac.local',
+ 'contributorId': contributorId,
+ 'engines': engines,
+ 'observation': {
+ 'receivedAt': (readAt ?? DateTime.now()).millisecondsSinceEpoch,
+ 'capabilities': capabilities,
+ if (profiles)
+ 'profiles': [
+ {
+ 'engine': 'codex',
+ 'id': codexDefault,
+ 'label': 'Default',
+ 'leftPercent': 90,
+ 'resetsAt': null,
+ },
+ {
+ 'engine': 'claude',
+ 'id': claudeDefault,
+ 'label': 'Default',
+ 'leftPercent': 40,
+ 'resetsAt': null,
+ },
+ {
+ 'engine': 'claude',
+ 'id': 'aaaaaaaaaaaaaaaa',
+ 'label': 'Work',
+ 'leftPercent': 0,
+ 'resetsAt': '2099-01-02T15:00:00.000Z',
+ },
+ {
+ 'engine': 'codex',
+ 'id': 'bbbbbbbbbbbbbbbb',
+ 'label': 'Side',
+ 'leftPercent': 70,
+ 'resetsAt': null,
+ },
+ ],
+ },
+ };
+
+ /// Another machine of the Swarm, read just now: Studio, the reader's own
+ /// unless told, whose Harness starts and switches a PM, offering Codex in
+ /// its default account unless it reports [profiles].
+ Map<String, dynamic> studio({
+ String id = 'mac-2',
+ String name = 'Studio.local',
+ String contributorId = me,
+ DateTime? readAt,
+ List<String> capabilities = const ['leadStart', 'leadSwitch'],
+ List<Map<String, dynamic>>? profiles,
+ Map<String, dynamic> over = const {},
+ }) => {
+ 'machineId': id,
+ 'name': name,
+ 'contributorId': contributorId,
+ 'engines': ['codex'],
+ 'observation': {
+ 'receivedAt': (readAt ?? DateTime.now()).millisecondsSinceEpoch,
+ 'capabilities': capabilities,
+ 'profiles': ?profiles,
+ },
+ ...over,
+ };
+
+ /// A machine of the reader's last read five minutes ago.
+ Map<String, dynamic> oldMac() => studio(
+ id: 'mac-3',
+ name: 'Old Mac',
+ readAt: DateTime.now().subtract(const Duration(minutes: 5)),
+ );
+
+ /// The tab's routing-policy read, its catalog as backend catalog.ts has it.
+ Map<String, dynamic> policy() => {
+ 'policy': <String, dynamic>{},
+ 'catalog': {
+ 'models': [
+ for (final (engine, model, effort, offered) in const [
+ ('claude', 'opus', 'high', true),
+ ('claude', 'opus', 'xhigh', true),
+ ('codex', 'default', 'default', true),
+ ('codex', 'gpt-6.1-sol', 'high', true),
+ ('codex', 'gpt-6-astra', 'xhigh', true),
+ ('claude', 'sonnet', 'high', true),
+ ('claude', 'haiku', 'auto', false),
+ ])
+ {
+ 'engine': engine,
+ 'model': model,
+ 'effort': effort,
+ 'strength': 3,
+ 'cost': 1,
+ 'offered': offered,
+ },
+ ],
+ },
+ };
+
+ /// [hour]:[minute] of today, in local time.
+ DateTime today(int hour, int minute) {
+ final now = DateTime.now();
+ return DateTime(now.year, now.month, now.day, hour, minute);
+ }
+
+ /// The PM's usage-limit note in its project chat (backend terminal.ts).
+ Map<String, dynamic> limitNote({String agentId = 'agent-lead'}) => {
+ 'id': 'n1',
+ 'conversationId': leadChat,
+ 'sequence': 2,
+ 'text': 'River hit a usage limit.',
+ 'author': {'kind': 'agent', 'id': agentId, 'name': 'River'},
+ 'createdAt': DateTime.utc(2026, 11, 3, 8).toIso8601String(),
+ 'source': {
+ 'kind': 'terminal-alert',
+ 'alert': 'limit',
+ 'agentId': agentId,
+ 'lead': agentId == 'agent-lead' ? true : null,
+ // Today, so the note names the time alone.
+ 'limitedUntil': today(18, 5).toIso8601String(),
+ },
+ };
+
+ /// What the next command answers instead of the server.
+ FutureOr<Object?> Function()? answer;
+
+ setUp(() => answer = null);
+
+ FakeSwarm backend({
+ String role = 'owner',
+ String projectOwner = me,
+ Map<String, dynamic>? pm,
+ Map<String, dynamic>? machine,
+ List<Map<String, dynamic>> others = const [],
+ FutureOr<Object?> Function()? policy,
+ List<Map<String, dynamic>> messages = const [],
+ }) {
+ final fake = FakeSwarm();
+ // Unrouted, the read fails: Default alone.
+ if (policy != null) {
+ fake.routes['/api/super-tabs/$tab/routing-policy'] = (_) => policy();
+ }
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {
+ ...firstLoad(
+ head: headData(
+ projects: [
+ {
+ 'id': project,
+ 'name': 'Mobile',
+ 'ownerId': projectOwner,
+ 'leadConversationId': leadChat,
+ 'visibility': 'public',
+ 'members': <Object>[],
+ 'updateMinutes': 5,
+ },
+ ],
+ ),
+ agents: [pm ?? pmData()],
+ machines: [machine ?? machineData(), ...others],
+ ),
+ 'members': [part(me, 1, person(me, role: role))],
+ };
+ fake.routes[changesPath] = (_) => changes(cursor: 'c2');
+ fake.routes['/api/super-tabs/$tab/decisions'] = (_) => {
+ 'decisions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$tab/mentions'] = (_) => {
+ 'mentions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$tab/conversations/$leadChat/messages'] =
+ (_) => {
+ 'messages': messages.reversed.toList(),
+ 'threads': <Object>[],
+ 'next': null,
+ };
+ fake.routes[commandsPath] = (_) => answer?.call() ?? {'result': {}};
+ return fake;
+ }
+
+ Future<SwarmHost> pump(
+ WidgetTester tester,
+ FakeSwarm fake, {
+ Size size = const Size(390, 844),
+ }) async {
+ await tester.binding.setSurfaceSize(size);
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final account = ValueNotifier<String?>(me);
+ final host = SwarmHost(
+ accountId: () => account.value,
+ account: account,
+ request: fake.request,
+ upload: refuseSwarmUpload,
+ notices: SilentSystemNotices(),
+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm},
+ )..foreground = false;
+ addTearDown(host.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ builder: (context, child) => SwarmScope(notifier: host, child: child!),
+ home: const SwarmProjectPage(
+ swarmId: tab,
+ projectId: project,
+ tabs: SwarmProjectTab.homeC,
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return host;
+ }
+
+ /// The Swarm read again, its PM now [pm], [machines] as they are now,
+ /// [gone] taken off it, and the reader [role].
+ Future<void> readAgain(
+ WidgetTester tester,
+ FakeSwarm fake,
+ SwarmHost host, {
+ Map<String, dynamic>? pm,
+ List<Map<String, dynamic>> machines = const [],
+ List<String> gone = const [],
+ String? role,
+ }) async {
+ fake.routes[changesPath] = (_) => {
+ ...changes(cursor: 'c3', lastChangedAt: 200),
+ 'agents': [if (pm != null) part('agent-lead', 2, pm)],
+ 'machines': [
+ for (final m in machines) part(m['machineId'] as String, 2, m),
+ for (final id in gone)
+ // After any part of it this read carries.
+ {'key': id, 'version': 3, 'changedAt': 3, 'deleted': true},
+ ],
+ 'members': [if (role != null) part(me, 2, person(me, role: role))],
+ };
+ await host.session!.inbox.reader(tab)!.refresh();
+ await tester.pumpAndSettle();
+ }
+
+ Finder key(String value) => find.byKey(ValueKey(value));
+ // Project settings…'s row (the limit note's has its own key).
+ final menuItem = find.text('Switch PM…');
+ final noteAction = key('swarm-limit-switch-pm');
+ final dialog = find.byType(SwarmSwitchPmDialog);
+ final confirm = key('swarm-switch-pm-confirm');
+
+ Future<void> openMenu(WidgetTester tester) async {
+ await tester.tap(key('swarm-project-menu'));
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> openSettings(WidgetTester tester) async {
+ await openMenu(tester);
+ await tester.tap(key('swarm-project-menu-settings'));
+ await tester.pumpAndSettle();
+ expect(find.text('Project settings'), findsOneWidget);
+ }
+
+ Future<void> openDialog(WidgetTester tester) async {
+ await openSettings(tester);
+ await tester.tap(menuItem);
+ await tester.pumpAndSettle();
+ expect(dialog, findsOneWidget);
+ }
+
+ bool confirmOn(WidgetTester tester) =>
+ tester.widget<SwarmButton>(confirm).onPressed != null;
+
+ List<Map<String, dynamic>> switches(FakeSwarm fake) => [
+ for (final command in fake.commands)
+ if (command['type'] == 'lead.switch') command,
+ ];
+
+ List<String> switchReceipts(FakeSwarm fake) => [
+ for (final call in fake.calls)
+ if (call.method == 'POST' &&
+ call.path == commandsPath &&
+ (call.body!['command'] as Map)['type'] == 'lead.switch')
+ call.body!['operationId'] as String,
+ ];
+
+ group('Project settings…', () {
+ testWidgets('offers Switch PM… to the project owner, after Project '
+ 'details; the ⋮ itself keeps its rows', (tester) async {
+ await pump(tester, backend());
+ await openMenu(tester);
+ expect(key('swarm-project-menu-settings'), findsOneWidget);
+ expect(menuItem, findsNothing, reason: 'not a row of the ⋮');
+ await tester.tap(key('swarm-project-menu-settings'));
+ await tester.pumpAndSettle();
+
+ expect(menuItem, findsOneWidget);
+ double y(Finder finder) => tester.getTopLeft(finder).dy;
+ final details = find.text('Project details');
+ expect(y(find.text('Rename project')), lessThan(y(details)));
+ expect(y(details), lessThan(y(menuItem)));
+ });
+
+ testWidgets('offers it to the owner of the PM\'s machine who does not '
+ 'own the project', (tester) async {
+ await pump(tester, backend(role: 'collaborator', projectOwner: ken));
+ await openSettings(tester);
+ expect(find.text('Rename project'), findsNothing);
+ expect(menuItem, findsOneWidget);
+ });
+
+ testWidgets('not to a member who owns neither, a lent machine\'s '
+ 'borrower included', (tester) async {
+ // The PM runs on mac-1, contributed by the reader but owned by Ken.
+ await pump(
+ tester,
+ backend(
+ role: 'collaborator',
+ projectOwner: ken,
+ pm: pmData({'machineOwnerId': ken}),
+ ),
+ );
+ await openSettings(tester);
+ expect(find.text('Project details'), findsOneWidget);
+ expect(menuItem, findsNothing);
+ });
+
+ testWidgets('not to a viewer, even the project\'s owner', (tester) async {
+ await pump(tester, backend(role: 'viewer'));
+ await openSettings(tester);
+ expect(find.text('Project details'), findsOneWidget);
+ expect(menuItem, findsNothing);
+ });
+
+ testWidgets('not while the PM is switching', (tester) async {
+ await pump(tester, backend(pm: pmData({'switchRequest': switching()})));
+ await openSettings(tester);
+ expect(find.text('Project details'), findsOneWidget);
+ expect(menuItem, findsNothing);
+ });
+
+ testWidgets('not without a PM', (tester) async {
+ final fake = backend();
+ final load = fake.routes['/api/super-tabs/$tab/parts']!;
+ fake.routes['/api/super-tabs/$tab/parts'] = (body) async {
+ final read = await load(body) as Map<String, dynamic>;
+ return {...read, 'agents': <Object>[]};
+ };
+ await pump(tester, fake);
+ await openSettings(tester);
+ expect(find.text('Project details'), findsOneWidget);
+ expect(menuItem, findsNothing);
+ });
+
+ testWidgets('leaves the open sheet once a switch is asked for on another '
+ 'device', (tester) async {
+ final fake = backend();
+ final host = await pump(tester, fake);
+ await openSettings(tester);
+ expect(menuItem, findsOneWidget);
+ await readAgain(
+ tester,
+ fake,
+ host,
+ pm: pmData({'switchRequest': switching()}),
+ );
+ expect(find.text('Project details'), findsOneWidget);
+ expect(menuItem, findsNothing);
+ });
+ });
+
+ group('the dialog', () {
+ testWidgets('lists the PM machine\'s accounts by engine with what is '
+ 'left, the current one marked, 0% and current not pickable', (
+ tester,
+ ) async {
+ await pump(tester, backend());
+ await openDialog(tester);
+ expect(find.text('Switch PM'), findsOneWidget);
+ expect(find.text('Claude Code · Default'), findsOneWidget);
+ expect(find.text('Current · 40% left'), findsOneWidget);
+ expect(find.text('Claude Code · Work'), findsOneWidget);
+ expect(find.textContaining('0% left · resets '), findsOneWidget);
+ expect(find.text('Codex · Default'), findsOneWidget);
+ expect(find.text('90% left'), findsOneWidget);
+ expect(find.text('Codex · Side'), findsOneWidget);
+ expect(find.text('70% left'), findsOneWidget);
+ expect(
+ find.text(
+ 'The new session starts fresh and reads a handoff note. Tasks and '
+ 'chat stay.',
+ ),
+ findsOneWidget,
+ );
+ // Claude's accounts first, then Codex's, each in the machine's order.
+ double y(String text) => tester.getTopLeft(find.text(text)).dy;
+ expect(y('Claude Code · Default'), lessThan(y('Claude Code · Work')));
+ expect(y('Claude Code · Work'), lessThan(y('Codex · Default')));
+ expect(y('Codex · Default'), lessThan(y('Codex · Side')));
+ // The reader owns the machine: nothing is said of what is offered.
+ expect(
+ find.text('Only accounts its owner offered are listed.'),
+ findsNothing,
+ );
+
+ expect(confirmOn(tester), isFalse);
+ for (final id in [claudeDefault, 'aaaaaaaaaaaaaaaa']) {
+ await tester.tap(key('swarm-switch-pm-claude-$id'));
+ await tester.pumpAndSettle();
+ expect(confirmOn(tester), isFalse, reason: id);
+ }
+ await tester.tap(key('swarm-switch-pm-codex-$codexDefault'));
+ await tester.pumpAndSettle();
+ expect(confirmOn(tester), isTrue);
+ });
+
+ testWidgets('Switch sends lead.switch with the engine and account, '
+ 'closes, and the PM reads Switching… once read again', (tester) async {
+ final fake = backend();
+ final host = await pump(tester, fake);
+ await openDialog(tester);
+ await tester.tap(find.text('Codex · Side'));
+ await tester.pumpAndSettle();
+ await tester.tap(confirm);
+ await tester.pumpAndSettle();
+
+ expect(switches(fake), [
+ {
+ 'type': 'lead.switch',
+ 'projectId': project,
+ 'engine': 'codex',
+ 'profileId': 'bbbbbbbbbbbbbbbb',
+ },
+ ]);
+ expect(dialog, findsNothing);
+ final sent = fake.calls.indexWhere((c) => c.path == commandsPath);
+ expect(
+ fake.calls.skip(sent + 1).where((c) => c.path.startsWith(changesPath)),
+ isNotEmpty,
+ reason: 'the Swarm is read again',
+ );
+
+ await readAgain(
+ tester,
+ fake,
+ host,
+ pm: pmData({'switchRequest': switching()}),
+ );
+ final snapshot = host.session!.inbox.reader(tab)!.snapshot!;
+ expect(
+ swarmTeamGlance(snapshot, projectId: project).agents.single.label,
+ 'Switching…',
+ );
+ await openSettings(tester);
+ expect(menuItem, findsNothing);
+ });
+
+ testWidgets('a refusal says why under the list and stays open; trying '
+ 'again is a new ask', (tester) async {
+ final fake = backend();
+ await pump(tester, fake);
+ await openDialog(tester);
+ await tester.tap(find.text('Codex · Side'));
+ await tester.pumpAndSettle();
+ answer = () => throw const SuperTabFailure(
+ 'MACHINE_OFFLINE',
+ 'Wait for a fresh reading from Team Mac.',
+ statusCode: 409,
+ );
+ await tester.tap(confirm);
+ await tester.pumpAndSettle();
+ expect(dialog, findsOneWidget);
+ expect(
+ tester.widget<Text>(key('swarm-switch-pm-error')).data,
+ 'Wait for a fresh reading from Team Mac.',
+ );
+ expect(confirmOn(tester), isTrue);
+
+ answer = null;
+ await tester.tap(confirm);
+ await tester.pumpAndSettle();
+ expect(dialog, findsNothing);
+ final receipts = switchReceipts(fake);
+ expect(receipts, hasLength(2));
+ expect(receipts.first, isNot(receipts.last));
+ });
+
+ testWidgets('an answer lost on the way says so; trying again is the same '
+ 'ask', (tester) async {
+ final fake = backend();
+ await pump(tester, fake);
+ await openDialog(tester);
+ await tester.tap(find.text('Codex · Side'));
+ await tester.pumpAndSettle();
+ answer = () => throw TimeoutException('no answer');
+ await tester.tap(confirm);
+ await tester.pumpAndSettle();
+ expect(dialog, findsOneWidget);
+ expect(
+ find.text('Could not reach this Swarm. Try again.'),
+ findsOneWidget,
+ );
+
+ answer = null;
+ await tester.tap(confirm);
+ await tester.pumpAndSettle();
+ expect(dialog, findsNothing);
+ final receipts = switchReceipts(fake);
+ expect(receipts, hasLength(2));
+ expect(receipts.first, receipts.last);
+ });
+
+ testWidgets('Switch waits on its answer: neither Cancel nor a second '
+ 'tap', (tester) async {
+ final fake = backend();
+ await pump(tester, fake);
+ await openDialog(tester);
+ await tester.tap(find.text('Codex · Side'));
+ await tester.pumpAndSettle();
+ final sent = Completer<Object?>();
+ answer = () => sent.future;
+ await tester.tap(confirm);
+ await tester.pump();
+ expect(find.text('Switching…'), findsOneWidget);
+ expect(confirmOn(tester), isFalse);
+ expect(
+ tester.widget<SwarmButton>(key('swarm-switch-pm-cancel')).onPressed,
+ isNull,
+ );
+ sent.complete({'result': {}});
+ await tester.pumpAndSettle();
+ expect(dialog, findsNothing);
+ expect(switches(fake), hasLength(1));
+ });
+
+ testWidgets('Cancel sends nothing', (tester) async {
+ final fake = backend();
+ await pump(tester, fake);
+ await openDialog(tester);
+ await tester.tap(find.text('Codex · Side'));
+ await tester.pumpAndSettle();
+ await tester.tap(key('swarm-switch-pm-cancel'));
+ await tester.pumpAndSettle();
+ expect(dialog, findsNothing);
+ expect(switches(fake), isEmpty);
+ });
+
+ testWidgets('says only offered accounts are listed on a machine the '
+ 'reader does not own', (tester) async {
+ // Desktop reads it from the machine's contributor.
+ await pump(
+ tester,
+ backend(
+ pm: pmData({'machineOwnerId': ken}),
+ machine: machineData(contributorId: ken),
+ ),
+ );
+ await openDialog(tester);
+ expect(
+ find.text('Only accounts its owner offered are listed.'),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('a machine that reports no accounts offers each engine\'s '
+ 'default; picking one sends the default', (tester) async {
+ final fake = backend(machine: machineData(profiles: false));
+ await pump(tester, fake);
+ await openDialog(tester);
+ expect(find.text('Claude Code · Default'), findsOneWidget);
+ expect(find.text('Current'), findsOneWidget);
+ expect(find.text('Codex · Default'), findsOneWidget);
+ await tester.tap(key('swarm-switch-pm-codex-default'));
+ await tester.pumpAndSettle();
+ await tester.tap(confirm);
+ await tester.pumpAndSettle();
+ expect(switches(fake).single['profileId'], 'default');
+ expect(switches(fake).single['engine'], 'codex');
+ });
+
+ testWidgets('waits for a fresh reading from the PM\'s machine: Switch '
+ 'stays off until its machine reports again', (tester) async {
+ final fake = backend(
+ machine: machineData(
+ readAt: DateTime.now().subtract(const Duration(minutes: 1)),
+ ),
+ );
+ final host = await pump(tester, fake);
+ await openDialog(tester);
+ final note = key('swarm-switch-pm-no-choice');
+ expect(
+ tester.widget<Text>(note).data,
+ 'Wait for a fresh reading from the PM’s machine.',
+ );
+ // Its accounts can still be picked, as on Desktop; Switch waits.
+ await tester.tap(find.text('Codex · Side'));
+ await tester.pumpAndSettle();
+ expect(confirmOn(tester), isFalse);
+
+ await readAgain(tester, fake, host, machines: [machineData()]);
+ expect(dialog, findsOneWidget);
+ expect(note, findsNothing);
+ expect(confirmOn(tester), isTrue);
+ expect(switches(fake), isEmpty);
+ });
+
+ testWidgets('says to update Harness on a machine too old to switch it, '
+ 'by its name without .local', (tester) async {
+ await pump(
+ tester,
+ backend(machine: machineData(capabilities: const ['leadStart'])),
+ );
+ await openDialog(tester);
+ expect(
+ tester.widget<Text>(key('swarm-switch-pm-no-choice')).data,
+ 'Update Harness on Team Mac to switch this Product Manager.',
+ );
+ await tester.tap(find.text('Codex · Side'));
+ await tester.pumpAndSettle();
+ expect(confirmOn(tester), isFalse);
+ });
+
+ testWidgets('says so when no account can be picked', (tester) async {
+ // A machine that offers only the engine the PM runs, in its default
+ // account.
+ await pump(
+ tester,
+ backend(
+ machine: machineData(profiles: false, engines: const ['claude']),
+ ),
+ );
+ await openDialog(tester);
+ expect(find.text('Claude Code · Default'), findsOneWidget);
+ expect(find.text('Codex · Default'), findsNothing);
+ // No other machine to move it to either.
+ expect(
+ tester.widget<Text>(key('swarm-switch-pm-no-choice')).data,
+ 'No other machine or account can run a Product Manager right now.',
+ );
+ expect(confirmOn(tester), isFalse);
+ });
+
+ testWidgets('with nothing left to pick here, another machine to move it '
+ 'to is a choice', (tester) async {
+ await pump(
+ tester,
+ backend(
+ machine: machineData(profiles: false, engines: const ['claude']),
+ others: [studio()],
+ ),
+ );
+ await openDialog(tester);
+ expect(key('swarm-switch-pm-no-choice'), findsNothing);
+ });
+
+ testWidgets('with nothing left here nor on the machines it could move '
+ 'to, says no engine or account can run it', (tester) async {
+ await pump(
+ tester,
+ backend(
+ machine: machineData(profiles: false, engines: const ['claude']),
+ others: [
+ // Every account of it ran out.
+ studio(
+ profiles: [
+ {
+ 'engine': 'codex',
+ 'id': 'cccccccccccccccc',
+ 'label': 'Studio',
+ 'leftPercent': 0,
+ 'resetsAt': null,
+ },
+ ],
+ ),
+ oldMac(),
+ ],
+ ),
+ );
+ await openDialog(tester);
+ expect(
+ tester.widget<Text>(key('swarm-switch-pm-no-choice')).data,
+ 'No engine or account can run a Product Manager right now.',
+ );
+ expect(confirmOn(tester), isFalse);
+ });
+
+ testWidgets('says nothing of the kind while it can switch', (tester) async {
+ await pump(tester, backend());
+ await openDialog(tester);
+ expect(key('swarm-switch-pm-no-choice'), findsNothing);
+ });
+
+ testWidgets('goes once a switch is asked for on another device', (
+ tester,
+ ) async {
+ final fake = backend();
+ final host = await pump(tester, fake);
+ await openDialog(tester);
+ await readAgain(
+ tester,
+ fake,
+ host,
+ pm: pmData({'switchRequest': switching()}),
+ );
+ expect(dialog, findsNothing);
+ expect(switches(fake), isEmpty);
+ });
+
+ testWidgets('goes once the reader is only a viewer', (tester) async {
+ final fake = backend();
+ final host = await pump(tester, fake);
+ await openDialog(tester);
+ await readAgain(tester, fake, host, role: 'viewer');
+ expect(dialog, findsNothing);
+ });
+ });
+
+ /// The Machine or Model row's menu, open.
+ Future<void> openPicker(WidgetTester tester, String row) async {
+ await tester.tap(key('swarm-switch-pm-$row'));
+ await tester.pumpAndSettle();
+ }
+
+ /// Picks [option] of the Machine or Model row.
+ Future<void> choose(WidgetTester tester, String row, String option) async {
+ await openPicker(tester, row);
+ await tester.tap(key('swarm-switch-pm-$row-$option'));
+ await tester.pumpAndSettle();
+ }
+
+ /// What the Machine or Model row shows chosen, its menu shut.
+ String shown(WidgetTester tester, String row) {
+ final texts = tester
+ .widgetList<Text>(
+ find.descendant(
+ of: key('swarm-switch-pm-$row'),
+ matching: find.byType(Text),
+ ),
+ )
+ .map((t) => t.data)
+ .toList();
+ // Its label, then what is chosen.
+ return texts[1]!;
+ }
+
+ bool optionOn(WidgetTester tester, String row, String option) =>
+ tester
+ .widget<MenuItemButton>(key('swarm-switch-pm-$row-$option'))
+ .onPressed !=
+ null;
+
+ /// The words of a menu option: its name, and why it cannot be chosen.
+ List<String?> optionWords(WidgetTester tester, String row, String option) =>
+ tester
+ .widgetList<Text>(
+ find.descendant(
+ of: key('swarm-switch-pm-$row-$option'),
+ matching: find.byType(Text),
+ ),
+ )
+ .map((t) => t.data)
+ .toList();
+
+ group('the Machine row', () {
+ testWidgets('lists the Swarm\'s machines, the PM\'s own marked Current, '
+ 'never a Team account read on its Mac', (tester) async {
+ await pump(
+ tester,
+ backend(
+ others: [
+ studio(),
+ studio(
+ id: 'mac-2-team',
+ name: 'Studio (Team)',
+ over: {'hostMachineId': 'mac-2'},
+ ),
+ ],
+ ),
+ );
+ await openDialog(tester);
+ expect(shown(tester, 'machine'), 'Team Mac · Current');
+ await openPicker(tester, 'machine');
+ expect(optionWords(tester, 'machine', 'mac-1'), ['Team Mac · Current']);
+ expect(optionWords(tester, 'machine', 'mac-2'), ['Studio']);
+ expect(optionOn(tester, 'machine', 'mac-2'), isTrue);
+ expect(key('swarm-switch-pm-machine-mac-2-team'), findsNothing);
+ double y(String id) =>
+ tester.getTopLeft(key('swarm-switch-pm-machine-$id')).dy;
+ expect(y('mac-1'), lessThan(y('mac-2')));
+ });
+
+ testWidgets('a machine that cannot take it is dimmed, saying why in '
+ 'Desktop\'s words', (tester) async {
+ await pump(
+ tester,
+ backend(
+ others: [
+ oldMac(),
+ studio(
+ id: 'mac-4',
+ name: 'Lab',
+ capabilities: const ['leadSwitch'],
+ ),
+ studio(id: 'mac-5', name: 'Ken Mac', contributorId: ken),
+ studio(
+ id: 'mac-6',
+ name: 'Ken Mini',
+ contributorId: ken,
+ over: {
+ 'teamWork': {
+ 'allowed': false,
+ 'reason': 'Ken Mini takes no other projects now.',
+ },
+ },
+ ),
+ studio(
+ id: 'mac-7',
+ name: 'Shared',
+ contributorId: ken,
+ over: {
+ 'teamWork': {'allowed': true},
+ },
+ ),
+ studio(id: 'mac-8', name: 'Paused Mac', over: {'paused': true}),
+ studio(
+ id: 'mac-9',
+ name: 'Leaving',
+ over: {
+ 'removal': {'at': 1},
+ },
+ ),
+ ],
+ ),
+ );
+ await openDialog(tester);
+ await openPicker(tester, 'machine');
+ final why = {
+ 'mac-3': ['Old Mac', 'Old Mac is offline.'],
+ 'mac-4': [
+ 'Lab',
+ 'Update Harness on Lab to move a Product Manager there.',
+ ],
+ 'mac-5': ['Ken Mac', 'This machine cannot take this project’s work.'],
+ 'mac-6': ['Ken Mini', 'Ken Mini takes no other projects now.'],
+ 'mac-8': ['Paused Mac', 'Paused Mac is unavailable in this Swarm.'],
+ 'mac-9': ['Leaving', 'Leaving is unavailable in this Swarm.'],
+ };
+ for (final MapEntry(key: id, value: words) in why.entries) {
+ expect(optionWords(tester, 'machine', id), words, reason: id);
+ expect(optionOn(tester, 'machine', id), isFalse, reason: id);
+ }
+ // Someone else's machine that takes this project's work.
+ expect(optionWords(tester, 'machine', 'mac-7'), ['Shared']);
+ expect(optionOn(tester, 'machine', 'mac-7'), isTrue);
+ });
+
+ testWidgets('the PM machine\'s owner who does not own the project sees '
+ 'the others dimmed: only the project\'s owner moves it', (
+ tester,
+ ) async {
+ final fake = backend(
+ role: 'collaborator',
+ projectOwner: ken,
+ others: [studio()],
+ );
+ await pump(tester, fake);
+ await openDialog(tester);
+ await openPicker(tester, 'machine');
+ expect(optionWords(tester, 'machine', 'mac-2'), [
+ 'Studio',
+ 'Only the project’s owner moves its PM to another machine.',
+ ]);
+ expect(optionOn(tester, 'machine', 'mac-2'), isFalse);
+ await tester.tap(key('swarm-switch-pm-machine-mac-1'));
+ await tester.pumpAndSettle();
+
+ // Where it runs, they still switch it.
+ await tester.tap(find.text('Codex · Side'));
+ await tester.pumpAndSettle();
+ await tester.tap(confirm);
+ await tester.pumpAndSettle();
+ expect(switches(fake).single.containsKey('machineId'), isFalse);
+ });
+
+ testWidgets('another machine lists its own accounts and forgets the one '
+ 'picked; back on the PM\'s, Current is there again', (tester) async {
+ await pump(
+ tester,
+ backend(
+ others: [
+ studio(
+ profiles: [
+ {
+ 'engine': 'codex',
+ 'id': 'cccccccccccccccc',
+ 'label': 'Studio',
+ 'leftPercent': 50,
+ 'resetsAt': null,
+ },
+ ],
+ ),
+ ],
+ ),
+ );
+ await openDialog(tester);
+ await tester.tap(find.text('Codex · Side'));
+ await tester.pumpAndSettle();
+ expect(confirmOn(tester), isTrue);
+
+ await choose(tester, 'machine', 'mac-2');
+ expect(shown(tester, 'machine'), 'Studio');
+ expect(find.text('Codex · Studio'), findsOneWidget);
+ expect(find.text('50% left'), findsOneWidget);
+ expect(find.text('Codex · Side'), findsNothing);
+ expect(find.textContaining('Current'), findsNothing);
+ expect(confirmOn(tester), isFalse, reason: 'nothing picked there');
+ await tester.tap(find.text('Codex · Studio'));
+ await tester.pumpAndSettle();
+ expect(confirmOn(tester), isTrue);
+
+ await choose(tester, 'machine', 'mac-1');
+ expect(find.text('Current · 40% left'), findsOneWidget);
+ expect(confirmOn(tester), isFalse);
+ });
+
+ testWidgets('a machine someone else brought lists only what its owner '
+ 'offered', (tester) async {
+ await pump(
+ tester,
+ backend(
+ others: [
+ studio(
+ contributorId: ken,
+ over: {
+ 'teamWork': {'allowed': true},
+ },
+ ),
+ ],
+ ),
+ );
+ await openDialog(tester);
+ const offered = 'Only accounts its owner offered are listed.';
+ expect(find.text(offered), findsNothing);
+ await choose(tester, 'machine', 'mac-2');
+ expect(find.text(offered), findsOneWidget);
+ });
+
+ testWidgets('a machine with no account to offer says so', (tester) async {
+ await pump(
+ tester,
+ backend(
+ others: [
+ studio(over: {'engines': <String>[]}),
+ ],
+ ),
+ );
+ await openDialog(tester);
+ await choose(tester, 'machine', 'mac-2');
+ expect(
+ find.text('No engine or account is available on this machine.'),
+ findsOneWidget,
+ );
+ expect(confirmOn(tester), isFalse);
+ });
+
+ testWidgets('the machine chosen pausing dims its accounts and holds '
+ 'Switch; leaving the Swarm, it goes back to the PM\'s', (tester) async {
+ final fake = backend(others: [studio()]);
+ final host = await pump(tester, fake);
+ await openDialog(tester);
+ await choose(tester, 'machine', 'mac-2');
+ await tester.tap(find.text('Codex · Default'));
+ await tester.pumpAndSettle();
+ expect(confirmOn(tester), isTrue);
+
+ await readAgain(
+ tester,
+ fake,
+ host,
+ machines: [
+ studio(over: {'paused': true}),
+ ],
+ );
+ expect(dialog, findsOneWidget);
+ expect(shown(tester, 'machine'), 'Studio');
+ expect(confirmOn(tester), isFalse);
+ expect(
+ tester.widget<InkWell>(key('swarm-switch-pm-codex-default')).onTap,
+ isNull,
+ );
+
+ await readAgain(tester, fake, host, gone: ['mac-2']);
+ expect(dialog, findsOneWidget);
+ expect(shown(tester, 'machine'), 'Team Mac · Current');
+ expect(find.text('Codex · Side'), findsOneWidget);
+ expect(confirmOn(tester), isFalse);
+ expect(switches(fake), isEmpty);
+ });
+ });
+
+ group('the Model row', () {
+ testWidgets('offers Default, then each catalog model of the PM\'s engine '
+ 'once, never one the catalog does not offer', (tester) async {
+ await pump(tester, backend(policy: policy));
+ await openDialog(tester);
+ expect(shown(tester, 'model'), 'Default');
+ await openPicker(tester, 'model');
+ for (final option in ['default', 'opus', 'sonnet']) {
+ expect(key('swarm-switch-pm-model-$option'), findsOneWidget);
+ }
+ expect(optionWords(tester, 'model', 'default'), ['Default']);
+ expect(key('swarm-switch-pm-model-haiku'), findsNothing);
+ expect(key('swarm-switch-pm-model-gpt-6.1-sol'), findsNothing);
+ double y(String option) =>
+ tester.getTopLeft(key('swarm-switch-pm-model-$option')).dy;
+ expect(y('default'), lessThan(y('opus')));
+ expect(y('opus'), lessThan(y('sonnet')));
+ });
+
+ testWidgets('an account of another engine lists that engine\'s models, '
+ 'Codex\'s own default not twice, and forgets the model picked', (
+ tester,
+ ) async {
+ await pump(tester, backend(policy: policy));
+ await openDialog(tester);
+ await choose(tester, 'model', 'sonnet');
+ expect(shown(tester, 'model'), 'sonnet');
+
+ await tester.tap(find.text('Codex · Side'));
+ await tester.pumpAndSettle();
+ expect(shown(tester, 'model'), 'Default');
+ await openPicker(tester, 'model');
+ expect(key('swarm-switch-pm-model-gpt-6.1-sol'), findsOneWidget);
+ expect(key('swarm-switch-pm-model-gpt-6-astra'), findsOneWidget);
+ expect(key('swarm-switch-pm-model-sonnet'), findsNothing);
+ expect(find.text('default'), findsNothing);
+ });
+
+ testWidgets('another machine forgets the model picked', (tester) async {
+ await pump(tester, backend(policy: policy, others: [studio()]));
+ await openDialog(tester);
+ await tester.tap(find.text('Codex · Side'));
+ await tester.pumpAndSettle();
+ await choose(tester, 'model', 'gpt-6.1-sol');
+ expect(shown(tester, 'model'), 'gpt-6.1-sol');
+ await choose(tester, 'machine', 'mac-2');
+ expect(shown(tester, 'model'), 'Default');
+ });
+
+ testWidgets('a catalog that cannot be read leaves Default alone', (
+ tester,
+ ) async {
+ final fake = backend();
+ await pump(tester, fake);
+ await openDialog(tester);
+ expect(
+ fake.paths,
+ contains('/api/super-tabs/$tab/routing-policy'),
+ reason: 'asked, and refused',
+ );
+ await openPicker(tester, 'model');
+ expect(
+ find.descendant(
+ of: find.byType(MenuItemButton),
+ matching: find.byType(Text),
+ ),
+ findsOneWidget,
+ );
+ expect(key('swarm-switch-pm-model-default'), findsOneWidget);
+ });
+ });
+
+ group('what Switch sends', () {
+ testWidgets('another machine: its id, and its default account by the '
+ 'literal default', (tester) async {
+ final fake = backend(others: [studio()]);
+ await pump(tester, fake);
+ await openDialog(tester);
+ await choose(tester, 'machine', 'mac-2');
+ await tester.tap(find.text('Codex · Default'));
+ await tester.pumpAndSettle();
+ await tester.tap(confirm);
+ await tester.pumpAndSettle();
+ expect(switches(fake), [
+ {
+ 'type': 'lead.switch',
+ 'projectId': project,
+ 'engine': 'codex',
+ 'profileId': 'default',
+ 'machineId': 'mac-2',
+ },
+ ]);
+ expect(dialog, findsNothing);
+ });
+
+ testWidgets('a model picked: its name, and no effort', (tester) async {
+ final fake = backend(policy: policy);
+ await pump(tester, fake);
+ await openDialog(tester);
+ await tester.tap(find.text('Codex · Side'));
+ await tester.pumpAndSettle();
+ await choose(tester, 'model', 'gpt-6.1-sol');
+ await tester.tap(confirm);
+ await tester.pumpAndSettle();
+ expect(switches(fake), [
+ {
+ 'type': 'lead.switch',
+ 'projectId': project,
+ 'engine': 'codex',
+ 'profileId': 'bbbbbbbbbbbbbbbb',
+ 'model': 'gpt-6.1-sol',
+ },
+ ]);
+ });
+
+ testWidgets('a move the server refuses says why and keeps what was '
+ 'picked', (tester) async {
+ final fake = backend(others: [studio()]);
+ await pump(tester, fake);
+ await openDialog(tester);
+ await choose(tester, 'machine', 'mac-2');
+ await tester.tap(find.text('Codex · Default'));
+ await tester.pumpAndSettle();
+ answer = () => throw const SuperTabFailure(
+ 'HOST_OUTDATED',
+ 'Update Harness on Studio to move the Product Manager.',
+ statusCode: 409,
+ );
+ await tester.tap(confirm);
+ await tester.pumpAndSettle();
+ expect(dialog, findsOneWidget);
+ expect(
+ tester.widget<Text>(key('swarm-switch-pm-error')).data,
+ 'Update Harness on Studio to move the Product Manager.',
+ );
+ expect(shown(tester, 'machine'), 'Studio');
+ expect(confirmOn(tester), isTrue);
+ });
+
+ testWidgets('after an answer lost on the way, another pick is a new '
+ 'ask', (tester) async {
+ final fake = backend(policy: policy);
+ await pump(tester, fake);
+ await openDialog(tester);
+ await tester.tap(find.text('Codex · Side'));
+ await tester.pumpAndSettle();
+ answer = () => throw TimeoutException('no answer');
+ await tester.tap(confirm);
+ await tester.pumpAndSettle();
+ expect(dialog, findsOneWidget);
+
+ answer = null;
+ await choose(tester, 'model', 'gpt-6-astra');
+ await tester.tap(confirm);
+ await tester.pumpAndSettle();
+ expect(dialog, findsNothing);
+ final receipts = switchReceipts(fake);
+ expect(receipts, hasLength(2));
+ expect(receipts.first, isNot(receipts.last));
+ expect(switches(fake).last['model'], 'gpt-6-astra');
+ });
+ });
+
+ group('on a 320-point phone', () {
+ testWidgets('the dialog, Machine and Model included, fits with nothing '
+ 'cut, and the Machine menu stays on the screen', (tester) async {
+ const size = Size(320, 568);
+ await pump(
+ tester,
+ backend(
+ policy: policy,
+ role: 'owner',
+ others: [
+ studio(id: 'mac-5', name: 'Ken MacBook Pro', contributorId: ken),
+ oldMac(),
+ ],
+ ),
+ size: size,
+ );
+ await openDialog(tester);
+ expect(tester.takeException(), isNull);
+ final screen = Offset.zero & size;
+ for (final row in [
+ 'swarm-switch-pm-machine',
+ 'swarm-switch-pm-model',
+ 'swarm-switch-pm-cancel',
+ 'swarm-switch-pm-confirm',
+ ]) {
+ final rect = tester.getRect(key(row));
+ expect(screen.contains(rect.topLeft), isTrue, reason: row);
+ expect(
+ screen.contains(rect.bottomRight - const Offset(1, 1)),
+ isTrue,
+ reason: row,
+ );
+ }
+ expect(
+ tester.getSize(key('swarm-switch-pm-machine')).height,
+ greaterThanOrEqualTo(minTouchTarget),
+ );
+
+ await openPicker(tester, 'machine');
+ expect(tester.takeException(), isNull);
+ for (final id in ['mac-1', 'mac-5', 'mac-3']) {
+ final option = key('swarm-switch-pm-machine-$id');
+ final rect = tester.getRect(option);
+ expect(rect.left, greaterThanOrEqualTo(0), reason: id);
+ expect(rect.right, lessThanOrEqualTo(size.width), reason: id);
+ expect(rect.height, greaterThanOrEqualTo(minTouchTarget), reason: id);
+ // Each word whole, the why wrapped inside the menu.
+ for (final text
+ in find
+ .descendant(of: option, matching: find.byType(Text))
+ .evaluate()) {
+ final box = text.renderObject! as RenderBox;
+ final at = box.localToGlobal(Offset.zero) & box.size;
+ expect(at.right, lessThanOrEqualTo(rect.right), reason: id);
+ }
+ }
+ });
+ });
+
+ group('the PM\'s limit note', () {
+ testWidgets('offers Switch PM… while its machine still alerts about the '
+ 'limit, and opens the dialog', (tester) async {
+ await pump(
+ tester,
+ backend(
+ pm: pmData({
+ 'alerting': ['limit'],
+ }),
+ messages: [limitNote()],
+ ),
+ );
+ expect(find.textContaining('River hit a usage limit.'), findsOneWidget);
+ expect(find.textContaining('until 18:05'), findsOneWidget);
+ expect(noteAction, findsOneWidget);
+ await tester.tap(noteAction);
+ await tester.pumpAndSettle();
+ expect(dialog, findsOneWidget);
+ expect(find.text('Codex · Side'), findsOneWidget);
+ });
+
+ testWidgets('leaves once the limit alert ends or a switch is under way', (
+ tester,
+ ) async {
+ final fake = backend(
+ pm: pmData({
+ 'alerting': ['limit'],
+ }),
+ messages: [limitNote()],
+ );
+ final host = await pump(tester, fake);
+ expect(noteAction, findsOneWidget);
+
+ await readAgain(
+ tester,
+ fake,
+ host,
+ pm: pmData({
+ 'alerting': ['limit'],
+ 'switchRequest': switching(),
+ }),
+ );
+ expect(noteAction, findsNothing);
+ expect(find.textContaining('River hit a usage limit.'), findsOneWidget);
+
+ fake.routes[changesPath] = (_) => {
+ ...changes(cursor: 'c4', lastChangedAt: 300),
+ 'agents': [part('agent-lead', 3, pmData())],
+ };
+ await host.session!.inbox.reader(tab)!.refresh();
+ await tester.pumpAndSettle();
+ expect(noteAction, findsNothing);
+ });
+
+ testWidgets('not once its machine no longer alerts', (tester) async {
+ await pump(tester, backend(messages: [limitNote()]));
+ expect(find.textContaining('until 18:05'), findsOneWidget);
+ expect(noteAction, findsNothing);
+ });
+
+ testWidgets('not to a viewer', (tester) async {
+ await pump(
+ tester,
+ backend(
+ role: 'viewer',
+ pm: pmData({
+ 'alerting': ['limit'],
+ }),
+ messages: [limitNote()],
+ ),
+ );
+ expect(noteAction, findsNothing);
+ });
+
+ testWidgets('a worker\'s limit note never offers it', (tester) async {
+ await pump(
+ tester,
+ backend(
+ pm: pmData({
+ 'alerting': ['limit'],
+ }),
+ messages: [limitNote(agentId: 'agent-builder')],
+ ),
+ );
+ expect(noteAction, findsNothing);
+ });
+ });
+
+ group('the model', () {
+ test('a profile id is Desktop\'s and the CLI\'s', () {
+ // The vectors desktop/test/usage_account_key_test.dart and
+ // super_tab_switch_pm_test.dart pin.
+ expect(swarmProfileId('m', 'claude', 'default'), '71dc90339553114c');
+ expect(swarmProfileId('m', 'codex', 'default'), '07f54db4cdffbb30');
+ expect(
+ swarmProfileId('m', 'codex', '/home/me/.codex-b'),
+ '77103ab28be2ebd0',
+ );
+ });
+
+ SuperTabSnapshot snapshot(
+ Map<String, dynamic> pm, {
+ List<Map<String, dynamic>> machines = const [],
+ String projectOwner = me,
+ }) => SuperTabSnapshot.fromJson({
+ 'id': tab,
+ 'name': 'Phone Swarm',
+ 'ownerId': me,
+ 'projects': [
+ {
+ 'id': project,
+ 'name': 'Mobile',
+ 'ownerId': projectOwner,
+ 'leadConversationId': leadChat,
+ 'visibility': 'public',
+ 'members': <Object>[],
+ 'updateMinutes': 5,
+ },
+ ],
+ 'people': [person(me)],
+ 'invitations': <Object>[],
+ 'version': 1,
+ 'conversations': [
+ groupData(leadChat, agentIds: ['agent-lead'], leadId: 'agent-lead'),
+ ],
+ 'agents': [pm],
+ 'machines': machines,
+ });
+
+ List<String> current(SuperTabSnapshot s) => [
+ for (final c in swarmSwitchPmChoices(s, project))
+ if (c.current) '${c.profile.engine}-${c.profile.id}',
+ ];
+
+ test('the PM\'s own account is current; none, or the literal default, is '
+ 'its engine\'s default', () {
+ expect(current(snapshot(pmData(), machines: [machineData()])), [
+ 'claude-$claudeDefault',
+ ]);
+ expect(
+ current(
+ snapshot(pmData({'profileId': 'default'}), machines: [machineData()]),
+ ),
+ ['claude-$claudeDefault'],
+ );
+ expect(
+ current(
+ snapshot(
+ pmData({'profileId': 'aaaaaaaaaaaaaaaa'}),
+ machines: [machineData()],
+ ),
+ ),
+ ['claude-aaaaaaaaaaaaaaaa'],
+ );
+ expect(
+ current(
+ snapshot(
+ {
+ ...pmData({'profileId': 'bbbbbbbbbbbbbbbb'}),
+ 'configuration': {'engine': 'codex'},
+ },
+ machines: [machineData()],
+ ),
+ ),
+ ['codex-bbbbbbbbbbbbbbbb'],
+ );
+ });
+
+ test('the PM\'s machine refuses a switch without a reading of the last '
+ '35 seconds, or without leadSwitch', () {
+ final now = DateTime(2026, 11, 4, 12);
+ SwarmReader reader(Map<String, dynamic>? machine) {
+ final reader = SwarmReader(
+ tabId: tab,
+ accountId: me,
+ request: FakeSwarm().request,
+ )..snapshot = snapshot(pmData(), machines: [?machine]);
+ addTearDown(reader.dispose);
+ return reader;
+ }
+
+ String? refusal(Map<String, dynamic>? machine) =>
+ swarmSwitchPmRefusal(reader(machine), project, now: now);
+
+ const stale = 'Wait for a fresh reading from the PM’s machine.';
+ expect(refusal(null), stale);
+ expect(
+ refusal(machineData(readAt: now.subtract(const Duration(seconds: 35)))),
+ stale,
+ );
+ expect(
+ refusal(machineData(readAt: now.subtract(const Duration(seconds: 34)))),
+ isNull,
+ );
+ expect(
+ refusal({
+ ...machineData(readAt: now, capabilities: const []),
+ 'name': null,
+ }),
+ 'Update Harness on the PM’s machine to switch this Product Manager.',
+ );
+ expect(
+ refusal({
+ ...machineData(readAt: now),
+ 'observation': {'receivedAt': now.millisecondsSinceEpoch},
+ }),
+ 'Update Harness on Team Mac to switch this Product Manager.',
+ );
+ // Without a PM there is nothing to refuse.
+ expect(
+ swarmSwitchPmRefusal(
+ reader(machineData(readAt: now))..snapshot = null,
+ project,
+ now: now,
+ ),
+ isNull,
+ );
+ });
+
+ test('the catalog keeps each row with an engine and a model not marked '
+ 'unoffered; an answer without one has none', () {
+ expect(swarmSwitchPmCatalog(policy()), [
+ (engine: 'claude', model: 'opus'),
+ (engine: 'claude', model: 'opus'),
+ (engine: 'codex', model: 'default'),
+ (engine: 'codex', model: 'gpt-6.1-sol'),
+ (engine: 'codex', model: 'gpt-6-astra'),
+ (engine: 'claude', model: 'sonnet'),
+ ]);
+ expect(
+ swarmSwitchPmCatalog({
+ 'catalog': {
+ 'models': [
+ {'engine': 'claude'},
+ {'engine': 'claude', 'model': 7},
+ 'opus',
+ {'engine': 'claude', 'model': 'opus'},
+ ],
+ },
+ }),
+ [(engine: 'claude', model: 'opus')],
+ );
+ expect(swarmSwitchPmCatalog({'policy': <String, dynamic>{}}), isEmpty);
+ expect(swarmSwitchPmCatalog(null), isEmpty);
+ expect(
+ swarmSwitchPmCatalog({
+ 'catalog': {'models': 'opus'},
+ }),
+ isEmpty,
+ );
+ });
+
+ test('the models of an engine, each once, in the catalog\'s order, its '
+ 'own default left to Default', () {
+ final catalog = swarmSwitchPmCatalog(policy());
+ expect(swarmSwitchPmModels(catalog, 'claude'), ['opus', 'sonnet']);
+ expect(swarmSwitchPmModels(catalog, 'codex'), [
+ 'gpt-6.1-sol',
+ 'gpt-6-astra',
+ ]);
+ expect(swarmSwitchPmModels(catalog, 'gemini'), isEmpty);
+ expect(swarmSwitchPmModels(const [], 'claude'), isEmpty);
+ });
+
+ test('lead.switch names the machine only for a move, and the model '
+ 'only for one picked', () {
+ const picked = (engine: 'codex', id: 'bbbbbbbbbbbbbbbb');
+ expect(
+ swarmSwitchPmCommand(
+ projectId: project,
+ picked: picked,
+ currentMachineId: 'mac-1',
+ machineId: 'mac-1',
+ ),
+ {
+ 'type': 'lead.switch',
+ 'projectId': project,
+ 'engine': 'codex',
+ 'profileId': 'bbbbbbbbbbbbbbbb',
+ },
+ );
+ expect(
+ swarmSwitchPmCommand(
+ projectId: project,
+ picked: (engine: 'codex', id: 'default'),
+ currentMachineId: 'mac-1',
+ machineId: 'mac-2',
+ model: 'gpt-6-astra',
+ ),
+ {
+ 'type': 'lead.switch',
+ 'projectId': project,
+ 'engine': 'codex',
+ 'profileId': 'default',
+ 'machineId': 'mac-2',
+ 'model': 'gpt-6-astra',
+ },
+ );
+ });
+
+ test('another machine is offline from 35 seconds without a reading; '
+ 'the PM\'s own is never refused here', () {
+ final now = DateTime(2026, 11, 4, 12);
+ final reader = SwarmReader(
+ tabId: tab,
+ accountId: me,
+ request: FakeSwarm().request,
+ );
+ addTearDown(reader.dispose);
+ // Each machine read as the Swarm has it, beside the PM's.
+ String? refusal(Map<String, dynamic> pool) {
+ reader.snapshot = snapshot(
+ pmData(),
+ machines: [machineData(), if (pool['machineId'] != 'mac-1') pool],
+ );
+ return swarmSwitchPmMachineRefusal(reader, project, pool, now: now);
+ }
+
+ expect(
+ refusal(studio(readAt: now.subtract(const Duration(seconds: 34)))),
+ isNull,
+ );
+ expect(
+ refusal(studio(readAt: now.subtract(const Duration(seconds: 35)))),
+ 'Studio is offline.',
+ );
+ expect(
+ refusal({...studio(readAt: now), 'name': null, 'observation': null}),
+ 'Mac is offline.',
+ );
+ expect(
+ refusal(machineData(readAt: now.subtract(const Duration(minutes: 9)))),
+ isNull,
+ );
+ });
+
+ test('a PM whose machine is not in the Swarm is offered its own '
+ 'engine\'s default alone, which it runs in', () {
+ final choices = swarmSwitchPmChoices(snapshot(pmData()), project);
+ expect(choices, hasLength(1));
+ expect(choices.single.profile.id, 'default');
+ expect(choices.single.current, isTrue);
+ expect(swarmSwitchPmPickable(choices.single), isFalse);
+ });
+
+ test(
+ 'only the project\'s owner and the PM machine\'s owner may switch',
+ () {
+ expect(swarmMaySwitchLead(snapshot(pmData()), project, me), isTrue);
+ expect(
+ swarmMaySwitchLead(
+ snapshot(pmData(), projectOwner: ken),
+ project,
+ me,
+ ),
+ isTrue,
+ );
+ expect(
+ swarmMaySwitchLead(
+ snapshot(pmData({'machineOwnerId': ken}), projectOwner: ken),
+ project,
+ me,
+ ),
+ isFalse,
+ );
+ expect(swarmMaySwitchLead(snapshot(pmData()), project, null), isFalse);
+ expect(swarmMaySwitchLead(snapshot(pmData()), 'nope', me), isFalse);
+ },
+ );
+
+ test('a PM with a switch asked for reads Switching…', () {
+ final glance = swarmTeamGlance(
+ snapshot(
+ pmData({
+ 'switchRequest': switching(),
+ 'limitedUntil': DateTime.now()
+ .add(const Duration(hours: 1))
+ .toUtc()
+ .toIso8601String(),
+ }),
+ ),
+ projectId: project,
+ );
+ expect(glance.agents.single.label, 'Switching…');
+ expect(glance.agents.single.state, SwarmAgentState.working);
+ });
+ });
+}
diff --git a/mobile/test/swarm/swarm_username_shots_test.dart b/mobile/test/swarm/swarm_username_shots_test.dart
index 9080ae464..4da7e2ecb 100644
--- a/mobile/test/swarm/swarm_username_shots_test.dart
+++ b/mobile/test/swarm/swarm_username_shots_test.dart
@@ -19,8 +19,8 @@ import '../voice_fakes.dart';
import 'swarm_fixture.dart';
/// Review screenshots of the username on the phone (Tony 11-01, task 10):
-/// You with its Username row, then the profile with a taken name refused
-/// under its field. On a 390-point phone in both phone themes, from made-up
+/// You headed by it, then the profile with a taken name refused under its
+/// field. On a 390-point phone in both phone themes, from made-up
/// data only, to the folder `SWARM_USERNAME_SHOTS` names.
final shots = Platform.environment['SWARM_USERNAME_SHOTS'];
void main() {
@@ -145,9 +145,9 @@ void main() {
});
}
- expect(find.byKey(const ValueKey('swarm-you-username')), findsOneWidget);
+ expect(find.byKey(const ValueKey('swarm-you-me')), findsOneWidget);
await capture('you');
- await tester.tap(find.byKey(const ValueKey('swarm-you-username')));
+ await tester.tap(find.byKey(const ValueKey('swarm-you-me')));
await tester.pumpAndSettle();
await tester.enterText(
find.byKey(const ValueKey('swarm-username-field')),
diff --git a/mobile/test/swarm/swarm_username_test.dart b/mobile/test/swarm/swarm_username_test.dart
index eb346b4a5..f074b1ff2 100644
--- a/mobile/test/swarm/swarm_username_test.dart
+++ b/mobile/test/swarm/swarm_username_test.dart
@@ -9,6 +9,7 @@ import 'package:harness_mobile/swarm/swarm_request.dart';
import 'package:harness_mobile/swarm/swarm_session.dart';
import 'package:harness_mobile/swarm/swarm_style.dart';
import 'package:harness_mobile/swarm/swarm_you_page.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../voice_fakes.dart';
import 'swarm_fixture.dart';
@@ -138,6 +139,9 @@ void main() {
Finder key(String value) => find.byKey(ValueKey(value));
Finder inside(String k, Finder matching) =>
find.descendant(of: key(k), matching: matching);
+
+ /// The chevron that says You's header opens the profile.
+ final chevron = find.byIcon(LucideIcons.chevronRight300);
TextField field(WidgetTester tester) =>
tester.widget<TextField>(key('swarm-username-field'));
bool saveOn(WidgetTester tester) =>
@@ -154,7 +158,7 @@ void main() {
}
Future<void> openProfile(WidgetTester tester) async {
- await tester.tap(key('swarm-you-username'));
+ await tester.tap(key('swarm-you-me'));
await tester.pumpAndSettle();
expect(key('swarm-username-field'), findsOneWidget);
}
@@ -175,11 +179,11 @@ void main() {
if (c['type'] == 'member.username') c,
];
- testWidgets('You shows the username, and Change opens the profile with '
- 'it in its field', (tester) async {
+ testWidgets('You heads with the username, and a tap there opens the '
+ 'profile with it in its field', (tester) async {
await pump(tester);
- expect(inside('swarm-you-username', find.text('tony')), findsOneWidget);
- expect(inside('swarm-you-username', find.text('Change')), findsOneWidget);
+ expect(inside('swarm-you-me', find.text('tony')), findsOneWidget);
+ expect(inside('swarm-you-me', chevron), findsOneWidget);
await openProfile(tester);
expect(field(tester).controller!.text, 'tony');
expect(find.text('How people see and tag you in this Swarm.'), findsOne);
@@ -207,7 +211,7 @@ void main() {
);
await tester.tap(key('swarm-profile-close'));
await tester.pumpAndSettle();
- expect(inside('swarm-you-username', find.text('tony.b')), findsOneWidget);
+ expect(inside('swarm-you-me', find.text('tony.b')), findsOneWidget);
});
testWidgets('a name the server refuses says why under its field, and '
@@ -296,8 +300,8 @@ void main() {
await tester.tap(key('swarm-profile-close'));
await tester.pumpAndSettle();
// You keeps nothing of them, and offers no way in.
- expect(inside('swarm-you-username', find.text('tony')), findsNothing);
- expect(inside('swarm-you-username', find.text('Change')), findsNothing);
+ expect(find.text('tony'), findsNothing);
+ expect(inside('swarm-you-me', chevron), findsNothing);
});
testWidgets('an answer that lands after access was taken away changes '
@@ -350,15 +354,15 @@ void main() {
testWidgets('a first read that failed and then recovers still lets them '
'change it', (tester) async {
await pump(tester, firstLoadFails: true);
- expect(inside('swarm-you-username', find.text('Change')), findsNothing);
- await tester.tap(key('swarm-you-username'));
+ expect(inside('swarm-you-me', chevron), findsNothing);
+ await tester.tap(key('swarm-you-me'));
await tester.pumpAndSettle();
expect(key('swarm-username-field'), findsNothing);
partsFail = null;
await host.session!.inbox.reader(tab)!.refresh();
await tester.pumpAndSettle();
- expect(inside('swarm-you-username', find.text('tony')), findsOneWidget);
+ expect(inside('swarm-you-me', find.text('tony')), findsOneWidget);
await openProfile(tester);
await type(tester, 'tony.b');
await save(tester);
diff --git a/mobile/test/swarm/swarm_voice_bubble_test.dart b/mobile/test/swarm/swarm_voice_bubble_test.dart
index b0d8fbea3..0cfe2ca99 100644
--- a/mobile/test/swarm/swarm_voice_bubble_test.dart
+++ b/mobile/test/swarm/swarm_voice_bubble_test.dart
@@ -4,10 +4,14 @@ import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;
import 'package:harness_mobile/swarm/model.dart';
+import 'package:harness_mobile/swarm/swarm_attachment_store.dart';
import 'package:harness_mobile/swarm/swarm_file_links.dart';
import 'package:harness_mobile/swarm/swarm_voice_bubble.dart';
+import 'package:http/http.dart' as http;
import 'package:video_player/video_player.dart';
+import 'swarm_attachment_fakes.dart';
+
/// A voice message as both apps draw it (task #2584):
///
/// ( ▶ ) ıllıllııılllıı.ılıı.ıll 1:21 →A
@@ -15,6 +19,7 @@ import 'package:video_player/video_player.dart';
/// Play hears it, from a copy of the file on the phone; →A shows its words
/// under it, and a second tap hides them.
void main() {
+ final cachedCopy = swarmVoiceFile;
final clip = SuperTabAttachment.fromJson({
'id': 'clip',
'name': 'Voice message.wav',
@@ -188,6 +193,122 @@ void main() {
expect(player.calls, isEmpty);
expect(key('swarm-voice-play'), findsOneWidget);
});
+
+ // As the app plays it: its copy kept by the store, fetched over its signed
+ // link from storage that serves it as bare bytes, as the backend does.
+ group('from the copy the store keeps', () {
+ late Directory root;
+ late _Storage storage;
+ final signed = SuperTabAttachment.fromJson({
+ 'id': 'clip',
+ 'name': 'Voice message.wav',
+ 'mime': 'audio/wav',
+ 'size': 2592044,
+ 'url': 'https://cdn.example.test/super-tabs/tab/abc/Voice_message.wav',
+ 'link':
+ 'https://storage.googleapis.com/harness-cdn/super-tabs/tab/abc/'
+ 'Voice_message.wav?X-Goog-Signature=sig',
+ 'expiresAt': DateTime(2100).millisecondsSinceEpoch,
+ 'voice': {
+ 'durationMs': 81000,
+ 'waveform': List.generate(48, (i) => i % 32),
+ 'transcribed': true,
+ },
+ });
+
+ setUp(() {
+ root = Directory.systemTemp.createTempSync('swarm-voice-');
+ storage = _Storage();
+ final store = swarmAttachments;
+ swarmAttachments = storeIn(root, SwarmFileFetch(client: storage));
+ swarmVoiceFile = cachedCopy;
+ addTearDown(() {
+ swarmAttachments = store;
+ if (root.existsSync()) root.deleteSync(recursive: true);
+ });
+ });
+
+ /// Real time for the file to be fetched and written, a frame after each
+ /// step, until the player has it.
+ Future<File> played(WidgetTester tester) async {
+ for (var i = 0; i < 100 && player.source == null; i++) {
+ await tester.runAsync(
+ () => Future<void>.delayed(const Duration(milliseconds: 10)),
+ );
+ await tester.pump();
+ }
+ expect(player.calls, ['initialize', 'play']);
+ return player.source!;
+ }
+
+ /// The bubble gone, and the cache's own cleanup, which it runs every few
+ /// seconds, let run.
+ Future<void> closed(WidgetTester tester) async {
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(minutes: 1));
+ }
+
+ testWidgets("plays it kept as .wav, which an iPhone's player opens", (
+ tester,
+ ) async {
+ await tester.runAsync(() => swarmAttachments.keepOnly('person-me'));
+ await pump(tester, file: signed);
+ await tester.tap(key('swarm-voice-play'));
+ final source = await played(tester);
+ expect(source.path, endsWith('.wav'));
+ expect(await tester.runAsync(source.readAsBytes), _Storage.wav);
+ expect(storage.asked.single.path, endsWith('/Voice_message.wav'));
+ expect(find.textContaining("Couldn't"), findsNothing);
+ await closed(tester);
+ });
+
+ testWidgets('a copy kept as .bin before is fetched again, never played', (
+ tester,
+ ) async {
+ final old = (await tester.runAsync(() async {
+ await swarmAttachments.keepOnly('person-me');
+ storage.named = false;
+ final kept = await swarmAttachments.file(
+ Uri.parse('https://storage.googleapis.com/harness-cdn/old'),
+ key: 'voice:clip',
+ );
+ storage.named = true;
+ return kept;
+ }))!;
+ expect(old.path, endsWith('.bin'));
+ await pump(tester, file: signed);
+ await tester.tap(key('swarm-voice-play'));
+ final source = await played(tester);
+ expect(source.path, isNot(old.path));
+ expect(source.path, endsWith('.wav'));
+ await closed(tester);
+ });
+ });
+}
+
+/// Harness's file storage, serving a voice message's clip as the backend
+/// serves any file but a picture: bare bytes, named in its
+/// `Content-Disposition` while [named].
+class _Storage extends http.BaseClient {
+ static final wav = [...'RIFF'.codeUnits, 0, 0, 0, 0, ...'WAVE'.codeUnits];
+
+ final asked = <Uri>[];
+ bool named = true;
+
+ @override
+ Future<http.StreamedResponse> send(http.BaseRequest request) async {
+ asked.add(request.url);
+ return http.StreamedResponse(
+ Stream.value(wav),
+ HttpStatus.ok,
+ headers: {
+ 'content-type': 'application/octet-stream',
+ if (named)
+ 'content-disposition':
+ "attachment; filename*=UTF-8''Voice%20message.wav",
+ },
+ );
+ }
}
class _Player extends VideoPlayerController {
diff --git a/mobile/test/swarm/swarm_you_test.dart b/mobile/test/swarm/swarm_you_test.dart
index 947f316c4..1f9f2a553 100644
--- a/mobile/test/swarm/swarm_you_test.dart
+++ b/mobile/test/swarm/swarm_you_test.dart
@@ -1,6 +1,5 @@
import 'dart:async';
-import 'package:clock/clock.dart';
import 'package:flutter/cupertino.dart' show CupertinoPageRoute;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
@@ -8,22 +7,36 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:harness_mobile/notify/system_notices.dart';
import 'package:harness_mobile/phone/out_of_sight.dart';
import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/shared/theme/appearance_prefs_store.dart';
import 'package:harness_mobile/swarm/swarm_request.dart';
import 'package:harness_mobile/swarm/swarm_devices_page.dart';
import 'package:harness_mobile/swarm/swarm_models_page.dart';
import 'package:harness_mobile/swarm/swarm_profile_sheet.dart';
+import 'package:harness_mobile/swarm/swarm_row.dart';
import 'package:harness_mobile/swarm/swarm_session.dart';
import 'package:harness_mobile/swarm/swarm_start.dart';
import 'package:harness_mobile/swarm/swarm_style.dart';
import 'package:harness_mobile/swarm/swarm_you_page.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../voice_fakes.dart';
import 'swarm_computers_fake.dart';
import 'swarm_fixture.dart';
+/// The phone's notice centre, counting each time it is asked to notify.
+class _AskedNotices extends SilentSystemNotices {
+ var asked = 0;
+
+ @override
+ Future<bool?> requestPermission() async {
+ asked++;
+ return null;
+ }
+}
+
/// You, as Tony's prototype C4 draws it (2026-10-30): who the person is in
-/// the Swarm Home shows, their status and the way to change it, Your models
-/// and Your devices with what is ready, and Settings.
+/// the Swarm Home shows, which opens their profile; Your models and Your
+/// devices with what is ready; and Notifications, Theme and Settings.
void main() {
/// The Swarms [swarms], each with the person as [email protected], [status]
/// and [name] set when given, its models on, and [models] served by the person's
@@ -100,13 +113,16 @@ void main() {
late SwarmHost host;
late List<String> settingsOpened;
+ late AppearancePrefsStore appearance;
- /// You under a Swarm that is on, on an iPhone's screen.
+ /// You under a Swarm that is on, on an iPhone's screen; its Notifications
+ /// on [notices] when given, its Theme on a store of its own.
Future<void> pump(
WidgetTester tester,
FakeSwarm fake, {
SwarmComputers? computers,
ValueListenable<bool>? hidden,
+ SystemNotices? notices,
}) async {
tester.view.physicalSize = const Size(1170, 2532);
tester.view.devicePixelRatio = 3;
@@ -124,6 +140,7 @@ void main() {
)..foreground = false;
addTearDown(host.dispose);
settingsOpened = [];
+ appearance = AppearancePrefsStore(storage: MemoryKeyValueStore());
await tester.pumpWidget(
MaterialApp(
builder: (context, child) => SwarmScope(notifier: host, child: child!),
@@ -131,6 +148,8 @@ void main() {
builder: (_) {
final page = SwarmYouPage(
onSettings: (_) => settingsOpened.add('settings'),
+ notices: notices,
+ appearance: appearance,
);
if (hidden == null) return page;
return ValueListenableBuilder(
@@ -166,8 +185,8 @@ void main() {
{'model': 'llama-4', 'name': 'Llama 4', 'kind': 'shared'},
];
- testWidgets('who you are: your face, your name and your Swarm, Active '
- 'with no status set, and Change opens your profile', (tester) async {
+ testWidgets('who you are: your face, your name and your Swarm, and a tap '
+ 'there opens your profile', (tester) async {
await pump(tester, backend());
expect(
@@ -177,17 +196,24 @@ void main() {
expect(inside('swarm-you-me', find.text('tony')), findsOneWidget);
expect(inside('swarm-you-me', find.text('Autonomous')), findsOneWidget);
expect(inside('swarm-you-me', find.byType(SwarmAvatar)), findsOneWidget);
- expect(inside('swarm-you-status', find.text('Active')), findsOneWidget);
- expect(inside('swarm-you-profile', find.text('Change')), findsOneWidget);
+ expect(
+ inside('swarm-you-me', find.byIcon(LucideIcons.chevronRight300)),
+ findsOneWidget,
+ reason: 'it says it opens',
+ );
+ expect(
+ tester.getSemantics(key('swarm-you-me')),
+ isSemantics(isButton: true, hasTapAction: true),
+ );
- await tester.tap(key('swarm-you-profile'));
+ await tester.tap(key('swarm-you-me'));
await tester.pumpAndSettle();
expect(find.byType(SwarmProfileSheet), findsOneWidget);
});
- testWidgets('Status and Name are one Profile row: the name, the status '
- 'under it, one Change, then Username', (tester) async {
+ testWidgets('nothing under the header opens the profile again: no Profile, '
+ 'no Username, no status line, no Change', (tester) async {
await pump(
tester,
backend(
@@ -196,50 +222,94 @@ void main() {
),
);
- final captions = [
- for (final caption in tester.widgetList<SwarmCaption>(
- find.byType(SwarmCaption),
- ))
- caption.text,
- ];
- expect(captions, ['Profile', 'Username']);
- expect(key('swarm-you-name'), findsNothing);
- expect(inside('swarm-you-profile', find.text('Minh Nguyen')), findsOne);
- expect(inside('swarm-you-profile', find.text('🎯 Focusing')), findsOne);
- expect(inside('swarm-you-profile', find.text('Change')), findsOne);
+ expect(inside('swarm-you-me', find.text('Minh Nguyen')), findsOne);
+ expect(find.byType(SwarmCaption), findsNothing);
+ for (final gone in ['profile', 'username', 'status', 'name']) {
+ expect(key('swarm-you-$gone'), findsNothing, reason: gone);
+ }
+ expect(find.byIcon(LucideIcons.atSign300), findsNothing);
+ expect(find.text('Change'), findsNothing);
+ expect(find.text('🎯 Focusing'), findsNothing);
+ });
+
+ testWidgets('under the header: Your models and Your devices, then '
+ 'Notifications, Theme and Settings in one card', (tester) async {
+ await pump(tester, backend(), notices: _AskedNotices());
+
+ double top(String row) => tester.getTopLeft(key('swarm-you-$row')).dy;
+ final order = ['me', 'models', 'devices', 'notifications', 'theme'];
+ for (final (i, row) in order.indexed) {
+ expect(
+ top(row),
+ lessThan(top(i + 1 < order.length ? order[i + 1] : 'settings')),
+ reason: row,
+ );
+ }
+ SwarmGroup cardOf(String row) => tester.widget<SwarmGroup>(
+ find.ancestor(of: key('swarm-you-$row'), matching: find.byType(SwarmGroup)),
+ );
+ expect(cardOf('notifications'), same(cardOf('settings')));
+ expect(cardOf('theme'), same(cardOf('settings')));
+ expect(cardOf('models'), same(cardOf('devices')));
+ expect(cardOf('models'), isNot(same(cardOf('settings'))));
+ // Drawn as You's own rows, each led by its glyph.
+ for (final (row, glyph) in [
+ ('notifications', LucideIcons.bell300),
+ ('theme', LucideIcons.sunMoon300),
+ ]) {
+ expect(inside('swarm-you-$row', find.byType(SwarmRow)), findsOne);
+ expect(inside('swarm-you-$row', find.byIcon(glyph)), findsOne);
+ }
+ });
+
+ testWidgets('Notifications asks the phone, with no line under it', (
+ tester,
+ ) async {
+ final notices = _AskedNotices();
+ await pump(tester, backend(), notices: notices);
+
expect(
- tester
- .getTopLeft(inside('swarm-you-profile', find.text('Minh Nguyen')))
- .dy,
- lessThan(tester.getTopLeft(key('swarm-you-status')).dy),
- reason: 'the status sits under the name',
+ inside('swarm-you-notifications', find.text('Notifications')),
+ findsOne,
);
expect(
- tester.getTopLeft(key('swarm-you-profile')).dy,
- lessThan(tester.getTopLeft(key('swarm-you-username')).dy),
+ inside('swarm-you-notifications', find.textContaining('needs you')),
+ findsNothing,
);
+ await tester.tap(key('swarm-you-notifications'));
+ await tester.pumpAndSettle();
+ expect(notices.asked, 1);
});
- testWidgets('with no name set the row asks for one, over Active', (
+ testWidgets('with no notice centre to ask, as in the sample, Notifications '
+ 'is no row', (tester) async {
+ await pump(tester, backend());
+
+ expect(key('swarm-you-notifications'), findsNothing);
+ expect(find.text('Notifications'), findsNothing);
+ expect(key('swarm-you-theme'), findsOne);
+ });
+
+ testWidgets('Theme: System, Dark and Light, and a tap keeps the choice', (
tester,
) async {
await pump(tester, backend());
- expect(inside('swarm-you-profile', find.text('Add your name')), findsOne);
- expect(inside('swarm-you-status', find.text('Active')), findsOne);
+ for (final label in ['System', 'Dark', 'Light']) {
+ expect(inside('swarm-you-theme', find.text(label)), findsOne);
+ }
+ await tester.tap(inside('swarm-you-theme', find.text('Light')));
+ await tester.pumpAndSettle();
+ expect(appearance.value.themeMode, AppThemeMode.light);
});
- testWidgets('a long name and status stay on one line each on a small '
- 'phone at large text', (tester) async {
+ testWidgets('a long name and Swarm stay on one line each, the chevron and '
+ 'Theme on screen, on a small phone at large text', (tester) async {
+ const name = 'Maximilian Alexander Featherstonehaugh-Wolfeschlegel';
+ const swarm = 'The Autonomous Research and Design Laboratory';
await pump(
tester,
- backend(
- name: 'Maximilian Alexander Featherstonehaugh-Wolfeschlegel',
- status: {
- 'text': 'Out for the whole afternoon at the dentist, back at five',
- 'emoji': '🦷',
- },
- ),
+ backend(name: name, swarms: const [(id: tab, name: swarm)]),
);
tester.view.physicalSize = const Size(960, 1704);
tester.platformDispatcher.textScaleFactorTestValue = 1.6;
@@ -247,55 +317,45 @@ void main() {
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
- final row = tester.getRect(key('swarm-you-profile'));
- expect(row.right, lessThanOrEqualTo(320));
+ final header = tester.getRect(key('swarm-you-me'));
+ expect(header.right, lessThanOrEqualTo(320));
expect(
- tester.getRect(inside('swarm-you-profile', find.text('Change'))).right,
- lessThanOrEqualTo(row.right),
+ tester
+ .getRect(
+ inside('swarm-you-me', find.byIcon(LucideIcons.chevronRight300)),
+ )
+ .right,
+ lessThanOrEqualTo(header.right),
);
- for (final line in tester.widgetList<Text>(
- inside('swarm-you-profile', find.byType(Text)),
- )) {
- expect(line.maxLines, anyOf(isNull, 1), reason: '${line.data}');
+ for (final line in [name, swarm]) {
+ expect(
+ tester.widget<Text>(inside('swarm-you-me', find.text(line))).maxLines,
+ 1,
+ reason: line,
+ );
}
+ expect(tester.getRect(key('swarm-you-theme')).right, lessThanOrEqualTo(320));
});
- testWidgets('a status set shows in place of Active', (tester) async {
+ testWidgets('a status set is the profile\'s, not a line on You', (
+ tester,
+ ) async {
await pump(
tester,
backend(status: {'text': 'In a meeting', 'emoji': '📅'}),
);
+ expect(find.text('📅 In a meeting'), findsNothing);
+ expect(find.text('Active'), findsNothing);
+ await tester.tap(key('swarm-you-me'));
+ await tester.pumpAndSettle();
expect(
- inside('swarm-you-status', find.text('📅 In a meeting')),
- findsOneWidget,
- );
- expect(inside('swarm-you-status', find.text('Active')), findsNothing);
- });
-
- testWidgets('a status that ends goes back to Active when it ends', (
- tester,
- ) async {
- final until = clock.now().add(const Duration(minutes: 30));
- await pump(
- tester,
- backend(
- status: {
- 'text': 'In a meeting',
- 'emoji': '📅',
- 'until': until.toUtc().toIso8601String(),
- },
+ find.descendant(
+ of: find.byType(SwarmProfileSheet),
+ matching: find.text('📅 In a meeting'),
),
- );
- expect(
- inside('swarm-you-status', find.text('📅 In a meeting')),
findsOneWidget,
);
-
- await tester.pump(const Duration(minutes: 31));
-
- expect(inside('swarm-you-status', find.text('Active')), findsOneWidget);
- expect(find.text('📅 In a meeting'), findsNothing);
});
testWidgets('Your models counts what every Swarm can use now, and opens '
@@ -495,6 +555,11 @@ void main() {
expect(find.text('tony'), findsNothing);
expect(inside('swarm-you-me', find.text('You')), findsOneWidget);
expect(find.textContaining('ready now'), findsNothing);
+ expect(
+ inside('swarm-you-me', find.byIcon(LucideIcons.chevronRight300)),
+ findsNothing,
+ reason: 'no way in',
+ );
});
testWidgets('a read that fails shows You with no rows on their way', (
@@ -508,15 +573,15 @@ void main() {
expect(inside('swarm-you-me', find.text('You')), findsOneWidget);
expect(find.byType(SwarmSkeletonRows), findsNothing);
expect(find.textContaining('ready now'), findsNothing);
- for (final row in ['profile', 'username', 'models', 'devices']) {
+ for (final row in ['models', 'devices', 'theme', 'settings']) {
expect(key('swarm-you-$row'), findsOneWidget, reason: row);
}
- expect(key('swarm-you-settings'), findsOneWidget);
- expect(inside('swarm-you-profile', find.text('Name')), findsOne);
- expect(inside('swarm-you-status', find.text('Set a status')), findsOne);
- expect(inside('swarm-you-profile', find.text('Change')), findsNothing);
+ expect(
+ inside('swarm-you-me', find.byIcon(LucideIcons.chevronRight300)),
+ findsNothing,
+ );
- await tester.tap(key('swarm-you-profile'));
+ await tester.tap(key('swarm-you-me'));
await tester.pumpAndSettle();
expect(find.byType(SwarmProfileSheet), findsNothing);
});
@@ -526,9 +591,17 @@ void main() {
tester,
backend(models: threeModels),
computers: FakeComputers(const [studio])..own = [own(studio)],
+ notices: _AskedNotices(),
);
- for (final row in ['profile', 'username', 'models', 'devices', 'settings']) {
+ for (final row in [
+ 'me',
+ 'models',
+ 'devices',
+ 'notifications',
+ 'theme',
+ 'settings',
+ ]) {
final size = tester.getSize(key('swarm-you-$row'));
expect(size.height, greaterThanOrEqualTo(44), reason: row);
expect(size.width, greaterThanOrEqualTo(44), reason: row);