Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Phone: + New project on Swarm Home starts its Product Manager on a Swarm machine (#2324)

harness-for-autonomous[bot]c3755cfa1f0c
diff --git a/mobile/lib/swarm/swarm_new_project_sheet.dart b/mobile/lib/swarm/swarm_new_project_sheet.dart
new file mode 100644
index 000000000..c225c2684
--- /dev/null
+++ b/mobile/lib/swarm/swarm_new_project_sheet.dart
@@ -0,0 +1,2130 @@
+import 'dart:async';
+import 'dart:math' as math;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:lucide_icons_flutter/lucide_icons.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/theme/app_theme.dart' show AppColors;
+
+import 'model.dart';
+import 'swarm_buddy.dart' show swarmCanWrite;
+import 'swarm_home_list.dart' show swarmProjectActivity;
+import 'swarm_home_top.dart' show swarmHomeOffers;
+import 'swarm_inbox.dart';
+import 'swarm_reader.dart';
+import 'swarm_request.dart';
+import 'swarm_row.dart';
+import 'swarm_session.dart';
+import 'swarm_style.dart';
+
+/// New project from the phone (Tony, 10-30): Swarm Home's last Projects row
+/// ([SwarmNewProjectRow]) opens a sheet ([showSwarmNewProjectSheet]) that
+/// creates a project in a Swarm the person may write in and starts its
+/// Product Manager on the Swarm machine they pick, as Desktop's New Project
+/// does through the Swarm (desktop `super_tabs/launch.dart` `startInSwarm`,
+/// #2208, #2215, #2228). A phone never runs the Product Manager itself, so
+/// it has no "this computer".
+
+/// Whether the person may create a project in Swarm [swarmId] from Home: Home
+/// offers it, it is read, and they may write in it (an owner or a
+/// collaborator, never a viewer, as the server's `project.create` asks).
+bool swarmMayCreateProject(SwarmInbox inbox, String swarmId) {
+ final reader = inbox.reader(swarmId);
+ return reader != null &&
+ !reader.accessRevoked &&
+ reader.snapshot != null &&
+ swarmHomeOffers(inbox, swarmId) &&
+ swarmCanWrite(reader);
+}
+
+/// The engines a Product Manager runs on, in the order one is chosen
+/// (Desktop's `kLeadEngines`).
+const swarmLeadEngines = ['claude', 'codex'];
+
+/// A Product Manager engine's name as people read it.
+String swarmLeadEngineLabel(String engine) =>
+ const {'claude': 'Claude Code', 'codex': 'Codex'}[engine] ?? engine;
+
+/// Why a paused Swarm's machines take no work (Desktop's `kLeadSwarmPaused`).
+const swarmLeadSwarmPaused = 'New work is paused in this Swarm';
+
+/// New project's reason while no machine is chosen: none is chosen for the
+/// person, since only they know which one stays on (Ken, 10-29).
+const swarmLeadChooseMachine =
+ 'Choose the machine the Product Manager runs on.';
+
+/// What PM runs on says when no machine can take the Product Manager now.
+const swarmLeadNoMachine = 'No machine can run the Product Manager now.';
+
+/// Why one of the person's machines added for the Lead only cannot take a
+/// project's Product Manager: the server's reason, said to its owner.
+const swarmLeadUnscoped =
+ 'Add this machine to the Swarm again to support other projects.';
+
+/// What the sheet says once Start over lets go of a create never answered:
+/// the Swarm may have made the project all the same.
+const swarmNewProjectMaybeMade =
+ 'A project may already have been made. '
+ 'Check Projects before you create it again.';
+
+/// A machine's reading counts while it is this fresh (backend
+/// `MACHINE_FRESH_MS`, as the start itself reads it).
+const _freshFor = Duration(seconds: 45);
+
+/// The longest brief kept: a project's brief, and its chat's first message
+/// (Desktop's 4000; the server takes 8000 characters, a rune is at most two).
+const swarmNewProjectBriefRunes = 4000;
+
+/// A machine of the Swarm a new project's Product Manager could start on, as
+/// PM runs on lists it: Desktop's `LeadMachine`, without what only a desktop
+/// that starts it itself needs.
+class SwarmLeadMachine {
+ const SwarmLeadMachine({
+ required this.id,
+ required this.name,
+ required this.online,
+ required this.freeAgents,
+ this.own = true,
+ this.maySleep = false,
+ this.team = false,
+ this.teamEngines,
+ this.unavailable,
+ this.engineRefusals = const {},
+ });
+
+ final String id, name;
+ final bool online;
+
+ /// The agent slots it offers the Swarm that nothing runs in.
+ final int freeAgents;
+
+ /// One of the person's own machines.
+ final bool own;
+
+ /// A laptop: it may sleep with the Product Manager on it.
+ final bool maySleep;
+
+ /// It runs the Product Manager in that Mac's Harness Team account.
+ final bool team;
+
+ /// The engines it runs in that Mac's Harness Team account, as the server
+ /// decided (backend leadStart.ts `leadChoices`); null where it does not say.
+ final Set<String>? teamEngines;
+
+ /// Why the Product Manager cannot start here whatever its engine, or null.
+ final String? unavailable;
+
+ /// Why an engine cannot run a Product Manager here, by engine; an engine
+ /// not in it runs.
+ final Map<String, String> engineRefusals;
+
+ bool runs(String engine) => !engineRefusals.containsKey(engine);
+
+ /// The engines it runs a Product Manager with, best first.
+ List<String> get leadEngines => [
+ for (final engine in swarmLeadEngines)
+ if (runs(engine)) engine,
+ ];
+
+ /// The engine its Product Manager starts with: the first it runs.
+ String? get engine => leadEngines.firstOrNull;
+
+ /// It runs with [engine] in that Mac's Harness Team account.
+ bool inTeam(String engine) => teamEngines?.contains(engine) ?? team;
+
+ /// It can start a Product Manager now.
+ bool get startable =>
+ unavailable == null && online && freeAgents > 0 && leadEngines.isNotEmpty;
+
+ /// Its line under its name, in words: why it cannot take the Product
+ /// Manager, or the engine it starts it with and its room (Desktop's
+ /// `leadMachineDetail`).
+ String get detail {
+ if (unavailable case final why?) return why;
+ if (!online) return 'Offline';
+ if (leadEngines.isEmpty) {
+ // One reason for both engines (a paused or offline machine) said once.
+ return 'Can’t run a Product Manager: '
+ '${{for (final engine in swarmLeadEngines) ?engineRefusals[engine]}.join(', ')}';
+ }
+ final engine = this.engine!;
+ return [
+ swarmLeadEngineLabel(engine),
+ freeAgents <= 0
+ ? 'No agents free'
+ : '$freeAgents ${freeAgents == 1 ? 'agent' : 'agents'} free',
+ if (freeAgents > 0 && inTeam(engine)) 'Team account',
+ if (freeAgents > 0 && maySleep) 'May sleep',
+ ].join(' · ');
+ }
+}
+
+/// Why each of [swarmLeadEngines] cannot run a Product Manager on a machine,
+/// from what the Swarm reads of it: the engines it offers ([offered], null when
+/// not reported), each engine's install and sign-in ([readiness], null for not
+/// known), its subscription windows' use ([usedPercents]) and the engines the
+/// server suspended there ([suspended], with why). What is not known rules
+/// nothing out (Desktop's `leadEngineRefusals`).
+Map<String, String> swarmLeadEngineRefusals({
+ Set<String>? offered,
+ Map<String, ({bool? installed, bool? signedIn})> readiness = const {},
+ Map<String, List<num>> usedPercents = const {},
+ Map<String, String> suspended = const {},
+}) {
+ String? refusal(String engine) {
+ final label = swarmLeadEngineLabel(engine);
+ if (offered != null && !offered.contains(engine)) {
+ return '$label isn’t offered here';
+ }
+ if (readiness[engine]?.installed == false) return '$label isn’t installed';
+ if (readiness[engine]?.signedIn == false) return '$label isn’t signed in';
+ if ((usedPercents[engine] ?? const []).any((used) => used >= 100)) {
+ return '$label has no quota left until it resets';
+ }
+ return suspended[engine];
+ }
+
+ return {for (final engine in swarmLeadEngines) engine: ?refusal(engine)};
+}
+
+/// The engines the Swarm's model list ([policy], its routing policy) has no
+/// enabled model of, with why: none of them may run a new project's Product
+/// Manager (Desktop's `LeadModelList.engineRefusal`). Null or unread rules
+/// nothing out.
+Map<String, String> swarmLeadModelListRefusals(Map<String, dynamic>? policy) {
+ final byEngine = <String, bool>{};
+ for (final row in policy?['models'] as List? ?? const []) {
+ if (row case {'engine': final String engine, 'enabled': final bool on}) {
+ byEngine[engine] = (byEngine[engine] ?? false) || on;
+ }
+ }
+ return {
+ for (final MapEntry(:key, :value) in byEngine.entries)
+ if (!value && swarmLeadEngines.contains(key))
+ key:
+ 'The Swarm’s model list has no enabled '
+ '${const {'claude': 'Claude', 'codex': 'Codex'}[key]} model',
+ };
+}
+
+/// The Swarm's machines a new project's Product Manager could start on, one
+/// row per computer, best first: Desktop's `leadMachinesOf`, where every start
+/// is the Swarm's (`lead.start`), never the phone's. The person's own machine
+/// takes it when its Harness can start one and an engine runs there; a
+/// teammate's as the server decided for each engine (backend leadStart.ts
+/// `leadChoices`), or, from a server that does not say, its Harness Team
+/// account or the Mac itself as Desktop reads them. [modelList] rules engines
+/// out everywhere ([swarmLeadModelListRefusals]).
+List<SwarmLeadMachine> swarmLeadMachines(
+ SuperTabSnapshot snapshot,
+ String accountId, {
+ required DateTime now,
+ Map<String, String> modelList = const {},
+}) {
+ Map<String, dynamic> part(Object? value) =>
+ value is Map ? superTabMap(value) : const {};
+ bool fresh(Map<String, dynamic> observation) =>
+ switch (observation['receivedAt']) {
+ final num at =>
+ now.difference(DateTime.fromMillisecondsSinceEpoch(at.toInt())) <=
+ _freshFor,
+ _ => false,
+ };
+ bool hostsLead(Map<String, dynamic> observation) =>
+ (observation['capabilities'] as List?)?.contains('leadStart') == true;
+
+ SwarmLeadMachine row(String id, Map<String, dynamic> pool) {
+ final reading = snapshot.readingPoolOf(id, accountId) ?? pool;
+ final observation = part(reading['observation']);
+ final name = _machineName(pool['name'] as String? ?? id);
+ final own = pool['contributorId'] == accountId;
+ final capable = hostsLead(observation);
+ // Another person's Mac runs one in its Harness Team account when that
+ // takes it now, else itself.
+ final teamReading =
+ !own &&
+ (reading['hostMachineId'] != null ||
+ observation['sessionKind'] == 'team');
+ final teamRefusal = !teamReading
+ ? null
+ : switch (reading['teamWork']) {
+ {'allowed': false, 'reason': final String reason} => reason,
+ _ when !capable =>
+ 'Update Harness on $name to run a Product Manager there.',
+ _ => null,
+ };
+ final team =
+ teamReading &&
+ teamRefusal == null &&
+ fresh(observation) &&
+ reading['paused'] != true;
+ final mac = part(pool['observation']);
+ // A Mac added as its person joined takes teammates' work only in its
+ // Team account (backend machines.ts teamAccountOnly).
+ final macTakes =
+ pool['teamAccountOnly'] != true &&
+ pool['hostMachineId'] == null &&
+ mac['sessionKind'] != 'team' &&
+ hostsLead(mac);
+ // On a teammate's machine the server decides, by engine, where it runs,
+ // as the start itself does.
+ final decided = <String, String>{}, refused = <String, String>{};
+ if (!own && pool['lead'] is Map) {
+ for (final MapEntry(:key, :value) in superTabMap(pool['lead']).entries) {
+ switch (value) {
+ case {'machineId': final String machine}:
+ decided[key] = machine;
+ case {'refused': final String why}:
+ // Its line adds its own full stop.
+ refused[key] = why.endsWith('.')
+ ? why.substring(0, why.length - 1)
+ : why;
+ }
+ }
+ }
+ final server = decided.isNotEmpty || refused.isNotEmpty;
+ final shownHost = [for (final engine in swarmLeadEngines) ?decided[engine]]
+ .firstOrNull;
+ // Where it would run: the server's machine for its first engine that
+ // runs; else the Mac itself when its Team account cannot.
+ final host = server
+ ? (shownHost == null ? pool : snapshot.pool(shownHost) ?? pool)
+ : teamReading && !team
+ ? pool
+ : reading;
+ final hostReading = part(host['observation']);
+ final running = hostReading['runningHarnessIds'];
+ final max = host['maxAgents'];
+ final device = part(hostReading['resources'])['deviceType'];
+ final engineRefusals = {
+ ...server
+ ? {
+ for (final engine in swarmLeadEngines)
+ if (refused[engine] ?? (decided[engine] == null ? '' : null)
+ case final why?)
+ engine: why.isEmpty ? 'Not offered by this Swarm' : why,
+ }
+ : swarmLeadEngineRefusals(
+ offered: switch (host['engines']) {
+ final List engines => engines.whereType<String>().toSet(),
+ _ => null,
+ },
+ readiness: {
+ for (final raw
+ in part(hostReading['readiness'])['engines'] as List? ??
+ const [])
+ if (part(raw)
+ case {'engine': final String engine} && final row)
+ engine: (
+ installed: row['installed'] as bool?,
+ signedIn: row['signedIn'] as bool?,
+ ),
+ },
+ usedPercents: {
+ for (final raw in hostReading['quotas'] as List? ?? const [])
+ if (part(raw) case {
+ 'engine': final String engine,
+ 'known': true,
+ 'windows': final List windows,
+ })
+ engine: [
+ for (final window in windows)
+ if (part(window)['usedPercent'] case final num used)
+ used,
+ ],
+ },
+ suspended: {
+ for (final source in {pool, host})
+ if (source['suspendedEngines'] case final Map raw)
+ for (final MapEntry(:key, :value) in raw.entries)
+ if ((key, value) case (
+ final String engine,
+ final String why,
+ ))
+ engine: why,
+ },
+ ),
+ // The Swarm's model list rules an engine out wherever it would run.
+ for (final MapEntry(:key, :value) in modelList.entries)
+ if (swarmLeadEngines.contains(key)) key: value,
+ };
+ return SwarmLeadMachine(
+ id: id,
+ name: name,
+ online: fresh(hostReading),
+ // The server's count holds pending starts and the Team account sharing
+ // a Mac; a server without it: slots minus running.
+ freeAgents: switch (host['availableSlots']) {
+ final num slots => math.max(0, slots.toInt()),
+ _ => math.max(
+ 0,
+ (max is num ? max.toInt() : 0) -
+ (running is List ? running.length : 0),
+ ),
+ },
+ own: own,
+ maySleep:
+ device is String && device.trim().toLowerCase().startsWith('macbook'),
+ team: server ? shownHost != null && shownHost != id : team,
+ teamEngines: server
+ ? {
+ for (final MapEntry(:key, :value) in decided.entries)
+ if (value != id) key,
+ }
+ : null,
+ engineRefusals: engineRefusals,
+ unavailable: snapshot.paused
+ ? swarmLeadSwarmPaused
+ // The Swarm starts it on the person's own machine too: its Harness
+ // must be able to (backend leadStart.ts `admitLead`).
+ : own
+ ? (pool['paused'] == true
+ ? 'Paused in this Swarm'
+ // Added for the Lead only: the server takes no other
+ // project's work there (backend machines.ts
+ // admitMachineStart, PROJECT_CONTRIBUTION).
+ : pool['scope'] != 'swarm'
+ ? swarmLeadUnscoped
+ : capable
+ ? null
+ : 'Update Harness on $name to run a Product Manager there.')
+ // The server's reasons are each engine's (engineRefusals).
+ : server
+ ? null
+ : host['paused'] == true
+ ? 'Paused in this Swarm'
+ : team || macTakes
+ ? null
+ : teamRefusal ??
+ switch (pool['teamWork']) {
+ {'allowed': false, 'reason': final String reason} => reason,
+ _ =>
+ 'Update Harness on $name to run a Product Manager there.',
+ },
+ );
+ }
+
+ final machines = [
+ for (final pool in snapshot.machines)
+ if (pool['machineId'] case final String id
+ when snapshot.placeOf(id) == id && pool['removal'] == null)
+ row(id, pool),
+ ];
+ // Best first: one that can start it now (the person's own first, those
+ // that stay on before laptops, the most room), then full ones, then the
+ // ones that cannot, then offline ones (Desktop's `rankLeadMachines`).
+ int tier(SwarmLeadMachine m) => m.startable
+ ? 0
+ : m.unavailable == null && m.online && m.leadEngines.isNotEmpty
+ ? 1
+ : m.online
+ ? 2
+ : 3;
+ int flag(bool value) => value ? 0 : 1;
+ return machines..sort(
+ (a, b) => [
+ tier(a).compareTo(tier(b)),
+ flag(a.own).compareTo(flag(b.own)),
+ flag(!a.maySleep).compareTo(flag(!b.maySleep)),
+ b.freeAgents.compareTo(a.freeAgents),
+ a.name.toLowerCase().compareTo(b.name.toLowerCase()),
+ ].firstWhere((order) => order != 0, orElse: () => 0),
+ );
+}
+
+/// Why the Product Manager cannot start on [machineId] now, in words that
+/// say what to do; null when it can (Desktop's `checkLeadMachine`).
+String? swarmLeadMachineRefusal(
+ List<SwarmLeadMachine> machines,
+ String machineId,
+) {
+ final chosen = machines.where((m) => m.id == machineId).firstOrNull;
+ if (chosen == null) return 'Choose one of this Swarm’s machines.';
+ if (chosen.startable) return null;
+ final name = chosen.name;
+ if (chosen.unavailable case final why?) {
+ // One full stop, whether its reason ends with one or not.
+ return '$name: ${why.endsWith('.') ? why : '$why.'} '
+ 'Choose another machine.';
+ }
+ return !chosen.online
+ ? '$name is offline. Choose another machine.'
+ : chosen.leadEngines.isEmpty
+ ? '$name: ${chosen.detail}. Choose another machine.'
+ : '$name has no free agents. Choose another machine.';
+}
+
+/// A machine's name without its `.local`, as Desktop shows it.
+String _machineName(String name) {
+ const suffix = '.local';
+ return name.length > suffix.length && name.toLowerCase().endsWith(suffix)
+ ? name.substring(0, name.length - suffix.length)
+ : name;
+}
+
+/// One repository however its address is spelled: `host/owner/name`, lower
+/// case, without scheme, user, `.git` or trailing slash; null for none
+/// (Desktop's `leadRepositoryKey`).
+String? swarmRepositoryKey(String? remote) {
+ var value = remote?.trim().toLowerCase() ?? '';
+ if (value.isEmpty) return null;
+ value = value.replaceFirst(RegExp(r'^[a-z+]+://'), '');
+ value = value.replaceFirst(RegExp(r'^[^@/]+@'), '');
+ // scp-like `host:owner/name`.
+ value = value.replaceFirstMapped(
+ RegExp(r'^([^/:]+):(?!\d)'),
+ (m) => '${m[1]}/',
+ );
+ value = value.replaceFirst(RegExp(r'/+$'), '');
+ value = value.replaceFirst(RegExp(r'\.git$'), '');
+ return value.isEmpty ? null : value;
+}
+
+/// A repository's name as a project takes it: the last part of its address,
+/// without `.git`.
+String swarmRepositoryName(String url) {
+ final key = swarmRepositoryKey(url) ?? url;
+ final name = key.split('/').where((part) => part.isNotEmpty).lastOrNull;
+ return name == null || name.isEmpty ? 'New project' : name;
+}
+
+/// Whether the server takes [value] as a project's repository: a git or web
+/// address with a host and no credentials, or `git@host:path` (backend
+/// commands.ts `repositoryUrl`). Never stricter in what it lets through.
+bool swarmRepositoryUrlValid(String value) {
+ if (value.isEmpty || value.length > 4096) return false;
+ if (RegExp(r'[\x00-\x20\x7f]').hasMatch(value)) return false;
+ if (RegExp(r'^git@[^/@:]+:[^@]+$').hasMatch(value)) return true;
+ final uri = Uri.tryParse(value);
+ if (uri == null || !uri.hasScheme || uri.host.isEmpty) return false;
+ if (!const {'https', 'http', 'ssh', 'git'}.contains(uri.scheme)) {
+ return false;
+ }
+ final user = uri.userInfo;
+ final colon = user.indexOf(':');
+ final username = colon < 0 ? user : user.substring(0, colon);
+ final password = colon < 0 ? '' : user.substring(colon + 1);
+ if (password.isNotEmpty) return false;
+ return username.isEmpty || (uri.scheme == 'ssh' && username == 'git');
+}
+
+/// The address a typed link stands for, or null when the server would refuse
+/// it: trimmed, and `github.com/owner/name` read as its https address, as
+/// Desktop reads a checkout's remote.
+String? swarmRepositoryLink(String typed) {
+ final value = typed.trim();
+ final link = value.toLowerCase().startsWith('github.com/')
+ ? 'https://$value'
+ : value;
+ return swarmRepositoryUrlValid(link) ? link : null;
+}
+
+/// The repositories of the projects [reader] reads in its Swarm, once each,
+/// the most recently active project's first: what New project offers, with
+/// the first chosen for the person (Lead's ruling, 10-30). Only projects the
+/// person may read are in a read, so no other project's repository shows.
+List<String> swarmProjectRepositories(SwarmReader reader) {
+ final snapshot = reader.snapshot;
+ if (snapshot == null) return const [];
+ final activity = swarmProjectActivity(snapshot, reader.buddies);
+ final never = DateTime.fromMillisecondsSinceEpoch(0, isUtc: true);
+ final projects = [...snapshot.projects]
+ ..sort(
+ (a, b) => (activity[b.id] ?? never).compareTo(activity[a.id] ?? never),
+ );
+ final seen = <String>{};
+ return [
+ for (final project in projects)
+ if (project.repository?['repositoryUrl'] case final String url
+ when swarmRepositoryUrlValid(url) &&
+ seen.add(swarmRepositoryKey(url) ?? url))
+ url,
+ ];
+}
+
+/// A step of New project stopped because the sheet that asked for it went:
+/// its Swarm, the person's access or their account. Nothing more is sent.
+class SwarmNewProjectGone implements Exception {
+ const SwarmNewProjectGone();
+}
+
+/// The New project steps each Swarm's reader holds until they finish: kept
+/// with the session's reader of that Swarm, so they go with the Swarm, the
+/// person's access to it or their account, and never outlive the session.
+final _heldSteps = Expando<SwarmNewProjectSteps>('New project steps');
+
+/// One New project's steps in one Swarm, as Desktop's `startInSwarm` runs
+/// them: the project, its brief in its chat, its Product Manager's start on
+/// the machine picked, then its name. Each request is kept as first sent,
+/// under one operation id, until the steps finish: Create again repeats only
+/// what has not answered, and the Swarm answers a repeated operation with its
+/// receipt, so a lost answer never makes a second project. Only a definite
+/// refusal drops a request, so the next attempt (perhaps on another machine)
+/// is a new one. The Swarm's reader holds them ([SwarmNewProjectSteps.of]):
+/// the sheet closed or torn down between steps, opening it again resumes
+/// them (Lead's ruling on #2324).
+class SwarmNewProjectSteps {
+ SwarmNewProjectSteps._(this.reader);
+
+ /// The steps [reader]'s Swarm holds, or new ones it holds from now on.
+ factory SwarmNewProjectSteps.of(SwarmReader reader) =>
+ _heldSteps[reader] ??= SwarmNewProjectSteps._(reader);
+
+ /// The steps [reader]'s Swarm holds, if any.
+ static SwarmNewProjectSteps? heldBy(SwarmReader reader) => _heldSteps[reader];
+
+ final SwarmReader reader;
+
+ Map<String, dynamic>? _create, _brief, _start;
+ String? _projectId, _conversationId;
+ bool _briefPosted = false, _started = false, _named = false;
+
+ Future<void>? _running;
+
+ /// The run under way, if any: the next waits for it.
+ Future<void>? get running => _running;
+
+ /// What the sheet last chose and last said, to show again when it opens
+ /// on these steps.
+ String? chosenMachine, chosenRepository, failure;
+
+ /// The project exists: its Swarm, brief and visibility are what it was
+ /// made with.
+ String? get projectId => _projectId;
+
+ /// Its creation was asked for: Swarm, brief and visibility stay as sent.
+ bool get sent => _create != null || _projectId != null;
+
+ /// Its creation was asked for and never answered: the Swarm may have made
+ /// it all the same. A refusal made nothing, and drops the request.
+ bool get createUnanswered => _create != null && _projectId == null;
+
+ /// The brief and visibility its creation was asked with, once [sent].
+ String? get sentBrief =>
+ superTabMap(_create?['command'] ?? const {})['brief'] as String?;
+ String? get sentVisibility =>
+ superTabMap(_create?['command'] ?? const {})['visibility'] as String?;
+
+ /// A start was sent and has not answered: a retry repeats it as it is.
+ bool get starting => _start != null && !_started;
+
+ /// The Swarm took its Product Manager's start: only its name is left.
+ bool get started => _started;
+
+ /// A start was sent, answered or not: its machine and repository stay as
+ /// sent, whatever the machine's room says now.
+ bool get startSent => _start != null;
+
+ /// The machine of the start under way, if any.
+ String? get startMachine =>
+ superTabMap(_start?['command'] ?? const {})['machineId'] as String?;
+
+ /// The repository of the start under way, if any.
+ String? get startRepository =>
+ superTabMap(_start?['command'] ?? const {})['repositoryUrl'] as String?;
+
+ /// Done with: the Swarm holds them no more.
+ void forget() {
+ if (identical(_heldSteps[reader], this)) _heldSteps[reader] = null;
+ }
+
+ /// Runs what is left: creates the project with [brief] and [visibility],
+ /// posts [brief] in its chat, starts its Product Manager on [machineId]
+ /// with the repository [repositoryUrl], then names it after that
+ /// repository. Answers the project's id once all of it is done and read.
+ /// Each answer is kept before [live] is asked: once it says no, nothing
+ /// more is sent and [SwarmNewProjectGone] is thrown, and the next run
+ /// starts after what was answered. [machinesOf] lists the machines from a
+ /// fresh read before a start is first sent, as Desktop checks the machine
+ /// again: one that can no longer take it is refused with why, and nothing
+ /// is sent. A project made in an earlier run is looked for first, and one
+ /// deleted since lets the steps go. A name the Swarm refuses counts as
+ /// done. One run at a time: a second waits for the first.
+ Future<String> run({
+ required String brief,
+ required String visibility,
+ required String machineId,
+ required String repositoryUrl,
+ required bool Function() live,
+ required List<SwarmLeadMachine> Function(SuperTabSnapshot snapshot)
+ machinesOf,
+ }) async {
+ for (var running = _running; running != null; running = _running) {
+ await running;
+ }
+ final done = Completer<void>();
+ _running = done.future;
+ try {
+ return await _run(
+ brief: brief,
+ visibility: visibility,
+ machineId: machineId,
+ repositoryUrl: repositoryUrl,
+ live: live,
+ machinesOf: machinesOf,
+ );
+ } finally {
+ _running = null;
+ done.complete();
+ }
+ }
+
+ Future<String> _run({
+ required String brief,
+ required String visibility,
+ required String machineId,
+ required String repositoryUrl,
+ required bool Function() live,
+ required List<SwarmLeadMachine> Function(SuperTabSnapshot snapshot)
+ machinesOf,
+ }) async {
+ void check() {
+ if (!live()) throw const SwarmNewProjectGone();
+ }
+
+ check();
+ final text = String.fromCharCodes(
+ brief.trim().runes.take(swarmNewProjectBriefRunes),
+ ).trim();
+ // Made in an earlier run, it may have been deleted since (from Desktop,
+ // say): then these steps are done with, whatever step they stopped at.
+ // Unread, the steps left say what is wrong themselves.
+ var read = false;
+ if (_projectId case final made?) {
+ switch (await _deleted(made, check)) {
+ case true:
+ _gone();
+ case false:
+ read = true;
+ case null:
+ }
+ }
+ if (_projectId == null) {
+ _create ??= {
+ 'operationId': superTabOperationId(),
+ 'command': {
+ 'type': 'project.create',
+ 'name': 'New project',
+ 'visibility': visibility,
+ 'brief': text,
+ },
+ };
+ final result = await _send(() => _create, (v) => _create = v);
+ final (projectId, conversationId) = switch (result) {
+ {
+ 'projectId': final String project,
+ 'conversationId': final String conversation,
+ } =>
+ (project, conversation),
+ _ => throw const FormatException('The Swarm did not name the project.'),
+ };
+ _projectId = projectId;
+ _conversationId = conversationId;
+ // In Home's list at once, while its Product Manager starts.
+ unawaited(reader.refresh());
+ check();
+ }
+ final projectId = _projectId!;
+ // The brief the project was made with, whatever the field says now.
+ final posted = sentBrief ?? text;
+ if (!_briefPosted && posted.isNotEmpty) {
+ _brief ??= {
+ 'operationId': superTabOperationId(),
+ 'command': {
+ 'type': 'message.send',
+ 'conversationId': _conversationId,
+ 'text': posted,
+ 'replyTo': null,
+ 'recipientIds': const <String>[],
+ },
+ };
+ await _send(() => _brief, (v) => _brief = v);
+ _briefPosted = true;
+ check();
+ }
+ if (!_started) {
+ if (_start == null) {
+ // The list from when the sheet drew it may be stale: read the Swarm
+ // again (unless this run just did), and send nothing to a machine
+ // that cannot take it now, nor for a project deleted meanwhile.
+ final deleted = read ? false : await _deleted(projectId, check);
+ final snapshot = reader.snapshot;
+ if (deleted == null || snapshot == null) {
+ throw const SuperTabFailure(
+ 'SWARM_UNREADABLE',
+ 'Couldn’t check the machine for the Product Manager: the Swarm '
+ 'didn’t answer. Try again.',
+ );
+ }
+ if (deleted) _gone();
+ final machines = machinesOf(snapshot);
+ if (swarmLeadMachineRefusal(machines, machineId) case final why?) {
+ throw SuperTabFailure('MACHINE_UNAVAILABLE', why);
+ }
+ final machine = machines.firstWhere((m) => m.id == machineId);
+ _start = {
+ 'operationId': superTabOperationId(),
+ 'command': {
+ 'type': 'lead.start',
+ 'projectId': projectId,
+ 'machineId': machineId,
+ // No model: the Swarm fills its role's default where the owner's
+ // model list and rules allow it (backend commands.ts lead.start).
+ 'engine': machine.engine,
+ 'repositoryUrl': repositoryUrl,
+ },
+ };
+ }
+ await _send(() => _start, (v) => _start = v);
+ _started = true;
+ check();
+ }
+ final name = swarmRepositoryName(startRepository ?? repositoryUrl);
+ if (!_named) {
+ try {
+ await _send(
+ () => {
+ 'operationId':
+ '${superTabMap(_create ?? const {})['operationId'] ?? projectId}-name',
+ 'command': {
+ 'type': 'project.rename',
+ 'projectId': projectId,
+ 'name': name,
+ },
+ },
+ (_) {},
+ );
+ } on SuperTabFailure catch (failure) {
+ // Refused, it never will be: the project keeps the name it has and
+ // opens by it, rather than hold the steps (Lead's re-review).
+ if (!_refusedOutright(failure)) rethrow;
+ }
+ _named = true;
+ check();
+ }
+ // Read before the project opens, so its screen finds it by its name:
+ // once more when the read joined was asked before the name was.
+ for (var i = 0; i < 2; i++) {
+ await reader.refresh();
+ check();
+ if (reader.snapshot?.projectById(projectId)?.name == name) break;
+ }
+ // Not there (its name refused because it was deleted, say): it says so
+ // rather than close on nothing.
+ if (reader.snapshot?.projectById(projectId) == null &&
+ (await _deleted(projectId, check) ?? false)) {
+ _gone();
+ }
+ forget();
+ return projectId;
+ }
+
+ /// Whether project [projectId] was deleted: absent from a read of the
+ /// Swarm asked after it was made. A read already on its way is joined and
+ /// may have been asked before, so an absence is read once more before it
+ /// counts. Null when the Swarm did not answer. [check] runs after each
+ /// read.
+ Future<bool?> _deleted(String projectId, void Function() check) async {
+ for (var i = 0; i < 2; i++) {
+ final reads = reader.reads.value;
+ await reader.refresh();
+ check();
+ final snapshot = reader.snapshot;
+ if (reader.reads.value == reads || snapshot == null) return null;
+ if (snapshot.projectById(projectId) != null) return false;
+ }
+ return true;
+ }
+
+ /// Its project deleted meanwhile: these steps are done with, and the next
+ /// Create makes a new project.
+ Never _gone() {
+ forget();
+ throw const SuperTabFailure(
+ 'PROJECT_GONE',
+ 'The project was deleted meanwhile. Create it again.',
+ );
+ }
+
+ /// Sends the request [held] holds exactly as it was first written and
+ /// answers its result. A definite refusal drops it ([drop] with null).
+ Future<Map<String, dynamic>> _send(
+ Map<String, dynamic>? Function() held,
+ void Function(Map<String, dynamic>? value) drop,
+ ) async {
+ final request = held()!;
+ try {
+ final answer = superTabMap(
+ await reader.request(
+ 'POST',
+ '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}/commands',
+ body: request,
+ ),
+ );
+ return answer['result'] is Map ? superTabMap(answer['result']) : const {};
+ } on SuperTabFailure catch (failure) {
+ if (_refusedOutright(failure)) drop(null);
+ rethrow;
+ }
+ }
+
+ /// The Swarm said no and wrote nothing: a 4xx answer other than a timeout
+ /// or a rate limit. A transport failure or a 5xx may have been committed.
+ static bool _refusedOutright(SuperTabFailure failure) =>
+ failure.statusCode >= 400 &&
+ failure.statusCode < 500 &&
+ failure.statusCode != 408 &&
+ failure.statusCode != 429;
+}
+
+/// Swarm Home's last Projects row, in a project row's shape: a plus, then
+/// "New project". Shown only to someone who may write in a Swarm Home shows
+/// ([swarmMayCreateProject]).
+class SwarmNewProjectRow extends StatelessWidget {
+ const SwarmNewProjectRow({super.key, required this.onTap});
+
+ final VoidCallback onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ return Semantics(
+ button: true,
+ label: 'New project',
+ excludeSemantics: true,
+ child: Material(
+ color: Colors.transparent,
+ child: InkWell(
+ onTap: () {
+ HapticFeedback.selectionClick();
+ onTap();
+ },
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(minHeight: SwarmRow.height),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: AppSpace.l,
+ vertical: AppSpace.m,
+ ),
+ child: Row(
+ children: [
+ SizedBox(
+ width: 16,
+ child: Icon(
+ LucideIcons.plus300,
+ size: 18,
+ color: AppPalette.textSecondary,
+ ),
+ ),
+ const SizedBox(width: AppSpace.s),
+ Expanded(
+ child: Text(
+ 'New project',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppType.label(
+ color: AppPalette.textSecondary,
+ height: 1.3,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// A project New project made: the Swarm, and the project.
+typedef SwarmNewProject = ({String swarmId, String projectId});
+
+/// New project, from Swarm Home: which Swarm (only when Home shows several,
+/// and only those of [swarmIds] the person may write in), the brief, the
+/// visibility, the repository and the machine its Product Manager runs on,
+/// then Create. Answers the project once it is made and its Product Manager
+/// asked to start; null when closed. The Swarm taken away, the person's
+/// access to it, or their account, while it is open closes it, and nothing
+/// more is sent. Steps left unfinished stay with the Swarm's reader
+/// ([SwarmNewProjectSteps]): the sheet opens on them again, and stays open
+/// while one of them waits for its answer. [now] is what machine readings
+/// are measured from.
+Future<SwarmNewProject?> showSwarmNewProjectSheet(
+ BuildContext context, {
+ required SwarmSession session,
+ required List<String> swarmIds,
+ DateTime Function() now = DateTime.now,
+}) {
+ // The sheet reads no status bar of its own (the route takes it away).
+ final top = MediaQuery.paddingOf(context).top;
+ return showModalBottomSheet<SwarmNewProject>(
+ context: context,
+ isScrollControlled: true,
+ backgroundColor: AppGlass.rowFill,
+ shape: AppControl.sheetShape,
+ builder: (_) => SwarmNewProjectSheet(
+ session: session,
+ swarmIds: swarmIds,
+ now: now,
+ topInset: top,
+ ),
+ );
+}
+
+/// What [showSwarmNewProjectSheet] shows.
+class SwarmNewProjectSheet extends StatefulWidget {
+ const SwarmNewProjectSheet({
+ super.key,
+ required this.session,
+ required this.swarmIds,
+ this.now = DateTime.now,
+ this.topInset = 0,
+ });
+
+ final SwarmSession session;
+ final List<String> swarmIds;
+ final DateTime Function() now;
+
+ /// The phone's status bar: with the keyboard up the sheet reaches it.
+ final double topInset;
+
+ @override
+ State<SwarmNewProjectSheet> createState() => _SwarmNewProjectSheetState();
+}
+
+/// What the sheet shows in place of its form: one of its choices' lists.
+enum _Pick { swarm, visibility, repository, link, machine }
+
+class _SwarmNewProjectSheetState extends State<SwarmNewProjectSheet> {
+ final _brief = TextEditingController();
+ final _link = TextEditingController();
+ String? _swarmId;
+ String _visibility = 'public';
+
+ /// The repository the person chose; until then, the Swarm's first
+ /// ([swarmProjectRepositories]).
+ String? _repository;
+ bool _repositoryPicked = false;
+ String? _machineId;
+ _Pick? _picking;
+ String? _linkError;
+
+ /// A step's answer is awaited: the sheet stays open until it comes.
+ bool _busy = false;
+ String? _error;
+ final _errorKey = GlobalKey();
+
+ /// Start over let go of a create never answered ([swarmNewProjectMaybeMade]),
+ /// until the next Create or another Swarm.
+ bool _maybeMade = false;
+
+ /// The model list of the Swarm [_policySwarm], once read.
+ Map<String, String> _modelList = const {};
+ String? _policySwarm;
+ int _policyReads = 0;
+
+ bool _closing = false;
+ SwarmSession? _scoped;
+
+ SwarmInbox get _inbox => widget.session.inbox;
+
+ /// Each Swarm's reader as the sheet opened. One replaced since (its Swarm
+ /// left Home's list and came back) is another read of it: the sheet goes
+ /// rather than send through either.
+ late final Map<String, SwarmReader?> _readers;
+
+ List<String> get _writable => [
+ for (final id in widget.swarmIds)
+ if (_readers[id] case final reader?
+ when identical(_inbox.reader(id), reader) &&
+ swarmMayCreateProject(_inbox, id))
+ id,
+ ];
+
+ /// The steps the Swarm picked holds, if any.
+ SwarmNewProjectSteps? get _steps => switch (_readers[_swarmId]) {
+ final reader? => SwarmNewProjectSteps.heldBy(reader),
+ null => null,
+ };
+
+ @override
+ void initState() {
+ super.initState();
+ _readers = {for (final id in widget.swarmIds) id: _inbox.reader(id)};
+ final writable = _writable;
+ // A Swarm with a project's steps left unfinished: it opens on them.
+ _swarmId =
+ writable
+ .where(
+ (id) => SwarmNewProjectSteps.heldBy(_readers[id]!)?.sent ?? false,
+ )
+ .firstOrNull ??
+ writable.firstOrNull;
+ if (_steps case final steps?) _resume(steps);
+ if (_swarmId case final id?) unawaited(_readModelList(id));
+ }
+
+ /// Shows [steps] where they stopped: what they were sent with, what was
+ /// last chosen, and why they stopped. A run still under way keeps the
+ /// sheet busy until it answers.
+ void _resume(SwarmNewProjectSteps steps) {
+ if (steps.sentBrief case final brief?) _brief.text = brief;
+ if (steps.sentVisibility case final visibility?) _visibility = visibility;
+ if (steps.chosenRepository case final repository?) {
+ _repository = repository;
+ _repositoryPicked = true;
+ }
+ _machineId = steps.chosenMachine;
+ _error = steps.failure;
+ if (_error != null) _showError();
+ if (steps.running case final running?) {
+ _busy = true;
+ unawaited(
+ running.whenComplete(() {
+ if (!mounted || _closing) return;
+ setState(() {
+ _busy = false;
+ _error = steps.failure;
+ });
+ if (_error != null) _showError();
+ }),
+ );
+ }
+ }
+
+ /// Steps nothing was sent for, nor runs: let go, so the next Create
+ /// starts afresh.
+ void _dropUnsent() {
+ if (_steps case final steps? when !steps.sent && steps.running == null) {
+ steps.forget();
+ }
+ }
+
+ /// Scrolls why Create stopped into sight once it is drawn.
+ void _showError() => WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (_errorKey.currentContext case final shown? when mounted) {
+ unawaited(Scrollable.ensureVisible(shown, alignment: 1));
+ }
+ });
+
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+ _scoped = SwarmScope.of(context);
+ }
+
+ @override
+ void dispose() {
+ _dropUnsent();
+ _brief.dispose();
+ _link.dispose();
+ super.dispose();
+ }
+
+ /// The sheet still stands for [swarmId]: open, the account's session the
+ /// same, and the person still able to write in it.
+ bool _live(String swarmId, SwarmReader reader) =>
+ mounted &&
+ !_closing &&
+ _scoped == widget.session &&
+ identical(_inbox.reader(swarmId), reader) &&
+ swarmMayCreateProject(_inbox, swarmId);
+
+ /// Reads Swarm [swarmId]'s model list. Unread, nothing is ruled out by it;
+ /// an answer for a Swarm no longer picked is dropped.
+ Future<void> _readModelList(String swarmId) async {
+ final reader = _inbox.reader(swarmId);
+ if (reader == null) return;
+ final read = ++_policyReads;
+ Map<String, String> refusals = const {};
+ try {
+ final answer = superTabMap(
+ await reader.request(
+ 'GET',
+ '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}/routing-policy',
+ ),
+ );
+ refusals = swarmLeadModelListRefusals(
+ answer['policy'] is Map ? superTabMap(answer['policy']) : null,
+ );
+ } catch (_) {
+ // Unread: the start's own checks still apply.
+ }
+ if (read != _policyReads ||
+ _swarmId != swarmId ||
+ !_live(swarmId, reader)) {
+ return;
+ }
+ setState(() {
+ _modelList = refusals;
+ _policySwarm = swarmId;
+ });
+ }
+
+ /// Closes the sheet once, after the frame it went blank in.
+ void _close() {
+ if (_closing) return;
+ _closing = true;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted) return;
+ final route = ModalRoute.of(context);
+ if (route == null || !route.isActive) return;
+ if (route.isCurrent) {
+ Navigator.of(context).pop();
+ } else {
+ Navigator.of(context).removeRoute(route);
+ }
+ });
+ }
+
+ List<SwarmLeadMachine> _machinesOf(
+ String swarmId,
+ SuperTabSnapshot snapshot,
+ ) => swarmLeadMachines(
+ snapshot,
+ widget.session.inbox.reader(swarmId)?.accountId ?? '',
+ now: widget.now(),
+ modelList: _policySwarm == swarmId ? _modelList : const {},
+ );
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ // Signed out or another account: its session is gone, and nothing of it
+ // is listened to again.
+ if (_closing || SwarmScope.of(context) != widget.session) {
+ _close();
+ return const SizedBox.shrink();
+ }
+ return ListenableBuilder(
+ listenable: Listenable.merge([
+ widget.session,
+ _inbox,
+ // Not one replaced since: the inbox disposes it.
+ for (final MapEntry(:key, :value) in _readers.entries)
+ if (value != null && identical(_inbox.reader(key), value)) value,
+ ]),
+ builder: (context, _) {
+ final writable = _writable;
+ final swarmId = _swarmId;
+ // Signed out, another account, or the Swarm picked no longer the
+ // person's to write in, or read again: nothing of it stays, and the
+ // sheet goes.
+ if (_closing ||
+ SwarmScope.of(context) != widget.session ||
+ swarmId == null ||
+ !writable.contains(swarmId)) {
+ _close();
+ return const SizedBox.shrink();
+ }
+ final reader = _inbox.reader(swarmId)!;
+ final snapshot = reader.snapshot!;
+ final insets = MediaQuery.viewInsetsOf(context).bottom;
+ final height = MediaQuery.sizeOf(context).height;
+ // With the keyboard up the sheet may reach the status bar, so what
+ // is typed in and Create both stay in sight on a small phone.
+ final maxHeight =
+ (insets > 0
+ ? height - widget.topInset - AppSpace.s
+ : height * .85) -
+ insets;
+ // While a step's answer is unknown the sheet stays: its close, the
+ // back gesture, the dimmed page behind it, and a drag down (which
+ // closes a sheet past PopScope) do nothing.
+ return PopScope(
+ canPop: !_busy,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onVerticalDragStart: _busy ? (_) {} : null,
+ child: Padding(
+ padding: EdgeInsets.only(bottom: insets),
+ child: ConstrainedBox(
+ constraints: BoxConstraints(maxHeight: math.max(0, maxHeight)),
+ child: SafeArea(
+ top: false,
+ child: KeyedSubtree(
+ key: const ValueKey('swarm-new-project-sheet'),
+ child: switch (_picking) {
+ null => _form(
+ context,
+ writable,
+ swarmId,
+ reader,
+ snapshot,
+ ),
+ final pick => _pick(
+ context,
+ pick,
+ writable,
+ swarmId,
+ reader,
+ snapshot,
+ ),
+ },
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ },
+ );
+ }
+
+ /// The sheet's grabber and [header] at its top and [footer] (its one
+ /// button) at its bottom, always in sight; [children] between them scroll
+ /// when the phone, or the room the keyboard leaves, is too short for them.
+ Widget _frame({
+ required Widget header,
+ required List<Widget> children,
+ List<Widget> footer = const [],
+ }) => Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ AppSpace.l,
+ AppSpace.s,
+ AppSpace.l,
+ 0,
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ // The grabber: a capsule as wide as the two largest steps.
+ Center(
+ child: Container(
+ width: AppSpace.xl + AppSpace.m,
+ height: AppSpace.xs,
+ margin: const EdgeInsets.only(bottom: AppSpace.s),
+ decoration: ShapeDecoration(
+ color: AppGlass.hair,
+ shape: const StadiumBorder(),
+ ),
+ ),
+ ),
+ header,
+ ],
+ ),
+ ),
+ Flexible(
+ child: SingleChildScrollView(
+ padding: EdgeInsets.fromLTRB(
+ AppSpace.l,
+ 0,
+ AppSpace.l,
+ footer.isEmpty ? AppSpace.l : 0,
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: children,
+ ),
+ ),
+ ),
+ if (footer.isNotEmpty)
+ Padding(
+ padding: const EdgeInsets.all(AppSpace.l).copyWith(top: 0),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: footer,
+ ),
+ ),
+ ],
+ );
+
+ /// The sheet's title row: [leading] at its left, [title] in the middle.
+ Widget _header(String title, Widget leading) => Padding(
+ padding: const EdgeInsets.only(bottom: AppSpace.s),
+ child: Row(
+ children: [
+ leading,
+ Expanded(
+ child: Text(
+ title,
+ textAlign: TextAlign.center,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppType.heading(color: AppPalette.textPrimary),
+ ),
+ ),
+ // As wide as [leading], so the title stays in the middle.
+ const SizedBox(width: 44),
+ ],
+ ),
+ );
+
+ Widget _form(
+ BuildContext context,
+ List<String> writable,
+ String swarmId,
+ SwarmReader reader,
+ SuperTabSnapshot snapshot,
+ ) {
+ final steps = _steps;
+ final machines = _machinesOf(swarmId, snapshot);
+ final repositories = swarmProjectRepositories(reader);
+ final repository =
+ steps?.startRepository ??
+ (_repositoryPicked ? _repository : repositories.firstOrNull);
+ final machineId = steps?.startMachine ?? _machineId;
+ final machine = machines.where((m) => m.id == machineId).firstOrNull;
+ final sent = steps?.sent ?? false;
+ final startSent = steps?.startSent ?? false;
+ final blocked = _blocked(snapshot, machines, machine, repository);
+ final swarmName =
+ _inbox.swarms.where((s) => s.id == swarmId).firstOrNull?.name ??
+ snapshot.name;
+ return _frame(
+ header: _header(
+ 'New project',
+ // Dimmed while a step's answer is awaited, and the sheet stays.
+ IgnorePointer(
+ ignoring: _busy,
+ child: Opacity(
+ opacity: _busy ? .55 : 1,
+ child: SwarmIconButton(
+ key: const ValueKey('swarm-new-project-close'),
+ icon: LucideIcons.x300,
+ label: 'Close',
+ onPressed: () => unawaited(Navigator.of(context).maybePop()),
+ ),
+ ),
+ ),
+ ),
+ children: [
+ if (writable.length > 1 || widget.swarmIds.length > 1) ...[
+ SwarmGroup(
+ children: [
+ _Field(
+ key: const ValueKey('swarm-new-project-swarm'),
+ label: 'Swarm',
+ value: swarmName,
+ onTap: sent || _busy
+ ? null
+ : () => setState(() => _picking = _Pick.swarm),
+ ),
+ ],
+ ),
+ const SizedBox(height: AppSpace.m),
+ ],
+ TextField(
+ key: const ValueKey('swarm-new-project-brief'),
+ controller: _brief,
+ enabled: !sent && !_busy,
+ minLines: 3,
+ maxLines: 6,
+ textCapitalization: TextCapitalization.sentences,
+ inputFormatters: const [_RuneLimit(swarmNewProjectBriefRunes)],
+ style: AppType.body(color: AppPalette.textPrimary),
+ decoration: InputDecoration(
+ hintText: 'What should this project work on? (optional)',
+ hintStyle: TextStyle(color: AppPalette.textFaint),
+ filled: true,
+ fillColor: AppPalette.swarmField,
+ border: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(AppControl.radius),
+ borderSide: BorderSide.none,
+ ),
+ ),
+ ),
+ const SizedBox(height: AppSpace.m),
+ SwarmGroup(
+ children: [
+ _Field(
+ key: const ValueKey('swarm-new-project-visibility'),
+ label: 'Visibility',
+ value: _visibility == 'private' ? 'Private' : 'Public',
+ onTap: sent || _busy
+ ? null
+ : () => setState(() => _picking = _Pick.visibility),
+ ),
+ // Just above PM runs on, chosen for the person (Lead, 10-30).
+ _Field(
+ key: const ValueKey('swarm-new-project-repository'),
+ label: 'Repository',
+ value: repository == null
+ ? 'Choose'
+ : swarmRepositoryName(repository),
+ detail: repository == null
+ ? null
+ : swarmRepositoryKey(repository),
+ onTap: startSent || _busy
+ ? null
+ : () => setState(() => _picking = _Pick.repository),
+ ),
+ _Field(
+ key: const ValueKey('swarm-new-project-machine'),
+ label: 'PM runs on',
+ value: machine?.name ?? 'Choose',
+ detail: machine?.detail,
+ onTap: startSent || _busy
+ ? null
+ : () => setState(() => _picking = _Pick.machine),
+ ),
+ ],
+ ),
+ if (_maybeMade)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ AppSpace.xs,
+ AppSpace.m,
+ AppSpace.xs,
+ 0,
+ ),
+ child: SwarmRow.line(
+ swarmNewProjectMaybeMade,
+ key: const ValueKey('swarm-new-project-maybe-made'),
+ lines: 3,
+ ),
+ ),
+ // Why it stopped, under what it is about; scrolled into sight when
+ // it appears (_showError).
+ if (_error case final error?)
+ Padding(
+ key: _errorKey,
+ padding: const EdgeInsets.fromLTRB(
+ AppSpace.xs,
+ AppSpace.m,
+ AppSpace.xs,
+ 0,
+ ),
+ child: SwarmRow.line(
+ error,
+ key: const ValueKey('swarm-new-project-error'),
+ lines: 4,
+ color: AppColors.danger,
+ ),
+ )
+ else if (blocked case final why?)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ AppSpace.xs,
+ AppSpace.m,
+ AppSpace.xs,
+ 0,
+ ),
+ child: SwarmRow.line(
+ why,
+ key: const ValueKey('swarm-new-project-note'),
+ lines: 3,
+ ),
+ ),
+ ],
+ // Create in sight however short the phone, the keyboard up too.
+ footer: [
+ const SizedBox(height: AppSpace.l),
+ SwarmButton(
+ key: const ValueKey('swarm-new-project-create'),
+ label: _error == null ? 'Create' : 'Try again',
+ style: SwarmButtonStyle.fill,
+ wide: true,
+ busy: _busy,
+ busyLabel: 'Creating…',
+ onPressed:
+ blocked == null &&
+ repository != null &&
+ machineId != null &&
+ (machine != null || startSent)
+ ? () => unawaited(_create(swarmId, reader, repository, machineId))
+ : null,
+ ),
+ // Steps left that nothing runs: the way out of them, whatever stops
+ // them (Lead's re-review).
+ if (steps != null && steps.sent && steps.running == null && !_busy) ...[
+ const SizedBox(height: AppSpace.s),
+ SwarmButton(
+ key: const ValueKey('swarm-new-project-start-over'),
+ label: 'Start over',
+ style: SwarmButtonStyle.link,
+ wide: true,
+ onPressed: _startOver,
+ ),
+ ],
+ ],
+ );
+ }
+
+ /// Lets the Swarm's steps go: the fields open again, and the next Create
+ /// makes a new project. One already made stays in the list; one whose
+ /// create was never answered may be there too, and the sheet says so.
+ void _startOver() {
+ if (_busy) return;
+ setState(() {
+ _maybeMade = _steps?.createUnanswered ?? false;
+ _steps?.forget();
+ _error = null;
+ });
+ }
+
+ /// Why Create cannot be pressed now, or null (Desktop's `leadBlocked`).
+ String? _blocked(
+ SuperTabSnapshot snapshot,
+ List<SwarmLeadMachine> machines,
+ SwarmLeadMachine? machine,
+ String? repository,
+ ) {
+ if (snapshot.paused) {
+ return '$swarmLeadSwarmPaused. New project can start once it resumes.';
+ }
+ if (repository == null) {
+ return 'Choose the repository this project works in.';
+ }
+ // A start sent is repeated as it was, or is done, whatever the list
+ // says now: the Product Manager it started may fill its machine.
+ if (_steps?.startSent ?? false) return null;
+ if (!machines.any((m) => m.startable)) return swarmLeadNoMachine;
+ if (machine == null) return swarmLeadChooseMachine;
+ if (!machine.startable) {
+ return '${machine.name} cannot start the Product Manager. '
+ 'Choose another machine.';
+ }
+ return null;
+ }
+
+ Future<void> _create(
+ String swarmId,
+ SwarmReader reader,
+ String repository,
+ String machineId,
+ ) async {
+ if (_busy) return;
+ // Held by the Swarm's reader: a sheet opened again resumes them.
+ final steps = SwarmNewProjectSteps.of(reader)
+ ..chosenMachine = machineId
+ ..chosenRepository = repository
+ ..failure = null;
+ setState(() {
+ _busy = true;
+ _error = null;
+ _maybeMade = false;
+ });
+ try {
+ final projectId = await steps.run(
+ brief: _brief.text,
+ visibility: _visibility,
+ machineId: machineId,
+ repositoryUrl: repository,
+ live: () => _live(swarmId, reader),
+ machinesOf: (snapshot) => _machinesOf(swarmId, snapshot),
+ );
+ if (!mounted || !_live(swarmId, reader)) return;
+ _closing = true;
+ Navigator.of(context).pop((swarmId: swarmId, projectId: projectId));
+ } on SwarmNewProjectGone {
+ // The sheet goes by itself: its Swarm, access or account went.
+ } on SuperTabFailure catch (failure) {
+ _fail(swarmId, reader, steps, failure.message);
+ } catch (_) {
+ _fail(swarmId, reader, steps, 'The Swarm didn’t answer. Try again.');
+ } finally {
+ if (mounted && !_closing) setState(() => _busy = false);
+ }
+ }
+
+ /// Says why the last Create stopped; once the project exists, that it
+ /// stays, as Desktop leaves it in the list. Kept with [steps], for a sheet
+ /// that opens on them again.
+ void _fail(
+ String swarmId,
+ SwarmReader reader,
+ SwarmNewProjectSteps steps,
+ String why,
+ ) {
+ final error = steps.projectId == null
+ ? 'Couldn’t create the project: $why'
+ // Its project deleted meanwhile, the steps were let go: the next
+ // Create starts afresh.
+ : !identical(SwarmNewProjectSteps.heldBy(reader), steps)
+ ? why
+ : steps.started
+ ? 'The project is made and its Product Manager is starting. '
+ 'Naming it didn’t finish: $why'
+ : 'The project is made. Its Product Manager didn’t start: $why';
+ steps.failure = error;
+ if (!_live(swarmId, reader)) return;
+ setState(() => _error = error);
+ _showError();
+ }
+
+ Widget _pick(
+ BuildContext context,
+ _Pick pick,
+ List<String> writable,
+ String swarmId,
+ SwarmReader reader,
+ SuperTabSnapshot snapshot,
+ ) {
+ void back() => setState(() {
+ _picking = pick == _Pick.link ? _Pick.repository : null;
+ _linkError = null;
+ });
+ final header = _header(
+ switch (pick) {
+ _Pick.swarm => 'Swarm',
+ _Pick.visibility => 'Visibility',
+ _Pick.repository => 'Repository',
+ _Pick.link => 'Enter a link',
+ _Pick.machine => 'PM runs on',
+ },
+ SwarmIconButton(
+ key: const ValueKey('swarm-new-project-back'),
+ icon: LucideIcons.chevronLeft300,
+ size: 24,
+ label: 'Back',
+ onPressed: back,
+ ),
+ );
+ Widget tick() =>
+ Icon(LucideIcons.check300, size: 20, color: AppPalette.swarmAccent);
+ switch (pick) {
+ case _Pick.swarm:
+ return _frame(
+ header: header,
+ children: [
+ SwarmGroup(
+ children: [
+ for (final id in writable)
+ _Option(
+ key: ValueKey('swarm-new-project-pick-swarm-$id'),
+ leading: SwarmProjectTile(_swarmName(id)),
+ title: _swarmName(id),
+ trailing: id == swarmId ? tick() : null,
+ onTap: () => setState(() {
+ _picking = null;
+ if (id == _swarmId) return;
+ // Another Swarm: its own repositories and machines.
+ _dropUnsent();
+ _swarmId = id;
+ _error = null;
+ _maybeMade = false;
+ _repository = null;
+ _repositoryPicked = false;
+ _machineId = null;
+ _modelList = const {};
+ _policySwarm = null;
+ unawaited(_readModelList(id));
+ }),
+ ),
+ ],
+ ),
+ ],
+ );
+ case _Pick.visibility:
+ return _frame(
+ header: header,
+ children: [
+ SwarmGroup(
+ children: [
+ for (final (id, title, line, icon) in [
+ (
+ 'public',
+ 'Public',
+ 'Everyone in this Swarm',
+ LucideIcons.users300,
+ ),
+ (
+ 'private',
+ 'Private',
+ 'Only people you invite to this project',
+ LucideIcons.lock300,
+ ),
+ ])
+ _Option(
+ key: ValueKey('swarm-new-project-pick-visibility-$id'),
+ leading: Icon(
+ icon,
+ size: 20,
+ color: AppPalette.textSecondary,
+ ),
+ title: title,
+ detail: line,
+ trailing: id == _visibility ? tick() : null,
+ onTap: () => setState(() {
+ _visibility = id;
+ _picking = null;
+ }),
+ ),
+ ],
+ ),
+ ],
+ );
+ case _Pick.repository:
+ final repositories = swarmProjectRepositories(reader);
+ final chosen = _repositoryPicked
+ ? _repository
+ : repositories.firstOrNull;
+ return _frame(
+ header: header,
+ children: [
+ SwarmGroup(
+ children: [
+ for (final url in {...repositories, ?chosen})
+ _Option(
+ key: ValueKey('swarm-new-project-pick-repo-$url'),
+ leading: Icon(
+ LucideIcons.gitBranch300,
+ size: 20,
+ color: AppPalette.textSecondary,
+ ),
+ title: swarmRepositoryName(url),
+ detail: swarmRepositoryKey(url),
+ trailing: url == chosen ? tick() : null,
+ onTap: () => setState(() {
+ _repository = url;
+ _repositoryPicked = true;
+ _picking = null;
+ }),
+ ),
+ _Option(
+ key: const ValueKey('swarm-new-project-pick-link'),
+ leading: Icon(
+ LucideIcons.link300,
+ size: 20,
+ color: AppPalette.textSecondary,
+ ),
+ title: 'Enter a link',
+ onTap: () => setState(() {
+ _picking = _Pick.link;
+ _linkError = null;
+ }),
+ ),
+ ],
+ ),
+ ],
+ );
+ case _Pick.link:
+ void use() {
+ final link = swarmRepositoryLink(_link.text);
+ setState(() {
+ if (link == null) {
+ _linkError =
+ 'Enter a repository link without a password, such as '
+ 'https://github.com/owner/name.';
+ return;
+ }
+ _repository = link;
+ _repositoryPicked = true;
+ _linkError = null;
+ _picking = null;
+ });
+ }
+ return _frame(
+ header: header,
+ children: [
+ TextField(
+ key: const ValueKey('swarm-new-project-link'),
+ controller: _link,
+ autofocus: true,
+ autocorrect: false,
+ enableSuggestions: false,
+ keyboardType: TextInputType.url,
+ textInputAction: TextInputAction.done,
+ onSubmitted: (_) => use(),
+ style: AppType.body(color: AppPalette.textPrimary),
+ decoration: InputDecoration(
+ hintText: 'https://github.com/owner/name',
+ hintStyle: TextStyle(color: AppPalette.textFaint),
+ filled: true,
+ fillColor: AppPalette.swarmField,
+ border: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(AppControl.radius),
+ borderSide: BorderSide.none,
+ ),
+ ),
+ ),
+ if (_linkError case final error?)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ AppSpace.xs,
+ AppSpace.s,
+ AppSpace.xs,
+ 0,
+ ),
+ child: SwarmRow.line(
+ error,
+ key: const ValueKey('swarm-new-project-link-error'),
+ lines: 3,
+ color: AppColors.danger,
+ ),
+ ),
+ ],
+ footer: [
+ const SizedBox(height: AppSpace.l),
+ SwarmButton(
+ key: const ValueKey('swarm-new-project-link-use'),
+ label: 'Use this link',
+ style: SwarmButtonStyle.fill,
+ wide: true,
+ onPressed: use,
+ ),
+ ],
+ );
+ case _Pick.machine:
+ final machines = _machinesOf(swarmId, snapshot);
+ final startable = machines.where((m) => m.startable).toList();
+ return _frame(
+ header: header,
+ children: [
+ if (startable.isEmpty)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ AppSpace.xs,
+ 0,
+ AppSpace.xs,
+ AppSpace.s,
+ ),
+ child: SwarmRow.line(
+ snapshot.paused
+ ? '$swarmLeadSwarmPaused.'
+ : machines.isEmpty
+ ? 'This Swarm has no machines yet. Add one from '
+ 'Harness on a computer.'
+ : swarmLeadNoMachine,
+ key: const ValueKey('swarm-new-project-no-machine'),
+ lines: 3,
+ ),
+ ),
+ if (machines.isNotEmpty)
+ SwarmGroup(
+ children: [
+ // Only those that can take it; when none can, each says
+ // why it cannot.
+ for (final m in startable.isEmpty ? machines : startable)
+ _Option(
+ key: ValueKey('swarm-new-project-pick-machine-${m.id}'),
+ leading: Icon(
+ m.maySleep
+ ? LucideIcons.laptop300
+ : LucideIcons.monitor300,
+ size: 20,
+ color: AppPalette.textSecondary,
+ ),
+ title: m.name,
+ detail: m.detail,
+ trailing: m.id == _machineId ? tick() : null,
+ onTap: m.startable
+ ? () => setState(() {
+ _machineId = m.id;
+ _picking = null;
+ _error = null;
+ })
+ : null,
+ ),
+ ],
+ ),
+ ],
+ );
+ }
+ }
+
+ String _swarmName(String id) =>
+ _inbox.swarms.where((s) => s.id == id).firstOrNull?.name ??
+ _inbox.reader(id)?.snapshot?.name ??
+ 'Swarm';
+}
+
+/// One of the sheet's choices: its [label] at its left, what is chosen at
+/// its right with a chevron, and maybe a line under it. Fixed ([onTap] null)
+/// once what it chose was sent.
+class _Field extends StatelessWidget {
+ const _Field({
+ super.key,
+ required this.label,
+ required this.value,
+ this.detail,
+ required this.onTap,
+ });
+
+ final String label, value;
+ final String? detail;
+ final VoidCallback? onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final enabled = onTap != null;
+ return Semantics(
+ button: true,
+ enabled: enabled,
+ label: '$label: $value',
+ excludeSemantics: true,
+ child: Material(
+ color: Colors.transparent,
+ child: InkWell(
+ onTap: onTap,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(minHeight: SwarmRow.height),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: AppSpace.l,
+ vertical: AppSpace.m,
+ ),
+ child: Row(
+ children: [
+ Text(
+ label,
+ style: AppType.label(color: AppPalette.textSecondary),
+ ),
+ const SizedBox(width: AppSpace.m),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.end,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ value,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ textAlign: TextAlign.end,
+ style: AppType.label(
+ color: enabled
+ ? AppPalette.textPrimary
+ : AppPalette.textSecondary,
+ height: 1.3,
+ ),
+ ),
+ if (detail case final detail?) ...[
+ const SizedBox(height: 3),
+ Text(
+ detail,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ textAlign: TextAlign.end,
+ style: AppType.caption(
+ color: AppPalette.textSecondary,
+ height: 1.35,
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ if (enabled) ...[
+ const SizedBox(width: AppSpace.s),
+ Icon(
+ LucideIcons.chevronDown300,
+ size: 18,
+ color: AppPalette.textFaint,
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// One choice in one of the sheet's lists: dimmed, and not tappable, when it
+/// cannot be chosen ([onTap] null), its line saying why.
+class _Option extends StatelessWidget {
+ const _Option({
+ super.key,
+ this.leading,
+ required this.title,
+ this.detail,
+ this.trailing,
+ required this.onTap,
+ });
+
+ final Widget? leading;
+ final String title;
+ final String? detail;
+ final Widget? trailing;
+ final VoidCallback? onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final enabled = onTap != null;
+ return Semantics(
+ button: true,
+ enabled: enabled,
+ selected: trailing != null,
+ child: Material(
+ color: Colors.transparent,
+ child: InkWell(
+ onTap: onTap,
+ child: Opacity(
+ opacity: enabled ? 1 : .55,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(minHeight: SwarmRow.height),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: AppSpace.l,
+ vertical: AppSpace.m,
+ ),
+ child: Row(
+ children: [
+ if (leading case final leading?) ...[
+ leading,
+ const SizedBox(width: AppSpace.m),
+ ],
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ title,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppType.label(
+ color: AppPalette.textPrimary,
+ height: 1.3,
+ ),
+ ),
+ if (detail case final detail?) ...[
+ const SizedBox(height: 3),
+ SwarmRow.line(detail, lines: 3),
+ ],
+ ],
+ ),
+ ),
+ if (trailing case final trailing?) ...[
+ const SizedBox(width: AppSpace.m),
+ trailing,
+ ],
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// Keeps a field to [max] runes, cutting a paste rather than refusing it,
+/// and never between the two halves of one.
+class _RuneLimit extends TextInputFormatter {
+ const _RuneLimit(this.max);
+
+ final int max;
+
+ @override
+ TextEditingValue formatEditUpdate(
+ TextEditingValue oldValue,
+ TextEditingValue newValue,
+ ) {
+ if (newValue.text.runes.length <= max) return newValue;
+ final text = String.fromCharCodes(newValue.text.runes.take(max));
+ return TextEditingValue(
+ text: text,
+ selection: TextSelection.collapsed(
+ offset: math.min(newValue.selection.extentOffset, text.length),
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/swarm/swarm_page.dart b/mobile/lib/swarm/swarm_page.dart
index bddc8156c..88a3974ed 100644
--- a/mobile/lib/swarm/swarm_page.dart
+++ b/mobile/lib/swarm/swarm_page.dart
@@ -21,6 +21,7 @@ import 'swarm_inbox.dart';
import 'swarm_jump_page.dart';
import 'swarm_needs_page.dart';
import 'swarm_new_message_sheet.dart';
+import 'swarm_new_project_sheet.dart';
import 'swarm_project_page.dart';
import 'swarm_reader.dart';
import 'swarm_row.dart';
@@ -478,12 +479,22 @@ class _SwarmPageState extends State<SwarmPage> {
);
final quiet = lists.quiet;
final empty = projects.isEmpty && reading.isEmpty && failed.isEmpty;
+ // Last, for someone who may write in a Swarm shown: never a viewer.
+ final create = shown.any((swarm) => swarmMayCreateProject(inbox, swarm.id))
+ ? SwarmNewProjectRow(
+ key: const ValueKey('swarm-new-project'),
+ onTap: () => unawaited(_newProject(session, shown)),
+ )
+ : null;
return [
if (lists.pinned.isNotEmpty) ...[
const SwarmCaption('Pinned'),
SwarmGroup(children: [for (final p in lists.pinned) row(p)]),
],
- if (lists.recent.isNotEmpty || quiet.isNotEmpty || empty) ...[
+ if (lists.recent.isNotEmpty ||
+ quiet.isNotEmpty ||
+ empty ||
+ create != null) ...[
const SwarmCaption('Projects'),
SwarmGroup(
children: [
@@ -499,6 +510,7 @@ class _SwarmPageState extends State<SwarmPage> {
if (_quietOpen)
for (final p in quiet) row(p),
],
+ ?create,
],
),
] else if (reading.isNotEmpty || failed.isNotEmpty)
@@ -523,6 +535,24 @@ class _SwarmPageState extends State<SwarmPage> {
];
}
+ /// + New project: its sheet over Home, for the Swarms [shown]; the project
+ /// it made opens, unless Home or the account changed meanwhile, or the
+ /// project is no longer Home's to list.
+ Future<void> _newProject(
+ SwarmSession session,
+ List<SwarmListing> shown,
+ ) async {
+ final made = await showSwarmNewProjectSheet(
+ context,
+ session: session,
+ swarmIds: [for (final swarm in shown) swarm.id],
+ now: widget.now,
+ );
+ if (made == null || !mounted || _session != session) return;
+ if (!swarmHomeListed(session.inbox, made.swarmId, made.projectId)) return;
+ _openProject(context, made.swarmId, made.projectId);
+ }
+
/// A long press on a project: Pin to top, or Unpin. The project taken away
/// meanwhile — its Swarm or itself — closes the sheet, and pins nothing.
Future<void> _pin(
diff --git a/mobile/test/swarm/swarm_new_project_fixture.dart b/mobile/test/swarm/swarm_new_project_fixture.dart
new file mode 100644
index 000000000..a8b8024cd
--- /dev/null
+++ b/mobile/test/swarm/swarm_new_project_fixture.dart
@@ -0,0 +1,262 @@
+import 'dart:async';
+
+import 'package:harness_mobile/swarm/model.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+
+import 'swarm_fixture.dart';
+
+/// New project's Swarms as a test scripts them: their machines, projects and
+/// commands (swarm_new_project_test.dart, swarm_new_project_shots_test.dart).
+
+/// Half an hour after the fixture's parts last changed, as Home reads it: no
+/// project is quiet. Every machine reading here is measured from it.
+final newProjectNow = DateTime.fromMillisecondsSinceEpoch(
+ 0,
+ isUtc: true,
+).add(const Duration(minutes: 30, seconds: 1));
+
+/// A reading [ago] before [newProjectNow], in epoch milliseconds.
+int _at(Duration ago) => newProjectNow.subtract(ago).millisecondsSinceEpoch;
+
+const harnessRepo = 'https://github.com/autonomous-ai/openharness';
+const lampRepo = 'https://github.com/autonomous-ai/lampos';
+
+/// A machine of the Swarm as the backend reads it, with its derived values
+/// over it: [contributor]'s, reporting [ago], offering [engines], its Harness
+/// able to start a Product Manager unless not [capable], [slots] agents free,
+/// added for every project ([scope] `swarm`) unless [scope] says otherwise.
+Map<String, dynamic> leadPool(
+ String id, {
+ String? name,
+ String contributor = me,
+ List<String> engines = const ['claude', 'codex'],
+ bool capable = true,
+ int slots = 2,
+ Duration ago = const Duration(seconds: 5),
+ Map<String, dynamic>? lead,
+ List<Map<String, dynamic>> readiness = const [],
+ List<Map<String, dynamic>> quotas = const [],
+ String deviceType = 'Mac Studio',
+ bool paused = false,
+ Map<String, String>? suspended,
+ String? scope = 'swarm',
+}) => {
+ 'machineId': id,
+ 'name': name ?? '$id.local',
+ 'contributorId': contributor,
+ 'scope': ?scope,
+ 'engines': engines,
+ 'maxAgents': 4,
+ 'cwd': '/Users/someone/swarm',
+ 'paused': ?(paused ? true : null),
+ 'observation': {
+ 'receivedAt': _at(ago),
+ 'capabilities': [if (capable) 'leadStart'],
+ 'readiness': {'engines': readiness},
+ 'quotas': quotas,
+ 'resources': {'deviceType': deviceType},
+ },
+ 'availableSlots': slots,
+ 'teamWork': {'allowed': true},
+ 'lead': ?lead,
+ 'suspendedEngines': ?suspended,
+};
+
+/// A project of the Swarm, its repository [repo].
+Map<String, dynamic> swarmProject(
+ String id,
+ String name, {
+ String? repo,
+ String visibility = 'public',
+}) => {
+ 'id': id,
+ 'name': name,
+ 'ownerId': me,
+ 'leadConversationId': id == project ? leadChat : 'lead-$id',
+ 'visibility': visibility,
+ 'members': <Object>[],
+ 'updateMinutes': 5,
+ if (repo != null)
+ 'repository': {
+ 'machineId': 'mac-1',
+ 'cwd': '/Users/someone/swarm/$name',
+ 'repositoryUrl': repo,
+ },
+};
+
+/// A snapshot of one Swarm with [machines], read by [me].
+SuperTabSnapshot leadSnapshot(
+ List<Map<String, dynamic>> machines, {
+ bool paused = false,
+ List<Map<String, dynamic>> people = const [],
+}) => SuperTabSnapshot.fromJson({
+ 'version': 1,
+ 'id': tab,
+ 'name': 'Phone Swarm',
+ 'ownerId': me,
+ 'paused': paused,
+ 'projects': [swarmProject(project, 'Mobile', repo: harnessRepo)],
+ 'people': [person(me), ...people],
+ 'agents': <Object>[],
+ 'machines': machines,
+ 'conversations': <Object>[],
+ 'invitations': <Object>[],
+});
+
+/// One scripted Swarm the sheet creates projects in: its projects, its
+/// person's role, its machines, and what each command answers. A project made
+/// is in every read after it, with its chat.
+class NewProjectSwarm {
+ NewProjectSwarm({
+ this.id = tab,
+ this.name = 'Phone Swarm',
+ this.role = 'owner',
+ List<Map<String, dynamic>>? machines,
+ List<Map<String, dynamic>>? projects,
+ }) : machines = machines ?? [leadPool('mac-1', name: 'Studio.local')],
+ projects =
+ projects ??
+ [
+ swarmProject(project, 'Mobile', repo: harnessRepo),
+ swarmProject('project-2', 'Lamp', repo: lampRepo),
+ ];
+
+ final String id, name;
+ String role;
+ List<Map<String, dynamic>> machines;
+ final List<Map<String, dynamic>> projects;
+ Map<String, dynamic>? policy;
+
+ /// When each project's chat last changed, by project; else the earlier in
+ /// [projects], the more recent.
+ final activity = <String, int>{};
+
+ /// Its reads fail, as a Swarm that does not answer.
+ bool unreadable = false;
+
+ /// The person's access to it is taken away: every read is refused.
+ bool revoked = false;
+
+ static Never _refused() => throw const SuperTabFailure(
+ 'FORBIDDEN',
+ 'You no longer have access to this Swarm.',
+ statusCode: 403,
+ );
+
+ /// Answers a command in place of the Swarm when it returns non-null:
+ /// throws to refuse it, or a future to hold its answer.
+ FutureOr<Object?>? Function(Map<String, dynamic> command)? answer;
+
+ /// Every command body sent, with its operation id.
+ final sent = <Map<String, dynamic>>[];
+
+ List<Map<String, dynamic>> commands(String type) => [
+ for (final body in sent)
+ if ((body['command'] as Map)['type'] == type) body,
+ ];
+
+ Map<String, dynamic> _load() {
+ if (revoked) _refused();
+ if (unreadable) {
+ throw const SuperTabFailure(
+ 'SERVER_ERROR',
+ 'Could not read this Swarm.',
+ statusCode: 503,
+ );
+ }
+ return {
+ ...firstLoad(
+ tabId: id,
+ head: headData(id: id, name: name, projects: projects),
+ machines: machines,
+ ),
+ 'members': [part(me, 1, person(me, role: role))],
+ // Each project's chat, its Product Manager's in Mobile.
+ 'groups': [
+ for (final (i, p) in projects.indexed)
+ {
+ ...part(p['leadConversationId'] as String, 1, {
+ ...groupData(
+ p['leadConversationId'] as String,
+ title: p['name'] as String,
+ agentIds: [if (p['id'] == project) 'agent-lead'],
+ leadId: p['id'] == project ? 'agent-lead' : null,
+ ),
+ 'projectId': p['id'],
+ }),
+ 'changedAt': activity[p['id']] ?? 1000 - i,
+ },
+ ],
+ };
+ }
+
+ void install(FakeSwarm fake) {
+ fake.routes['/api/super-tabs/$id/parts'] = (_) => _load();
+ // Every change read loads afresh: what changed is all here.
+ fake.routes['/api/super-tabs/$id/changes'] = (_) =>
+ revoked ? _refused() : {'reload': true};
+ fake.routes['/api/super-tabs/$id/routing-policy'] = (_) => {
+ 'policy': policy,
+ };
+ fake.routes['/api/super-tabs/$id/decisions?state=open'] = (_) => {
+ 'decisions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$id/mentions?state=waiting'] = (_) => {
+ 'mentions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$id/conversations/'] = (_) => {
+ 'messages': <Object>[],
+ 'next': null,
+ };
+ fake.routes['/api/super-tabs/$id/commands'] = (body) async {
+ sent.add(body!);
+ final command = body['command'] as Map<String, dynamic>;
+ if (answer?.call(command) case final answered?) {
+ final value = await answered;
+ if (value != null) return value;
+ }
+ final operation = body['operationId'] as String;
+ switch (command['type']) {
+ case 'project.create':
+ final made = 'p-$operation';
+ if (!projects.any((p) => p['id'] == made)) {
+ projects.add({
+ ...swarmProject(made, command['name'] as String),
+ 'leadConversationId': 'project-$made',
+ 'visibility': command['visibility'],
+ });
+ }
+ return {
+ 'result': {'projectId': made, 'conversationId': 'project-$made'},
+ };
+ case 'project.rename':
+ final named = projects.firstWhere(
+ (p) => p['id'] == command['projectId'],
+ );
+ named['name'] = command['name'];
+ return {'result': <String, dynamic>{}};
+ case 'lead.start':
+ return {
+ 'result': {'startId': operation, 'machineId': command['machineId']},
+ };
+ default:
+ return {'result': <String, dynamic>{}};
+ }
+ };
+ }
+}
+
+/// The backend of [swarms], listed in order.
+FakeSwarm newProjectBackend(List<NewProjectSwarm> swarms) {
+ final fake = FakeSwarm();
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ for (final s in swarms) {'id': s.id, 'name': s.name, 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ for (final s in swarms) {
+ s.install(fake);
+ }
+ return fake;
+}
diff --git a/mobile/test/swarm/swarm_new_project_shots_test.dart b/mobile/test/swarm/swarm_new_project_shots_test.dart
new file mode 100644
index 000000000..207b19f2c
--- /dev/null
+++ b/mobile/test/swarm/swarm_new_project_shots_test.dart
@@ -0,0 +1,297 @@
+import 'dart:convert';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/cupertino.dart' show CupertinoPageRoute;
+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_page.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+import 'swarm_new_project_fixture.dart';
+
+/// Review screenshots of + New project: Home's row, the sheet filled in, PM
+/// runs on, the brief written with the keyboard up, a long error (with the
+/// keyboard up too), a Product Manager that did not start, and no machine able to run
+/// one. On a 390-point and a 320-point phone in both phone themes, from
+/// made-up data only, to the folder `SWARM_NEW_PROJECT_SHOTS` names. The
+/// keyboard is a drawn box of an iPhone keyboard's height, labelled so.
+final shots = Platform.environment['SWARM_NEW_PROJECT_SHOTS'];
+void main() {
+ setUpAll(() async {
+ if (shots == null || !Platform.isMacOS) return;
+ final sf = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFont', 'Roboto']) {
+ await (FontLoader(family)..addFont(Future.value(sf))).load();
+ }
+ final mono = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFontMonospaced', 'monospace']) {
+ await (FontLoader(family)..addFont(Future.value(mono))).load();
+ }
+ final manifest =
+ jsonDecode(await rootBundle.loadString('FontManifest.json')) as List;
+ for (final entry in manifest.cast<Map<String, dynamic>>()) {
+ final loader = FontLoader(entry['family'] as String);
+ for (final font in (entry['fonts'] as List).cast<Map>()) {
+ loader.addFont(rootBundle.load(font['asset'] as String));
+ }
+ await loader.load();
+ }
+ });
+
+ testWidgets('+ New project on a 390 and a 320 point phone, in both phone '
+ 'themes', (tester) async {
+ for (final (width, height, top, bottom, keys) in [
+ (390.0, 844.0, 47.0, 34.0, 336.0),
+ (320.0, 568.0, 20.0, 0.0, 260.0),
+ ]) {
+ // The phone's screen, as the sheet measures its height by it.
+ await tester.binding.setSurfaceSize(Size(width, height));
+ tester.view.physicalSize = Size(width * 3, height * 3);
+ tester.view.devicePixelRatio = 3;
+ // An iPhone's status bar and home indicator.
+ tester.view.padding = FakeViewPadding(top: top * 3, bottom: bottom * 3);
+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {
+ final brightness = palette.brightness;
+ AppTheme.palette.value = palette;
+ AppTheme.brightness.value = brightness;
+ final swarm = NewProjectSwarm(
+ machines: [
+ leadPool('mac-studio', name: 'Studio.local', slots: 3),
+ leadPool(
+ 'mac-air',
+ name: 'Air.local',
+ slots: 1,
+ deviceType: 'MacBook Air',
+ ),
+ leadPool(
+ 'mac-ken',
+ name: 'Ken’s Mac mini',
+ contributor: 'person-ken',
+ lead: {
+ 'claude': {'machineId': 'team-ken'},
+ 'codex': {'machineId': 'team-ken'},
+ },
+ ),
+ ],
+ );
+ final features = ExperimentalFeaturesStore(
+ storage: MemoryKeyValueStore(),
+ )..value = {PhoneExperiment.swarm};
+ final account = ValueNotifier<String?>(me);
+ final host = SwarmHost(
+ accountId: () => me,
+ account: account,
+ request: newProjectBackend([swarm]).request,
+ notices: SilentSystemNotices(),
+ features: features,
+ readMarks: MemoryKeyValueStore(),
+ )..foreground = false;
+ final boundary = GlobalKey();
+ final keyboard = ValueNotifier<double>(0);
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: Directionality(
+ textDirection: TextDirection.ltr,
+ child: Stack(
+ children: [
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: buildAppTheme(brightness: brightness),
+ builder: (_, child) =>
+ SwarmScope(notifier: host, child: child!),
+ onGenerateRoute: (_) => CupertinoPageRoute<void>(
+ builder: (_) => SwarmPage(now: () => newProjectNow),
+ ),
+ ),
+ // Where the keyboard is, while it is up.
+ ValueListenableBuilder(
+ valueListenable: keyboard,
+ builder: (_, height, _) => height == 0
+ ? const SizedBox.shrink()
+ : Positioned(
+ left: 0,
+ right: 0,
+ bottom: 0,
+ height: height,
+ child: ColoredBox(
+ color: brightness == Brightness.dark
+ ? const Color(0xFF2C2C2E)
+ : const Color(0xFFD1D3D9),
+ child: Center(
+ child: Text(
+ 'Keyboard',
+ style: TextStyle(
+ fontFamily: '.AppleSystemUIFont',
+ fontSize: 17,
+ color: brightness == Brightness.dark
+ ? const Color(0xFF8E8E93)
+ : const Color(0xFF6E6E73),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ Future<void> capture(String name) => tester.runAsync(() async {
+ final image =
+ await (boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 3);
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ await File(
+ '$shots/new-project-${width.toInt()}-$name-${brightness.name}.png',
+ ).writeAsBytes(png!.buffer.asUint8List());
+ image.dispose();
+ });
+ Finder key(String value) => find.byKey(ValueKey(value));
+ Future<void> tap(String k) async {
+ await tester.ensureVisible(key(k));
+ await tester.pumpAndSettle();
+ await tester.tap(key(k));
+ await tester.pumpAndSettle();
+ }
+
+ // Home: + New project, the last of Projects.
+ await tester.ensureVisible(key('swarm-new-project'));
+ await tester.pumpAndSettle();
+ await capture('home');
+
+ // The sheet, its brief written and its machine picked.
+ await tap('swarm-new-project');
+ await tester.enterText(
+ key('swarm-new-project-brief'),
+ 'Let people start a project from the phone, with its Product '
+ 'Manager on a Swarm machine.',
+ );
+ FocusManager.instance.primaryFocus?.unfocus();
+ await tester.pumpAndSettle();
+ await tap('swarm-new-project-machine');
+ await capture('machines');
+ await tap('swarm-new-project-pick-machine-mac-studio');
+ await capture('sheet');
+
+ // The keyboard up while the brief is written: it and Create stay in
+ // sight.
+ Future<void> raiseKeyboard() async {
+ await tester.showKeyboard(key('swarm-new-project-brief'));
+ tester.view.viewInsets = FakeViewPadding(bottom: keys * 3);
+ // Under the keyboard there is no home indicator to keep clear of.
+ tester.view.padding = FakeViewPadding(top: top * 3);
+ keyboard.value = keys;
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> lowerKeyboard() async {
+ FocusManager.instance.primaryFocus?.unfocus();
+ tester.view.resetViewInsets();
+ tester.view.padding = FakeViewPadding(
+ top: top * 3,
+ bottom: bottom * 3,
+ );
+ keyboard.value = 0;
+ await tester.pumpAndSettle();
+ }
+
+ await raiseKeyboard();
+ await capture('keyboard');
+ await lowerKeyboard();
+
+ // A create never answered, let go: a project may be there.
+ swarm.answer = (command) => command['type'] == 'project.create'
+ ? throw const SuperTabFailure('NETWORK', 'The Swarm didn’t answer.')
+ : null;
+ await tap('swarm-new-project-create');
+ await tap('swarm-new-project-start-over');
+ await capture('maybe-made');
+
+ // A create refused with a long reason, then the brief written again.
+ swarm.answer = (command) => command['type'] == 'project.create'
+ ? throw const SuperTabFailure(
+ 'PROJECT_LIMIT',
+ 'This Swarm has as many projects as its plan holds. Archive '
+ 'one you no longer need, or ask its owner to raise the '
+ 'limit, then try again.',
+ statusCode: 409,
+ )
+ : null;
+ await tap('swarm-new-project-create');
+ await capture('error');
+ await raiseKeyboard();
+ await capture('keyboard-error');
+ await lowerKeyboard();
+
+ // Its Product Manager refused: the project stays, and says why.
+ swarm.answer = (command) => command['type'] == 'lead.start'
+ ? throw const SuperTabFailure(
+ 'ENGINE_UNAVAILABLE',
+ 'Claude Code isn’t signed in on Studio.',
+ statusCode: 409,
+ )
+ : null;
+ await tap('swarm-new-project-create');
+ await capture('failed');
+ await tap('swarm-new-project-close');
+
+ // No machine can run it: each says why.
+ swarm.machines = [
+ leadPool(
+ 'mac-studio',
+ name: 'Studio.local',
+ ago: const Duration(minutes: 3),
+ ),
+ leadPool(
+ 'mac-air',
+ name: 'Air.local',
+ capable: false,
+ deviceType: 'MacBook Air',
+ ),
+ leadPool(
+ 'mac-ken',
+ name: 'Ken’s Mac mini',
+ contributor: 'person-ken',
+ lead: {
+ 'claude': {'refused': 'Claude Code isn’t signed in there.'},
+ 'codex': {'refused': 'Codex isn’t signed in there.'},
+ },
+ ),
+ ];
+ await host.session!.inbox.reader(tab)!.refresh();
+ await tester.pumpAndSettle();
+ await tap('swarm-new-project');
+ await tap('swarm-new-project-machine');
+ await capture('none');
+
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(seconds: 30));
+ host.dispose();
+ account.dispose();
+ keyboard.dispose();
+ }
+ }
+ await tester.binding.setSurfaceSize(null);
+ tester.view.reset();
+ AppTheme.palette.value = HarnessPalette.graphite;
+ AppTheme.brightness.value = Brightness.dark;
+ }, skip: shots == null);
+}
diff --git a/mobile/test/swarm/swarm_new_project_test.dart b/mobile/test/swarm/swarm_new_project_test.dart
new file mode 100644
index 000000000..f970baaf3
--- /dev/null
+++ b/mobile/test/swarm/swarm_new_project_test.dart
@@ -0,0 +1,1609 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:flutter/cupertino.dart' show CupertinoPageRoute;
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/swarm/swarm_new_project_sheet.dart';
+import 'package:harness_mobile/swarm/swarm_page.dart';
+import 'package:harness_mobile/swarm/swarm_reader.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+import 'swarm_new_project_fixture.dart';
+
+void main() {
+ group('swarmLeadMachines', () {
+ List<SwarmLeadMachine> machines(
+ List<Map<String, dynamic>> pools, {
+ bool paused = false,
+ Map<String, String> modelList = const {},
+ }) => swarmLeadMachines(
+ leadSnapshot(
+ pools,
+ paused: paused,
+ people: [person('person-ken', role: 'collaborator')],
+ ),
+ me,
+ now: newProjectNow,
+ modelList: modelList,
+ );
+
+ test('lists the person\'s own machine that can start a Product Manager '
+ 'with the first engine it runs, by its name without .local', () {
+ final [studio] = machines([leadPool('mac-1', name: 'Studio.local')]);
+ expect(studio.name, 'Studio');
+ expect(studio.startable, isTrue);
+ expect(studio.engine, 'claude');
+ expect(studio.detail, 'Claude Code · 2 agents free');
+ });
+
+ test('a machine of theirs whose Harness cannot start a Product Manager '
+ 'says to update it, as the start would refuse it', () {
+ final [old] = machines([leadPool('mac-1', capable: false)]);
+ expect(old.startable, isFalse);
+ expect(
+ old.detail,
+ 'Update Harness on mac-1 to run a Product Manager there.',
+ );
+ expect(
+ swarmLeadMachineRefusal([old], 'mac-1'),
+ 'mac-1: Update Harness on mac-1 to run a Product Manager there. '
+ 'Choose another machine.',
+ reason: 'one full stop',
+ );
+ });
+
+ test('a machine of theirs added for the Lead only cannot take it, and '
+ 'says why as the server would refuse it', () {
+ final [swarm, lead] = machines([
+ leadPool('mac-1', name: 'Studio', scope: null),
+ leadPool('mac-2', name: 'Mini'),
+ ]);
+ expect(swarm.id, 'mac-2', reason: 'the one that can comes first');
+ expect(swarm.startable, isTrue);
+ expect(lead.startable, isFalse);
+ expect(lead.detail, swarmLeadUnscoped);
+ expect(
+ swarmLeadMachineRefusal([lead], 'mac-1'),
+ 'Studio: Add this machine to the Swarm again to support other '
+ 'projects. Choose another machine.',
+ );
+ });
+
+ test('an engine not offered, not installed, signed out, out of quota or '
+ 'suspended is ruled out with why; one left runs', () {
+ final [codexOnly] = machines([
+ leadPool(
+ 'mac-1',
+ readiness: [
+ {'engine': 'claude', 'installed': true, 'signedIn': false},
+ ],
+ ),
+ ]);
+ expect(codexOnly.engine, 'codex');
+ expect(codexOnly.engineRefusals, {
+ 'claude': 'Claude Code isn’t signed in',
+ });
+
+ final [none] = machines([
+ leadPool(
+ 'mac-1',
+ engines: ['claude'],
+ quotas: [
+ {
+ 'engine': 'claude',
+ 'known': true,
+ 'windows': [
+ {'usedPercent': 100},
+ ],
+ },
+ ],
+ ),
+ ]);
+ expect(none.startable, isFalse);
+ expect(
+ none.detail,
+ 'Can’t run a Product Manager: Claude Code has no quota left until it '
+ 'resets, Codex isn’t offered here',
+ );
+
+ final [suspended] = machines([
+ leadPool(
+ 'mac-1',
+ engines: ['claude'],
+ suspended: {'claude': 'Claude Code failed to start twice'},
+ ),
+ ]);
+ expect(suspended.startable, isFalse);
+ expect(suspended.engineRefusals['claude'], contains('failed to start'));
+ });
+
+ test('the Swarm\'s model list rules an engine out on every machine', () {
+ final [studio] = machines(
+ [leadPool('mac-1')],
+ modelList: swarmLeadModelListRefusals({
+ 'models': [
+ {'engine': 'claude', 'model': 'opus', 'enabled': false},
+ {'engine': 'codex', 'model': 'gpt-5', 'enabled': true},
+ ],
+ }),
+ );
+ expect(studio.engine, 'codex');
+ expect(
+ studio.engineRefusals['claude'],
+ 'The Swarm’s model list has no enabled Claude model',
+ );
+ expect(swarmLeadModelListRefusals(null), isEmpty);
+ });
+
+ test('a teammate\'s machine runs it as the server decided for each '
+ 'engine, and says the server\'s reason when it cannot', () {
+ final [team, refused] = machines([
+ leadPool(
+ 'mac-ken',
+ name: 'Ken Mac',
+ contributor: 'person-ken',
+ lead: {
+ 'claude': {'refused': 'Claude Code isn’t signed in on Ken Mac.'},
+ 'codex': {'machineId': 'team-ken'},
+ },
+ ),
+ leadPool(
+ 'mac-dee',
+ name: 'Dee Mac',
+ contributor: 'person-ken',
+ lead: {
+ 'claude': {'refused': 'Paused in this Swarm.'},
+ 'codex': {'refused': 'Paused in this Swarm.'},
+ },
+ ),
+ ]);
+ expect(team.name, 'Ken Mac');
+ expect(team.engine, 'codex');
+ expect(team.inTeam('codex'), isTrue);
+ expect(team.own, isFalse);
+ expect(refused.startable, isFalse);
+ expect(
+ refused.detail,
+ 'Can’t run a Product Manager: Paused in this Swarm',
+ );
+ });
+
+ test('a paused Swarm, an offline machine and a full one cannot take it; '
+ 'the ones that can come first', () {
+ final listed = machines([
+ leadPool('full', slots: 0),
+ leadPool('off', ago: const Duration(minutes: 2)),
+ leadPool('ok', name: 'Zed'),
+ leadPool('laptop', name: 'Air', deviceType: 'MacBook Air'),
+ ]);
+ expect([for (final m in listed) m.id], ['ok', 'laptop', 'full', 'off']);
+ expect(listed[1].detail, 'Claude Code · 2 agents free · May sleep');
+ expect(listed[2].detail, 'Claude Code · No agents free');
+ expect(listed[3].detail, 'Offline');
+
+ final [paused] = machines([leadPool('mac-1')], paused: true);
+ expect(paused.unavailable, swarmLeadSwarmPaused);
+ expect(
+ swarmLeadMachineRefusal([paused], 'mac-1'),
+ 'mac-1: New work is paused in this Swarm. Choose another machine.',
+ );
+ expect(
+ swarmLeadMachineRefusal([paused], 'elsewhere'),
+ 'Choose one of this Swarm’s machines.',
+ );
+ });
+ });
+
+ group('repositories', () {
+ test('a link is taken as the server takes it', () {
+ for (final ok in [
+ 'https://github.com/owner/name',
+ 'http://git.example.com/a/b.git',
+ 'ssh://[email protected]/owner/name.git',
+ '[email protected]:owner/name.git',
+ 'git://example.com/a',
+ ]) {
+ expect(swarmRepositoryUrlValid(ok), isTrue, reason: ok);
+ }
+ for (final no in [
+ '',
+ 'owner/name',
+ 'https://user:[email protected]/a/b',
+ 'https://[email protected]/a/b',
+ 'ssh://[email protected]/a/b',
+ 'ftp://example.com/a',
+ 'https://github.com/a b',
+ 'file:///tmp/repo',
+ 'https://${'a' * 4100}.com/x',
+ ]) {
+ expect(swarmRepositoryUrlValid(no), isFalse, reason: no);
+ }
+ expect(
+ swarmRepositoryLink(' github.com/Owner/Name '),
+ 'https://github.com/Owner/Name',
+ );
+ expect(swarmRepositoryLink('not a link'), isNull);
+ });
+
+ test('a repository is named and keyed however its address is spelled', () {
+ expect(
+ swarmRepositoryName('[email protected]:a/openharness.git'),
+ 'openharness',
+ );
+ expect(
+ swarmRepositoryKey('https://github.com/A/B.git/'),
+ 'github.com/a/b',
+ );
+ expect(swarmRepositoryName('https://github.com/'), 'github.com');
+ });
+
+ test('the Swarm\'s repositories come once each, the most recently active '
+ 'project\'s first', () async {
+ final fake = FakeSwarm();
+ NewProjectSwarm(
+ projects: [
+ swarmProject(project, 'Mobile', repo: harnessRepo),
+ swarmProject('project-2', 'Lamp', repo: lampRepo),
+ swarmProject('project-3', 'Copy', repo: '$harnessRepo.git'),
+ swarmProject('project-4', 'None'),
+ swarmProject('project-5', 'Bad', repo: 'https://me:[email protected]/a'),
+ ],
+ )
+ ..activity['project-2'] = 2000
+ ..activity['project-5'] = 3000
+ ..install(fake);
+ final reader = SwarmReader(
+ tabId: tab,
+ accountId: me,
+ request: fake.request,
+ );
+ addTearDown(reader.dispose);
+ await reader.refresh();
+ // Lamp's chat moved last; Bad's link is not one the server takes.
+ expect(swarmProjectRepositories(reader), [lampRepo, harnessRepo]);
+ });
+ });
+
+ group('SwarmNewProjectSteps', () {
+ late FakeSwarm fake;
+ late NewProjectSwarm swarm;
+ late SwarmReader reader;
+
+ setUp(() async {
+ fake = FakeSwarm();
+ swarm = NewProjectSwarm()..install(fake);
+ reader = SwarmReader(tabId: tab, accountId: me, request: fake.request);
+ await reader.refresh();
+ });
+ tearDown(() => reader.dispose());
+
+ Future<String> run(
+ SwarmNewProjectSteps steps, {
+ String brief = 'Ship the phone flow',
+ String machineId = 'mac-1',
+ String repositoryUrl = harnessRepo,
+ bool Function()? live,
+ }) => steps.run(
+ brief: brief,
+ visibility: 'private',
+ machineId: machineId,
+ repositoryUrl: repositoryUrl,
+ live: live ?? () => true,
+ machinesOf: (snapshot) =>
+ swarmLeadMachines(snapshot, me, now: newProjectNow),
+ );
+
+ test('creates the project, posts its brief, starts its Product Manager '
+ 'on the machine picked, then names it after its repository', () async {
+ final steps = SwarmNewProjectSteps.of(reader);
+ final made = await run(steps);
+
+ expect(
+ [for (final b in swarm.sent) (b['command'] as Map)['type']],
+ ['project.create', 'message.send', 'lead.start', 'project.rename'],
+ );
+ final create = swarm.commands('project.create').single;
+ expect(create['command'], {
+ 'type': 'project.create',
+ 'name': 'New project',
+ 'visibility': 'private',
+ 'brief': 'Ship the phone flow',
+ });
+ expect(made, 'p-${create['operationId']}');
+ expect(swarm.commands('message.send').single['command'], {
+ 'type': 'message.send',
+ 'conversationId': 'project-$made',
+ 'text': 'Ship the phone flow',
+ 'replyTo': null,
+ 'recipientIds': <String>[],
+ });
+ expect(swarm.commands('lead.start').single['command'], {
+ 'type': 'lead.start',
+ 'projectId': made,
+ 'machineId': 'mac-1',
+ 'engine': 'claude',
+ 'repositoryUrl': harnessRepo,
+ });
+ final rename = swarm.commands('project.rename').single;
+ expect(rename['command'], {
+ 'type': 'project.rename',
+ 'projectId': made,
+ 'name': 'openharness',
+ });
+ expect(rename['operationId'], '${create['operationId']}-name');
+ expect(reader.snapshot!.projectById(made)?.name, 'openharness');
+ final ids = [for (final b in swarm.sent) b['operationId']];
+ expect(ids.toSet(), hasLength(4), reason: 'one operation per step');
+ });
+
+ test('the Swarm\'s reader holds its steps until they finish, and runs '
+ 'them one at a time', () async {
+ final steps = SwarmNewProjectSteps.of(reader);
+ expect(SwarmNewProjectSteps.of(reader), same(steps));
+ expect(SwarmNewProjectSteps.heldBy(reader), same(steps));
+ final held = Completer<Object?>();
+ swarm.answer = (command) =>
+ command['type'] == 'project.create' ? held.future : null;
+ final first = run(steps);
+ final second = run(steps);
+ await settle();
+ held.complete(null);
+ final made = await first;
+ expect(await second, made, reason: 'the second finds it done');
+ expect(swarm.commands('project.create'), hasLength(1));
+ expect(swarm.commands('lead.start'), hasLength(1));
+ expect(SwarmNewProjectSteps.heldBy(reader), isNull, reason: 'finished');
+ expect(SwarmNewProjectSteps.of(reader), isNot(same(steps)));
+ });
+
+ test('a project deleted before its start lets its steps go: nothing is '
+ 'started, and the next Create makes a new one', () async {
+ swarm.answer = (command) {
+ if (command['type'] == 'message.send') {
+ // Deleted from Desktop meanwhile.
+ swarm.projects.removeWhere((p) => p['name'] == 'New project');
+ }
+ return null;
+ };
+ final steps = SwarmNewProjectSteps.of(reader);
+ await expectLater(
+ run(steps),
+ throwsA(
+ isA<SuperTabFailure>().having((f) => f.code, 'code', 'PROJECT_GONE'),
+ ),
+ );
+ expect(swarm.commands('lead.start'), isEmpty);
+ expect(SwarmNewProjectSteps.heldBy(reader), isNull);
+
+ swarm.answer = null;
+ await run(SwarmNewProjectSteps.of(reader));
+ final creates = swarm.commands('project.create');
+ expect(creates, hasLength(2));
+ expect(creates[0]['operationId'], isNot(creates[1]['operationId']));
+ expect(swarm.commands('lead.start'), hasLength(1));
+ });
+
+ test('a project deleted before its brief posts: the next run finds it '
+ 'gone and lets its steps go, sending nothing more to it', () async {
+ swarm.answer = (command) {
+ if (command['type'] == 'message.send') {
+ swarm.projects.removeWhere((p) => p['name'] == 'New project');
+ throw const SuperTabFailure(
+ 'NOT_FOUND',
+ 'This chat no longer exists.',
+ statusCode: 404,
+ );
+ }
+ return null;
+ };
+ final steps = SwarmNewProjectSteps.of(reader);
+ await expectLater(
+ run(steps),
+ throwsA(
+ isA<SuperTabFailure>().having((f) => f.code, 'code', 'NOT_FOUND'),
+ ),
+ );
+ expect(SwarmNewProjectSteps.heldBy(reader), same(steps));
+
+ await expectLater(
+ run(steps),
+ throwsA(
+ isA<SuperTabFailure>().having((f) => f.code, 'code', 'PROJECT_GONE'),
+ ),
+ );
+ expect(SwarmNewProjectSteps.heldBy(reader), isNull);
+ expect(swarm.commands('message.send'), hasLength(1));
+
+ swarm.answer = null;
+ await run(SwarmNewProjectSteps.of(reader));
+ final creates = swarm.commands('project.create');
+ expect(creates, hasLength(2));
+ expect(creates[0]['operationId'], isNot(creates[1]['operationId']));
+ });
+
+ test('a read asked before the project was made does not count it as '
+ 'deleted: an absence is read once more', () async {
+ final parts = fake.routes['/api/super-tabs/$tab/parts']!;
+ final gate = Completer<void>();
+ fake.routes['/api/super-tabs/$tab/parts'] = (body) async {
+ // As the Swarm answered then: nothing made since is in it.
+ final before = jsonDecode(jsonEncode(await parts(body)));
+ await gate.future;
+ return before;
+ };
+ // A read on its way since before the project.
+ final stale = reader.refresh();
+ await settle();
+ fake.routes['/api/super-tabs/$tab/parts'] = parts;
+ var lose = true;
+ swarm.answer = (command) {
+ if (command['type'] == 'message.send' && lose) {
+ lose = false;
+ throw const SuperTabFailure('NETWORK', 'The Swarm didn’t answer.');
+ }
+ return null;
+ };
+ final steps = SwarmNewProjectSteps.of(reader);
+ await expectLater(run(steps), throwsA(isA<SuperTabFailure>()));
+ final made = steps.projectId!;
+
+ final again = run(steps);
+ await settle();
+ gate.complete();
+ await stale;
+ expect(await again, made);
+ expect(swarm.commands('project.create'), hasLength(1));
+ expect(swarm.commands('lead.start'), hasLength(1));
+ });
+
+ test('a name the Swarm refuses counts as done: the project opens by the '
+ 'name it has, and nothing is held', () async {
+ swarm.answer = (command) => command['type'] == 'project.rename'
+ ? throw const SuperTabFailure(
+ 'FORBIDDEN',
+ 'Only its owner can rename it.',
+ statusCode: 403,
+ )
+ : null;
+ final made = await run(SwarmNewProjectSteps.of(reader));
+ expect(reader.snapshot!.projectById(made)?.name, 'New project');
+ expect(swarm.commands('project.rename'), hasLength(1));
+ expect(SwarmNewProjectSteps.heldBy(reader), isNull);
+ });
+
+ test('a name refused because the project was deleted says so, and lets '
+ 'its steps go', () async {
+ swarm.answer = (command) {
+ if (command['type'] == 'project.rename') {
+ swarm.projects.removeWhere((p) => p['id'] == command['projectId']);
+ throw const SuperTabFailure(
+ 'PROJECT_NOT_FOUND',
+ 'No such project.',
+ statusCode: 404,
+ );
+ }
+ return null;
+ };
+ await expectLater(
+ run(SwarmNewProjectSteps.of(reader)),
+ throwsA(
+ isA<SuperTabFailure>().having((f) => f.code, 'code', 'PROJECT_GONE'),
+ ),
+ );
+ expect(SwarmNewProjectSteps.heldBy(reader), isNull);
+ });
+
+ test('no brief posts nothing in its chat', () async {
+ await run(SwarmNewProjectSteps.of(reader), brief: ' ');
+ expect(swarm.commands('message.send'), isEmpty);
+ expect(
+ (swarm.commands('project.create').single['command'] as Map)['brief'],
+ '',
+ );
+ });
+
+ test('a brief at the limit round-trips whole; a longer one is cut at a '
+ 'rune, never inside one, and fits what the server takes', () async {
+ const smile = '😀';
+ final atLimit = smile * swarmNewProjectBriefRunes;
+ await run(SwarmNewProjectSteps.of(reader), brief: atLimit);
+ final brief =
+ (swarm.commands('project.create').single['command'] as Map)['brief']
+ as String;
+ expect(brief, atLimit);
+ expect(brief.length, lessThanOrEqualTo(8000), reason: 'server max');
+ expect(
+ (swarm.commands('message.send').single['command'] as Map)['text'],
+ atLimit,
+ );
+
+ swarm.sent.clear();
+ await run(SwarmNewProjectSteps.of(reader), brief: '${atLimit}x$smile');
+ final cut =
+ (swarm.commands('project.create').single['command'] as Map)['brief']
+ as String;
+ expect(cut, atLimit);
+ expect(cut.runes.length, swarmNewProjectBriefRunes);
+ });
+
+ test('a create whose answer was lost is sent again under the same '
+ 'operation, so the Swarm makes one project', () async {
+ var lose = true;
+ swarm.answer = (command) {
+ if (command['type'] == 'project.create' && lose) {
+ lose = false;
+ throw const SuperTabFailure('NETWORK', 'The Swarm didn’t answer.');
+ }
+ return null;
+ };
+ final steps = SwarmNewProjectSteps.of(reader);
+ await expectLater(run(steps), throwsA(isA<SuperTabFailure>()));
+ expect(steps.sent, isTrue, reason: 'its fields stay as sent');
+ expect(steps.projectId, isNull);
+ expect(steps.createUnanswered, isTrue);
+ await run(steps);
+ expect(steps.createUnanswered, isFalse);
+
+ final creates = swarm.commands('project.create');
+ expect(creates, hasLength(2));
+ expect(creates[0]['operationId'], creates[1]['operationId']);
+ expect(creates[0]['command'], creates[1]['command']);
+ expect(
+ swarm.projects.where((p) => p['name'] == 'openharness'),
+ hasLength(1),
+ );
+ });
+
+ test('a create the Swarm refused is not one left unanswered', () async {
+ swarm.answer = (command) => command['type'] == 'project.create'
+ ? throw const SuperTabFailure(
+ 'FORBIDDEN',
+ 'You may not create projects here.',
+ statusCode: 403,
+ )
+ : null;
+ final steps = SwarmNewProjectSteps.of(reader);
+ await expectLater(run(steps), throwsA(isA<SuperTabFailure>()));
+ expect(steps.createUnanswered, isFalse);
+ });
+
+ test(
+ 'a refused start keeps the project; Create again starts it on '
+ 'another machine as a new request and makes no second project',
+ () async {
+ swarm.machines = [
+ leadPool('mac-1', name: 'Studio'),
+ leadPool('mac-2', name: 'Mini'),
+ ];
+ await reader.refresh();
+ var refuse = true;
+ swarm.answer = (command) {
+ if (command['type'] == 'lead.start' && refuse) {
+ refuse = false;
+ throw const SuperTabFailure(
+ 'HOST_OUTDATED',
+ 'Update Harness on Studio to run a Product Manager there.',
+ statusCode: 409,
+ );
+ }
+ return null;
+ };
+ final steps = SwarmNewProjectSteps.of(reader);
+ await expectLater(
+ run(steps),
+ throwsA(
+ isA<SuperTabFailure>().having(
+ (f) => f.code,
+ 'code',
+ 'HOST_OUTDATED',
+ ),
+ ),
+ );
+ expect(steps.projectId, isNotNull);
+ expect(steps.starting, isFalse, reason: 'a refusal drops the start');
+ expect(
+ reader.snapshot!.projectById(steps.projectId!),
+ isNotNull,
+ reason: 'the project stays, in the list',
+ );
+
+ await run(steps, machineId: 'mac-2');
+ expect(swarm.commands('project.create'), hasLength(1));
+ expect(swarm.commands('message.send'), hasLength(1));
+ final starts = swarm.commands('lead.start');
+ expect(starts, hasLength(2));
+ expect(
+ starts[0]['operationId'],
+ isNot(starts[1]['operationId']),
+ reason: 'a new request',
+ );
+ expect((starts[1]['command'] as Map)['machineId'], 'mac-2');
+ },
+ );
+
+ test('a start whose answer was lost is repeated as it was sent, on its '
+ 'machine, under its operation', () async {
+ var lose = true;
+ swarm.answer = (command) {
+ if (command['type'] == 'lead.start' && lose) {
+ lose = false;
+ throw const SuperTabFailure(
+ 'SERVER_ERROR',
+ 'Try again.',
+ statusCode: 502,
+ );
+ }
+ return null;
+ };
+ final steps = SwarmNewProjectSteps.of(reader);
+ await expectLater(run(steps), throwsA(isA<SuperTabFailure>()));
+ expect(steps.starting, isTrue);
+ expect(steps.startMachine, 'mac-1');
+
+ await run(steps, machineId: 'elsewhere');
+ final starts = swarm.commands('lead.start');
+ expect(starts, hasLength(2));
+ expect(starts[0]['operationId'], starts[1]['operationId']);
+ expect((starts[1]['command'] as Map)['machineId'], 'mac-1');
+ });
+
+ test('a machine that can no longer take it on a fresh read is refused '
+ 'with why, and no start is sent', () async {
+ final steps = SwarmNewProjectSteps.of(reader);
+ swarm.machines = [leadPool('mac-1', name: 'Studio', slots: 0)];
+ await expectLater(
+ run(steps),
+ throwsA(
+ isA<SuperTabFailure>().having(
+ (f) => f.message,
+ 'message',
+ 'Studio has no free agents. Choose another machine.',
+ ),
+ ),
+ );
+ expect(swarm.commands('lead.start'), isEmpty);
+ expect(swarm.commands('project.create'), hasLength(1));
+ });
+
+ test('a fresh read that fails sends no start and says so; once the Swarm '
+ 'answers again, Create again starts it', () async {
+ final steps = SwarmNewProjectSteps.of(reader);
+ final changes = fake.routes['/api/super-tabs/$tab/changes']!;
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>
+ throw const SuperTabFailure('NETWORK', 'Offline.');
+ await expectLater(
+ run(steps),
+ throwsA(
+ isA<SuperTabFailure>().having(
+ (f) => f.code,
+ 'code',
+ 'SWARM_UNREADABLE',
+ ),
+ ),
+ );
+ expect(swarm.commands('lead.start'), isEmpty);
+
+ fake.routes['/api/super-tabs/$tab/changes'] = changes;
+ await run(steps);
+ expect(swarm.commands('lead.start'), hasLength(1));
+ expect(swarm.commands('project.create'), hasLength(1));
+ });
+
+ test(
+ 'once the sheet goes, an answer that arrives sends nothing more',
+ () async {
+ var live = true;
+ final held = Completer<Object?>();
+ swarm.answer = (command) =>
+ command['type'] == 'project.create' ? held.future : null;
+ final steps = SwarmNewProjectSteps.of(reader);
+ final running = run(steps, live: () => live);
+ await settle();
+ live = false;
+ held.complete(null);
+ await expectLater(running, throwsA(isA<SwarmNewProjectGone>()));
+ expect(
+ [for (final b in swarm.sent) (b['command'] as Map)['type']],
+ ['project.create'],
+ );
+ expect(steps.projectId, isNotNull, reason: 'its answer is kept');
+
+ // Opened again, it starts after what was answered.
+ await run(steps);
+ expect(
+ [for (final b in swarm.sent) (b['command'] as Map)['type']],
+ ['project.create', 'message.send', 'lead.start', 'project.rename'],
+ );
+ },
+ );
+
+ test('a name that fails once its Product Manager started is retried '
+ 'under its operation, and starts nothing more', () async {
+ var fail = true;
+ swarm.answer = (command) {
+ if (command['type'] == 'project.rename' && fail) {
+ fail = false;
+ throw const SuperTabFailure('NETWORK', 'The Swarm didn’t answer.');
+ }
+ return null;
+ };
+ final steps = SwarmNewProjectSteps.of(reader);
+ await expectLater(run(steps), throwsA(isA<SuperTabFailure>()));
+ expect(steps.started, isTrue);
+ expect(steps.startSent, isTrue);
+
+ // Its machine is full now, with the Product Manager on it.
+ swarm.machines = [leadPool('mac-1', name: 'Studio', slots: 0)];
+ await run(steps, machineId: 'elsewhere');
+ expect(swarm.commands('lead.start'), hasLength(1));
+ final renames = swarm.commands('project.rename');
+ expect(renames, hasLength(2));
+ expect(renames[0]['operationId'], renames[1]['operationId']);
+ });
+ });
+
+ group('Swarm Home', () {
+ /// Swarm Home over [swarms], on an iPhone's screen, as the person [me].
+ Future<SwarmHost> pump(
+ WidgetTester tester,
+ List<NewProjectSwarm> swarms, {
+ ValueNotifier<String?>? account,
+ }) async {
+ tester.view.physicalSize = const Size(1170, 2532);
+ tester.view.devicePixelRatio = 3;
+ addTearDown(tester.view.reset);
+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm};
+ final signedIn = account ?? ValueNotifier<String?>(me);
+ final host = SwarmHost(
+ accountId: () => signedIn.value,
+ account: signedIn,
+ request: newProjectBackend(swarms).request,
+ notices: SilentSystemNotices(),
+ features: features,
+ readMarks: MemoryKeyValueStore(),
+ )..foreground = false;
+ addTearDown(host.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ builder: (context, child) =>
+ SwarmScope(notifier: host, child: child!),
+ onGenerateRoute: (_) => CupertinoPageRoute<void>(
+ builder: (_) => SwarmPage(now: () => newProjectNow),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return host;
+ }
+
+ Finder key(String value) => find.byKey(ValueKey(value));
+
+ Future<void> tap(WidgetTester tester, String k) async {
+ await tester.ensureVisible(key(k));
+ await tester.pumpAndSettle();
+ await tester.tap(key(k));
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> pickMachine(WidgetTester tester, String id) async {
+ await tap(tester, 'swarm-new-project-machine');
+ await tap(tester, 'swarm-new-project-pick-machine-$id');
+ }
+
+ /// A second of frames: Create's spinner never settles while it waits.
+ Future<void> pumpFor(WidgetTester tester) async {
+ for (var i = 0; i < 10; i++) {
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+ }
+
+ testWidgets('+ New project is the last row of Projects for someone who '
+ 'may write in the Swarm', (tester) async {
+ await pump(tester, [NewProjectSwarm()]);
+ expect(key('swarm-new-project'), findsOneWidget);
+ expect(find.text('New project'), findsOneWidget);
+ final rows = [
+ key('swarm-project-$tab-$project'),
+ key('swarm-project-$tab-project-2'),
+ ];
+ for (final row in rows) {
+ expect(
+ tester.getTopLeft(row).dy,
+ lessThan(tester.getTopLeft(key('swarm-new-project')).dy),
+ );
+ }
+ });
+
+ testWidgets('a collaborator has it; a viewer does not', (tester) async {
+ await pump(tester, [NewProjectSwarm(role: 'collaborator')]);
+ expect(key('swarm-new-project'), findsOneWidget);
+ });
+
+ testWidgets('a viewer has no + New project', (tester) async {
+ await pump(tester, [NewProjectSwarm(role: 'viewer')]);
+ expect(key('swarm-project-$tab-$project'), findsOneWidget);
+ expect(key('swarm-new-project'), findsNothing);
+ });
+
+ testWidgets('a Swarm whose first read failed offers it once its read '
+ 'recovers', (tester) async {
+ final swarm = NewProjectSwarm()..unreadable = true;
+ final host = await pump(tester, [swarm]);
+ expect(key('swarm-projects-error-$tab'), findsOneWidget);
+ expect(key('swarm-new-project'), findsNothing);
+
+ swarm.unreadable = false;
+ await host.session!.inbox.reader(tab)!.refresh();
+ await tester.pumpAndSettle();
+ expect(key('swarm-new-project'), findsOneWidget);
+ await tap(tester, 'swarm-new-project');
+ expect(key('swarm-new-project-sheet'), findsOneWidget);
+ });
+
+ testWidgets('on All Swarms the sheet asks which Swarm, offering only '
+ 'those the person may write in', (tester) async {
+ await pump(tester, [
+ NewProjectSwarm(),
+ NewProjectSwarm(id: 'tab-viewed', name: 'Viewed', role: 'viewer'),
+ NewProjectSwarm(id: 'tab-2', name: 'Lamp Swarm', role: 'collaborator'),
+ ]);
+ await tap(tester, 'swarm-new-project');
+ expect(key('swarm-new-project-sheet'), findsOneWidget);
+ expect(key('swarm-new-project-swarm'), findsOneWidget);
+ await tap(tester, 'swarm-new-project-swarm');
+ expect(key('swarm-new-project-pick-swarm-$tab'), findsOneWidget);
+ expect(key('swarm-new-project-pick-swarm-tab-2'), findsOneWidget);
+ expect(key('swarm-new-project-pick-swarm-tab-viewed'), findsNothing);
+ expect(
+ find.descendant(
+ of: key('swarm-new-project-sheet'),
+ matching: find.text('Viewed'),
+ ),
+ findsNothing,
+ );
+ });
+
+ testWidgets('one Swarm shown: no Swarm row', (tester) async {
+ await pump(tester, [NewProjectSwarm()]);
+ await tap(tester, 'swarm-new-project');
+ expect(key('swarm-new-project-swarm'), findsNothing);
+ });
+
+ testWidgets('the repository is the most recently active project\'s, '
+ 'others and a link a tap away; a link the server would refuse is '
+ 'not taken', (tester) async {
+ await pump(tester, [NewProjectSwarm()]);
+ await tap(tester, 'swarm-new-project');
+ expect(
+ find.descendant(
+ of: key('swarm-new-project-repository'),
+ matching: find.text('openharness'),
+ ),
+ findsOneWidget,
+ );
+ await tap(tester, 'swarm-new-project-repository');
+ expect(key('swarm-new-project-pick-repo-$lampRepo'), findsOneWidget);
+ await tap(tester, 'swarm-new-project-pick-link');
+ await tester.enterText(
+ key('swarm-new-project-link'),
+ 'https://me:[email protected]/a/b',
+ );
+ await tap(tester, 'swarm-new-project-link-use');
+ expect(key('swarm-new-project-link-error'), findsOneWidget);
+ await tester.enterText(key('swarm-new-project-link'), 'github.com/a/b');
+ await tap(tester, 'swarm-new-project-link-use');
+ expect(
+ find.descendant(
+ of: key('swarm-new-project-repository'),
+ matching: find.text('b'),
+ ),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('PM runs on lists only machines that can run it; with none, '
+ 'each says why', (tester) async {
+ final swarm = NewProjectSwarm(
+ machines: [
+ leadPool('mac-1', name: 'Studio'),
+ leadPool('mac-2', name: 'Old', capable: false),
+ leadPool('mac-3', name: 'Full', slots: 0),
+ leadPool('mac-4', name: 'Lead only', scope: null),
+ ],
+ );
+ final host = await pump(tester, [swarm]);
+ await tap(tester, 'swarm-new-project');
+ expect(find.text(swarmLeadChooseMachine), findsOneWidget);
+ await tap(tester, 'swarm-new-project-machine');
+ expect(key('swarm-new-project-pick-machine-mac-1'), findsOneWidget);
+ expect(key('swarm-new-project-pick-machine-mac-2'), findsNothing);
+ expect(key('swarm-new-project-pick-machine-mac-3'), findsNothing);
+ expect(key('swarm-new-project-pick-machine-mac-4'), findsNothing);
+ await tap(tester, 'swarm-new-project-back');
+
+ // None can now: each says why, and Create says so.
+ swarm.machines = [
+ leadPool('mac-2', name: 'Old', capable: false),
+ leadPool('mac-3', name: 'Full', slots: 0),
+ leadPool('mac-4', name: 'Lead only', scope: null),
+ ];
+ await host.session!.inbox.reader(tab)!.refresh();
+ await tester.pumpAndSettle();
+ expect(find.text(swarmLeadNoMachine), findsOneWidget);
+ await tap(tester, 'swarm-new-project-machine');
+ expect(key('swarm-new-project-no-machine'), findsOneWidget);
+ expect(
+ find.text('Update Harness on Old to run a Product Manager there.'),
+ findsOneWidget,
+ );
+ expect(find.text('Claude Code · No agents free'), findsOneWidget);
+ // Added for the Lead only: the server would refuse it.
+ expect(
+ find.descendant(
+ of: key('swarm-new-project-pick-machine-mac-4'),
+ matching: find.text(swarmLeadUnscoped),
+ ),
+ findsOneWidget,
+ );
+ await tester.tap(key('swarm-new-project-pick-machine-mac-2'));
+ await tester.pumpAndSettle();
+ expect(
+ key('swarm-new-project-no-machine'),
+ findsOneWidget,
+ reason: 'not taken',
+ );
+ });
+
+ testWidgets('Create makes the project, starts its Product Manager on the '
+ 'machine picked and opens its project screen', (tester) async {
+ final swarm = NewProjectSwarm();
+ await pump(tester, [swarm]);
+ await tap(tester, 'swarm-new-project');
+ await tester.enterText(
+ key('swarm-new-project-brief'),
+ 'Phone New project',
+ );
+ await pickMachine(tester, 'mac-1');
+ await tap(tester, 'swarm-new-project-create');
+
+ expect(swarm.commands('project.create'), hasLength(1));
+ final start = swarm.commands('lead.start').single['command'] as Map;
+ expect(start['machineId'], 'mac-1');
+ expect(start['repositoryUrl'], harnessRepo);
+ expect(key('swarm-new-project-sheet'), findsNothing);
+ expectHomeCProject('openharness');
+ });
+
+ testWidgets('a refused start keeps the project, in the list, says why, '
+ 'and Create again starts it without a second project', (tester) async {
+ final swarm = NewProjectSwarm(
+ machines: [
+ leadPool('mac-1', name: 'Studio'),
+ leadPool('mac-2', name: 'Mini'),
+ ],
+ );
+ var refuse = true;
+ swarm.answer = (command) {
+ if (command['type'] == 'lead.start' && refuse) {
+ refuse = false;
+ throw const SuperTabFailure(
+ 'TEAM_ACCOUNT_BUSY',
+ 'Studio is busy.',
+ statusCode: 409,
+ );
+ }
+ return null;
+ };
+ await pump(tester, [swarm]);
+ await tap(tester, 'swarm-new-project');
+ await pickMachine(tester, 'mac-1');
+ await tap(tester, 'swarm-new-project-create');
+
+ expect(
+ find.text(
+ 'The project is made. Its Product Manager didn’t start: '
+ 'Studio is busy.',
+ ),
+ findsOneWidget,
+ );
+ final made = swarm.projects.last['id'] as String;
+ expect(key('swarm-project-$tab-$made'), findsOneWidget);
+ expect(find.text('Try again'), findsOneWidget);
+
+ await pickMachine(tester, 'mac-2');
+ await tap(tester, 'swarm-new-project-create');
+ expect(swarm.commands('project.create'), hasLength(1));
+ expect(swarm.commands('lead.start'), hasLength(2));
+ expectHomeCProject('openharness');
+ });
+
+ testWidgets('a create whose answer was lost is sent again under its '
+ 'operation on Try again', (tester) async {
+ final swarm = NewProjectSwarm();
+ var lose = true;
+ swarm.answer = (command) {
+ if (command['type'] == 'project.create' && lose) {
+ lose = false;
+ throw const SuperTabFailure('NETWORK', 'The Swarm didn’t answer.');
+ }
+ return null;
+ };
+ await pump(tester, [swarm]);
+ await tap(tester, 'swarm-new-project');
+ await pickMachine(tester, 'mac-1');
+ await tap(tester, 'swarm-new-project-create');
+ expect(key('swarm-new-project-error'), findsOneWidget);
+ await tap(tester, 'swarm-new-project-create');
+
+ final creates = swarm.commands('project.create');
+ expect(creates, hasLength(2));
+ expect(creates[0]['operationId'], creates[1]['operationId']);
+ expect(
+ swarm.projects.where((p) => p['name'] == 'openharness'),
+ hasLength(1),
+ );
+ });
+
+ testWidgets('a name that fails once its Product Manager started says '
+ 'so, and Try again names it without starting another, though its '
+ 'machine is full now', (tester) async {
+ final swarm = NewProjectSwarm();
+ var fail = true;
+ swarm.answer = (command) {
+ if (command['type'] == 'project.rename' && fail) {
+ fail = false;
+ // The Product Manager took the machine's last agent.
+ swarm.machines = [leadPool('mac-1', name: 'Studio.local', slots: 0)];
+ throw const SuperTabFailure('NETWORK', 'The Swarm didn’t answer.');
+ }
+ return null;
+ };
+ final host = await pump(tester, [swarm]);
+ await tap(tester, 'swarm-new-project');
+ await pickMachine(tester, 'mac-1');
+ await tap(tester, 'swarm-new-project-create');
+ await host.session!.inbox.reader(tab)!.refresh();
+ await tester.pumpAndSettle();
+
+ expect(
+ find.text(
+ 'The project is made and its Product Manager is starting. '
+ 'Naming it didn’t finish: The Swarm didn’t answer.',
+ ),
+ findsOneWidget,
+ );
+ expect(key('swarm-new-project-note'), findsNothing);
+ await tap(tester, 'swarm-new-project-create');
+ expect(swarm.commands('lead.start'), hasLength(1));
+ final renames = swarm.commands('project.rename');
+ expect(renames, hasLength(2));
+ expect(renames[0]['operationId'], renames[1]['operationId']);
+ expectHomeCProject('openharness');
+ });
+
+ testWidgets('while a step\'s answer is awaited it stays open: its close, '
+ 'back, the page behind it and a drag down do nothing', (tester) async {
+ final swarm = NewProjectSwarm();
+ final held = Completer<Object?>();
+ swarm.answer = (command) =>
+ command['type'] == 'project.create' ? held.future : null;
+ await pump(tester, [swarm]);
+ await tap(tester, 'swarm-new-project');
+ await pickMachine(tester, 'mac-1');
+ await tester.tap(key('swarm-new-project-create'));
+ await pumpFor(tester);
+ expect(find.text('Creating…'), findsOneWidget);
+ expect(key('swarm-new-project-start-over'), findsNothing);
+
+ await tester.tap(key('swarm-new-project-close'), warnIfMissed: false);
+ await pumpFor(tester);
+ expect(key('swarm-new-project-sheet'), findsOneWidget, reason: 'close');
+ await tester.binding.handlePopRoute();
+ await pumpFor(tester);
+ expect(key('swarm-new-project-sheet'), findsOneWidget, reason: 'back');
+ await tester.tapAt(const Offset(195, 40));
+ await pumpFor(tester);
+ expect(key('swarm-new-project-sheet'), findsOneWidget, reason: 'behind');
+ await tester.drag(
+ find.descendant(
+ of: key('swarm-new-project-sheet'),
+ matching: find.text('New project'),
+ ),
+ const Offset(0, 600),
+ );
+ await pumpFor(tester);
+ expect(key('swarm-new-project-sheet'), findsOneWidget, reason: 'drag');
+
+ held.complete(null);
+ await tester.pumpAndSettle();
+ expect(key('swarm-new-project-sheet'), findsNothing);
+ expect(swarm.commands('project.create'), hasLength(1));
+ expectHomeCProject('openharness');
+ });
+
+ testWidgets('closed after a create\'s answer was lost, it opens on its '
+ 'steps where they stopped and finishes them under the same '
+ 'operation', (tester) async {
+ final swarm = NewProjectSwarm();
+ var lose = true;
+ swarm.answer = (command) {
+ if (command['type'] == 'project.create' && lose) {
+ lose = false;
+ throw const SuperTabFailure('NETWORK', 'The Swarm didn’t answer.');
+ }
+ return null;
+ };
+ await pump(tester, [swarm]);
+ await tap(tester, 'swarm-new-project');
+ await tester.enterText(key('swarm-new-project-brief'), 'Ship it');
+ await tap(tester, 'swarm-new-project-visibility');
+ await tap(tester, 'swarm-new-project-pick-visibility-private');
+ await pickMachine(tester, 'mac-1');
+ await tap(tester, 'swarm-new-project-create');
+ expect(key('swarm-new-project-error'), findsOneWidget);
+ await tap(tester, 'swarm-new-project-close');
+ expect(key('swarm-new-project-sheet'), findsNothing);
+
+ await tap(tester, 'swarm-new-project');
+ expect(
+ find.text('Couldn’t create the project: The Swarm didn’t answer.'),
+ findsOneWidget,
+ );
+ expect(
+ tester
+ .widget<TextField>(key('swarm-new-project-brief'))
+ .controller!
+ .text,
+ 'Ship it',
+ );
+ for (final (field, value) in [
+ ('visibility', 'Private'),
+ ('machine', 'Studio'),
+ ('repository', 'openharness'),
+ ]) {
+ expect(
+ find.descendant(
+ of: key('swarm-new-project-$field'),
+ matching: find.text(value),
+ ),
+ findsOneWidget,
+ reason: field,
+ );
+ }
+ await tap(tester, 'swarm-new-project-create');
+
+ final creates = swarm.commands('project.create');
+ expect(creates, hasLength(2));
+ expect(creates[0]['operationId'], creates[1]['operationId']);
+ expect(creates[1]['command'], creates[0]['command']);
+ expect(
+ (swarm.commands('message.send').single['command'] as Map)['text'],
+ 'Ship it',
+ );
+ expect(swarm.commands('lead.start'), hasLength(1));
+ expectHomeCProject('openharness');
+ });
+
+ testWidgets('closed after its create was refused, it opens afresh: '
+ 'nothing was made to finish', (tester) async {
+ final swarm = NewProjectSwarm();
+ swarm.answer = (command) => command['type'] == 'project.create'
+ ? throw const SuperTabFailure(
+ 'PROJECT_LIMIT',
+ 'Too many projects.',
+ statusCode: 409,
+ )
+ : null;
+ await pump(tester, [swarm]);
+ await tap(tester, 'swarm-new-project');
+ await pickMachine(tester, 'mac-1');
+ await tap(tester, 'swarm-new-project-create');
+ expect(key('swarm-new-project-error'), findsOneWidget);
+ await tap(tester, 'swarm-new-project-close');
+
+ await tap(tester, 'swarm-new-project');
+ expect(key('swarm-new-project-error'), findsNothing);
+ expect(find.text('Create'), findsOneWidget);
+ expect(
+ find.descendant(
+ of: key('swarm-new-project-machine'),
+ matching: find.text('Choose'),
+ ),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('a project deleted before its brief posts cannot hold the '
+ 'sheet: Try again says so, the fields open, and Create makes a new '
+ 'one', (tester) async {
+ final swarm = NewProjectSwarm();
+ var delete = true;
+ swarm.answer = (command) {
+ if (command['type'] == 'message.send' && delete) {
+ delete = false;
+ swarm.projects.removeWhere((p) => p['name'] == 'New project');
+ throw const SuperTabFailure(
+ 'NOT_FOUND',
+ 'This chat no longer exists.',
+ statusCode: 404,
+ );
+ }
+ return null;
+ };
+ await pump(tester, [swarm]);
+ await tap(tester, 'swarm-new-project');
+ await tester.enterText(key('swarm-new-project-brief'), 'Ship it');
+ await pickMachine(tester, 'mac-1');
+ await tap(tester, 'swarm-new-project-create');
+ expect(key('swarm-new-project-error'), findsOneWidget);
+ await tap(tester, 'swarm-new-project-create');
+
+ expect(
+ find.text('The project was deleted meanwhile. Create it again.'),
+ findsOneWidget,
+ );
+ expect(
+ tester.widget<TextField>(key('swarm-new-project-brief')).enabled,
+ isTrue,
+ );
+ expect(key('swarm-new-project-start-over'), findsNothing);
+ await tap(tester, 'swarm-new-project-create');
+ expect(swarm.commands('project.create'), hasLength(2));
+ expect(swarm.commands('message.send'), hasLength(2));
+ expectHomeCProject('openharness');
+ });
+
+ testWidgets('Start over lets the steps go when nothing runs: the fields '
+ 'open, and Create makes a new project', (tester) async {
+ final swarm = NewProjectSwarm();
+ var lose = true;
+ swarm.answer = (command) {
+ if (command['type'] == 'project.create' && lose) {
+ lose = false;
+ throw const SuperTabFailure('NETWORK', 'The Swarm didn’t answer.');
+ }
+ return null;
+ };
+ await pump(tester, [swarm]);
+ await tap(tester, 'swarm-new-project');
+ await tester.enterText(key('swarm-new-project-brief'), 'Ship it');
+ await pickMachine(tester, 'mac-1');
+ expect(key('swarm-new-project-start-over'), findsNothing);
+ await tap(tester, 'swarm-new-project-create');
+ expect(
+ tester.widget<TextField>(key('swarm-new-project-brief')).enabled,
+ isFalse,
+ reason: 'held as sent',
+ );
+
+ expect(key('swarm-new-project-maybe-made'), findsNothing);
+ await tap(tester, 'swarm-new-project-start-over');
+ expect(key('swarm-new-project-error'), findsNothing);
+ expect(key('swarm-new-project-start-over'), findsNothing);
+ expect(find.text(swarmNewProjectMaybeMade), findsOneWidget);
+ final brief = tester.widget<TextField>(key('swarm-new-project-brief'));
+ expect(brief.enabled, isTrue);
+ expect(brief.controller!.text, 'Ship it');
+ await tap(tester, 'swarm-new-project-create');
+ final creates = swarm.commands('project.create');
+ expect(creates, hasLength(2));
+ expect(creates[0]['operationId'], isNot(creates[1]['operationId']));
+ expectHomeCProject('openharness');
+ });
+
+ testWidgets('Start over after a lost create says a project may be there, '
+ 'until the next Create, which says its own', (tester) async {
+ final swarm = NewProjectSwarm();
+ swarm.answer = (command) => command['type'] == 'project.create'
+ ? throw const SuperTabFailure('NETWORK', 'The Swarm didn’t answer.')
+ : null;
+ await pump(tester, [swarm]);
+ await tap(tester, 'swarm-new-project');
+ await pickMachine(tester, 'mac-1');
+ await tap(tester, 'swarm-new-project-create');
+ await tap(tester, 'swarm-new-project-close');
+ // Opened again on the steps: they still know, the sheet did not see it.
+ await tap(tester, 'swarm-new-project');
+ await tap(tester, 'swarm-new-project-start-over');
+ expect(key('swarm-new-project-maybe-made'), findsOneWidget);
+
+ await tap(tester, 'swarm-new-project-create');
+ expect(key('swarm-new-project-maybe-made'), findsNothing);
+ expect(key('swarm-new-project-error'), findsOneWidget);
+ });
+
+ testWidgets('Start over after the project was made says nothing of one '
+ 'that may be there: it is in the list', (tester) async {
+ final swarm = NewProjectSwarm();
+ swarm.answer = (command) => command['type'] == 'message.send'
+ ? throw const SuperTabFailure('NETWORK', 'The Swarm didn’t answer.')
+ : null;
+ await pump(tester, [swarm]);
+ await tap(tester, 'swarm-new-project');
+ await tester.enterText(key('swarm-new-project-brief'), 'Ship it');
+ await pickMachine(tester, 'mac-1');
+ await tap(tester, 'swarm-new-project-create');
+ expect(key('swarm-new-project-error'), findsOneWidget);
+ await tap(tester, 'swarm-new-project-start-over');
+ expect(key('swarm-new-project-error'), findsNothing);
+ expect(key('swarm-new-project-maybe-made'), findsNothing);
+ });
+
+ testWidgets('choosing another Swarm takes the note away: it was about the '
+ 'Swarm left', (tester) async {
+ final swarm = NewProjectSwarm();
+ swarm.answer = (command) => command['type'] == 'project.create'
+ ? throw const SuperTabFailure('NETWORK', 'The Swarm didn’t answer.')
+ : null;
+ await pump(tester, [
+ swarm,
+ NewProjectSwarm(id: 'tab-2', name: 'Lamp Swarm', role: 'collaborator'),
+ ]);
+ await tap(tester, 'swarm-new-project');
+ await pickMachine(tester, 'mac-1');
+ await tap(tester, 'swarm-new-project-create');
+ await tap(tester, 'swarm-new-project-start-over');
+ expect(key('swarm-new-project-maybe-made'), findsOneWidget);
+
+ await tap(tester, 'swarm-new-project-swarm');
+ await tap(tester, 'swarm-new-project-pick-swarm-tab-2');
+ expect(key('swarm-new-project-maybe-made'), findsNothing);
+ });
+
+ testWidgets('torn down between steps, it opens on them still under way, '
+ 'then finishes them with no second project or brief', (tester) async {
+ final swarm = NewProjectSwarm();
+ final held = Completer<Object?>();
+ swarm.answer = (command) =>
+ command['type'] == 'message.send' ? held.future : null;
+ await pump(tester, [swarm]);
+ await tap(tester, 'swarm-new-project');
+ await tester.enterText(key('swarm-new-project-brief'), 'Ship it');
+ await pickMachine(tester, 'mac-1');
+ await tester.tap(key('swarm-new-project-create'));
+ await pumpFor(tester);
+ expect(swarm.commands('message.send'), hasLength(1));
+
+ // Gone without a word, as the system may take a sheet away.
+ final sheet = tester.element(key('swarm-new-project-sheet'));
+ Navigator.of(sheet).removeRoute(ModalRoute.of(sheet)!);
+ await pumpFor(tester);
+ expect(key('swarm-new-project-sheet'), findsNothing);
+
+ await tester.tap(key('swarm-new-project'));
+ await pumpFor(tester);
+ expect(find.text('Creating…'), findsOneWidget, reason: 'still waiting');
+ expect(key('swarm-new-project-start-over'), findsNothing);
+ held.complete(null);
+ await tester.pumpAndSettle();
+ expect(find.text('Create'), findsOneWidget);
+ expect(key('swarm-new-project-start-over'), findsOneWidget);
+ expect(key('swarm-new-project-error'), findsNothing);
+ await tap(tester, 'swarm-new-project-create');
+
+ expect(
+ [for (final b in swarm.sent) (b['command'] as Map)['type']],
+ ['project.create', 'message.send', 'lead.start', 'project.rename'],
+ );
+ expectHomeCProject('openharness');
+ });
+
+ testWidgets('on a 320 by 568 phone with the keyboard up and a four-line '
+ 'error, the brief typed in and Create stay in sight', (tester) async {
+ final swarm = NewProjectSwarm();
+ swarm.answer = (command) => command['type'] == 'project.create'
+ ? throw SuperTabFailure(
+ 'PROJECT_LIMIT',
+ 'This Swarm has as many projects as it can hold. ' * 6,
+ statusCode: 409,
+ )
+ : null;
+ await pump(tester, [swarm]);
+ tester.view.physicalSize = const Size(960, 1704);
+ tester.view.padding = const FakeViewPadding(top: 60);
+ await tester.pumpAndSettle();
+ await tap(tester, 'swarm-new-project');
+ await pickMachine(tester, 'mac-1');
+ await tap(tester, 'swarm-new-project-create');
+ final error = key('swarm-new-project-error');
+ final scroll = find.descendant(
+ of: key('swarm-new-project-sheet'),
+ matching: find.byType(SingleChildScrollView),
+ );
+ // Scrolled into sight as it appears, over Create.
+ final first = tester.getRect(error);
+ expect(first.top, greaterThanOrEqualTo(tester.getRect(scroll).top));
+ expect(first.bottom, lessThanOrEqualTo(tester.getRect(scroll).bottom));
+ final text = find.descendant(of: error, matching: find.byType(RichText));
+ final painter = TextPainter(
+ text: tester.widget<RichText>(text).text,
+ textDirection: TextDirection.ltr,
+ maxLines: 4,
+ )..layout(maxWidth: tester.getSize(text).width);
+ expect(painter.computeLineMetrics(), hasLength(4));
+ painter.dispose();
+
+ // Refused outright: the brief is written again, the keyboard up, to
+ // its sixth line.
+ await tap(tester, 'swarm-new-project-brief');
+ tester.view.viewInsets = const FakeViewPadding(bottom: 260 * 3);
+ await tester.pumpAndSettle();
+ await tester.enterText(
+ key('swarm-new-project-brief'),
+ List.filled(6, 'Ship the phone flow.').join('\n'),
+ );
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ final create = tester.getRect(key('swarm-new-project-create'));
+ expect(create.bottom, lessThanOrEqualTo(568 - 260));
+ final view = tester.getRect(scroll);
+ expect(view.top, greaterThanOrEqualTo(20), reason: 'under the bar');
+ expect(view.bottom, lessThanOrEqualTo(create.top));
+ // The line typed in, in sight.
+ final editable = tester
+ .state<EditableTextState>(
+ find.descendant(
+ of: key('swarm-new-project-brief'),
+ matching: find.byType(EditableText),
+ ),
+ )
+ .renderEditable;
+ final caret = MatrixUtils.transformRect(
+ editable.getTransformTo(null),
+ editable.getLocalRectForCaret(
+ TextPosition(offset: editable.text!.toPlainText().length),
+ ),
+ );
+ expect(caret.top, greaterThanOrEqualTo(view.top));
+ expect(caret.bottom, lessThanOrEqualTo(view.bottom));
+ // Why it stopped scrolls with the form, a scroll away.
+ expect(find.descendant(of: scroll, matching: error), findsOneWidget);
+ await tester.ensureVisible(error);
+ await tester.pumpAndSettle();
+ final shown = tester.getRect(error);
+ expect(shown.top, greaterThanOrEqualTo(view.top));
+ expect(shown.bottom, lessThanOrEqualTo(view.bottom));
+ expect(
+ tester.getRect(key('swarm-new-project-create')),
+ create,
+ reason: 'Create stays',
+ );
+ });
+
+ testWidgets('its Swarm read again under another reader while it is open '
+ 'closes it, and nothing is sent through either', (tester) async {
+ final swarm = NewProjectSwarm();
+ final swarms = [swarm];
+ final host = await pump(tester, swarms);
+ await tap(tester, 'swarm-new-project');
+ await pickMachine(tester, 'mac-1');
+ final inbox = host.session!.inbox;
+ final before = inbox.reader(tab);
+ // Off the list and back, between two frames.
+ swarms.clear();
+ await inbox.refresh();
+ swarms.add(swarm);
+ await inbox.refresh();
+ expect(inbox.reader(tab), isNot(same(before)));
+ expect(swarmMayCreateProject(inbox, tab), isTrue);
+ await tester.pumpAndSettle();
+ expect(find.byType(BottomSheet), findsNothing);
+ expect(key('swarm-new-project'), findsOneWidget, reason: 'listed again');
+ expect(swarm.sent, isEmpty);
+ });
+
+ testWidgets('its Swarm read again under another reader while a create is '
+ 'on its way closes it; the answer sends nothing more, and the new '
+ 'reader holds no steps', (tester) async {
+ final swarm = NewProjectSwarm();
+ final swarms = [swarm];
+ final held = Completer<Object?>();
+ swarm.answer = (command) =>
+ command['type'] == 'project.create' ? held.future : null;
+ final host = await pump(tester, swarms);
+ await tap(tester, 'swarm-new-project');
+ await tester.enterText(key('swarm-new-project-brief'), 'Ship it');
+ await pickMachine(tester, 'mac-1');
+ await tester.tap(key('swarm-new-project-create'));
+ await pumpFor(tester);
+ expect(find.text('Creating…'), findsOneWidget);
+
+ final inbox = host.session!.inbox;
+ swarms.clear();
+ await inbox.refresh();
+ swarms.add(swarm);
+ await inbox.refresh();
+ await pumpFor(tester);
+ expect(find.byType(BottomSheet), findsNothing, reason: 'though busy');
+ held.complete(null);
+ await tester.pumpAndSettle();
+ expect(
+ [for (final b in swarm.sent) (b['command'] as Map)['type']],
+ ['project.create'],
+ );
+ expect(SwarmNewProjectSteps.heldBy(inbox.reader(tab)!), isNull);
+
+ await tap(tester, 'swarm-new-project');
+ expect(key('swarm-new-project-error'), findsNothing);
+ expect(
+ tester
+ .widget<TextField>(key('swarm-new-project-brief'))
+ .controller!
+ .text,
+ isEmpty,
+ );
+ });
+
+ testWidgets('its Swarm\'s read taken away while it is open closes it at '
+ 'once', (tester) async {
+ final swarm = NewProjectSwarm();
+ final host = await pump(tester, [swarm]);
+ await tap(tester, 'swarm-new-project');
+ expect(key('swarm-new-project-sheet'), findsOneWidget);
+ swarm.revoked = true;
+ await host.session!.inbox.reader(tab)!.refresh();
+ expect(host.session!.inbox.reader(tab)!.accessRevoked, isTrue);
+ await tester.pump();
+ expect(key('swarm-new-project-sheet'), findsNothing, reason: 'blank');
+ await tester.pumpAndSettle();
+ expect(find.byType(BottomSheet), findsNothing);
+ });
+
+ testWidgets('made a viewer while it is open closes it', (tester) async {
+ final swarm = NewProjectSwarm();
+ final host = await pump(tester, [swarm]);
+ await tap(tester, 'swarm-new-project');
+ swarm.role = 'viewer';
+ await host.session!.inbox.reader(tab)!.refresh();
+ await tester.pumpAndSettle();
+ expect(find.byType(BottomSheet), findsNothing);
+ expect(key('swarm-new-project'), findsNothing);
+ });
+
+ testWidgets('signing out while it is open closes it', (tester) async {
+ final account = ValueNotifier<String?>(me);
+ await pump(tester, [NewProjectSwarm()], account: account);
+ await tap(tester, 'swarm-new-project');
+ account.value = null;
+ await tester.pumpAndSettle();
+ expect(find.byType(BottomSheet), findsNothing);
+ expect(key('swarm-new-project-sheet'), findsNothing);
+ });
+
+ testWidgets('access taken away while a create is on its way: its answer '
+ 'opens nothing and nothing more is sent', (tester) async {
+ final swarm = NewProjectSwarm();
+ final held = Completer<Object?>();
+ swarm.answer = (command) =>
+ command['type'] == 'project.create' ? held.future : null;
+ final host = await pump(tester, [swarm]);
+ await tap(tester, 'swarm-new-project');
+ // A brief: the next step would post it.
+ await tester.enterText(key('swarm-new-project-brief'), 'Ship it');
+ await pickMachine(tester, 'mac-1');
+ await tester.tap(key('swarm-new-project-create'));
+ await tester.pump();
+ expect(swarm.commands('project.create'), hasLength(1));
+
+ swarm.revoked = true;
+ await host.session!.inbox.reader(tab)!.refresh();
+ await tester.pumpAndSettle();
+ expect(find.byType(BottomSheet), findsNothing);
+ held.complete(null);
+ await tester.pumpAndSettle();
+ expect(
+ [for (final b in swarm.sent) (b['command'] as Map)['type']],
+ ['project.create'],
+ );
+ expect(find.text('#openharness'), findsNothing);
+ expect(find.byType(SwarmPage), findsOneWidget);
+ });
+ });
+}