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.

66.5 KB
Raw Blame
import 'dart:async';
import 'dart:convert';
import 'dart:math' as math;

import 'package:dio/dio.dart' show CancelToken;
import 'package:flutter/foundation.dart' show visibleForTesting;
import 'package:path/path.dart' as p;
import 'package:url_launcher/url_launcher.dart';

import '../core/first_task.dart';
import '../logging/app_log.dart';
import '../core/models.dart';
import '../state/app_state.dart';
import '../state/harness_attachments.dart';
import '../state/harness_launch_integration.dart';
import '../state/lead_placement.dart';
import '../state/swarm.dart';
import 'attachment_upload.dart';
import 'actions.dart';
import 'controller.dart';
import 'machine_icon.dart';
import 'machine_status.dart';
import 'model.dart';
import 'new_repository.dart';
import 'personal_projects.dart' show PersonalProjects;
import 'launch_prompt.dart';
import 'identity.dart' show superTabMachineName;
import 'instructions_model.dart';

/// Captures a conversation before opening New Harness. Its journal survives a
/// closed form or process; a recovered launch only reads the native receipt.
class SuperTabLaunch {
  SuperTabLaunch._(
    this.app,
    this.swarmId,
    this.accountId,
    this.key,
    this.saved,
  );
  final AppNotifier app;
  final String swarmId, accountId, key;
  final Map<String, dynamic> saved;

  static Future<HarnessLaunchIntegration> open(
    AppNotifier app,
    Swarm tab,
    String conversationId, {
    bool newProject = false,
    // + New agent (task #4196): a Member in its own chat, or the Lead of a
    // new project, chosen in the form.
    bool newAgent = false,
  }) async {
    final account = app.currentUser?.id;
    if (account == null) {
      throw const SuperTabFailure('SIGNED_OUT', 'Sign in to create a Swarm.');
    }
    // + New agent keeps one request per Swarm, whichever tab opened it (hotfix #4647: one per tab piled up, and each
    // had to be discarded). A request an older Desktop kept under its tab moves to it.
    final perTab = 'super_tab.launch.$account.${tab.id}.$conversationId';
    final key = newAgent && tab.superTabId != null
        ? 'super_tab.launch.$account.swarm:${tab.superTabId}.$conversationId'
        : perTab;
    var raw = await app.superTabs.storage.read(key);
    if (raw == null && key != perTab) {
      raw = await app.superTabs.storage.read(perTab);
      if (raw != null) {
        await app.superTabs.storage.write(key, raw);
        await app.superTabs.storage.delete(perTab);
      }
    }
    if (app.currentUser?.id != account) {
      throw const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
    }
    // A project with no coordinator gets its Product Manager from New Harness
    // in its chat, the person's first message going to it (River, 11-03,
    // #2458: Tony's Personal project had none and joined a worker instead).
    SuperTabSnapshot? snapshot;
    if (raw == null && tab.superTabId != null && !newProject && !newAgent) {
      snapshot = await app.superTabs.readSnapshot(tab.superTabId!);
      if (app.currentUser?.id != account) {
        throw const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
      }
    }
    final unled = snapshot?.projectFor(conversationId);
    final coordinator =
        unled != null &&
        unled.leadConversationId == conversationId &&
        snapshot!.leadOf(unled.id) == null;
    final saved = raw == null && newAgent
        ? <String, dynamic>{
            'operationId': superTabOperationId(),
            'joinId': superTabOperationId(),
            'tabId': tab.superTabId,
            'conversationId': conversationId,
            'newAgent': true,
            'agentKind': 'member',
            'lead': false,
            'newSwarm': false,
            'newProject': false,
            'visibility': 'public',
          }
        : raw == null
        ? <String, dynamic>{
            'operationId': superTabOperationId(),
            'joinId': superTabOperationId(),
            'tabId': tab.superTabId,
            'conversationId': conversationId,
            'lead': tab.superTabId == null || newProject || coordinator,
            'newSwarm': tab.superTabId == null,
            'newProject': newProject,
            // It leads a project already there: its and the Swarm's names
            // and visibility stay as they are.
            if (coordinator) ...{
              'coordinator': true,
              'title': unled.name,
              'coordinatorName': snapshot.coordinatorNameOf(unled.id),
            },
            'visibility': 'public',
            if (!newProject) 'projectId': 'lead',
          }
        : superTabMap(jsonDecode(raw));
    final launch = SuperTabLaunch._(app, tab.id, account, key, saved);
    final recovering =
        saved['phase'] == 'starting' || saved['phase'] == 'joining';
    // An agent joining a project with instructions names its role; an older
    // Swarm (no coordinator name on the project) has no such field.
    List<String>? roleSuggestions;
    if (saved['lead'] != true &&
        saved['newAgent'] != true &&
        tab.superTabId != null) {
      final project =
          (snapshot ?? await app.superTabs.readSnapshot(tab.superTabId!))
              .projectFor(conversationId);
      if (project != null && project.hasInstructions) {
        roleSuggestions = await launch.readRoleSuggestions(
          tab.superTabId!,
          project,
        );
      }
    }
    // A project's Product Manager starts on one of the Swarm's machines.
    // Read from the open Swarm when there is one; each submit reads afresh.
    List<LeadMachine>? leadMachines;
    LeadModelList? leadModels;
    List<String>? newRepositoryOwners;
    if (saved['newProject'] == true && tab.superTabId != null) {
      final id = tab.superTabId!;
      final policy = launch.readRoutingPolicy(id);
      final snapshot =
          app.superTabs.peek(id)?.snapshot ??
          await app.superTabs.readSnapshot(id);
      leadMachines = launch.leadMachinesOf(snapshot);
      newRepositoryOwners = await launch.newRepositoryOwnersOf(snapshot);
      leadModels = LeadModelList.of(await policy);
    }
    late final HarnessLaunchIntegration integration;
    integration =
        HarnessLaunchIntegration(
            startInSwarm: leadMachines == null
                ? null
                : (start) async {
                    if (saved['projectPrepared'] != true &&
                        saved['creationRequest'] == null) {
                      saved['visibility'] =
                          integration.projectVisibility ?? 'public';
                    }
                    try {
                      // A start already sent is repeated as it is: the server may
                      // have committed it and taken the machine's last slot, so
                      // its answer decides, not a fresh check.
                      if (saved['leadStartRequest'] == null) {
                        await launch.recheckLeadMachine(
                          integration,
                          start.machineId,
                          engine: start.engine,
                        );
                      }
                      await launch.startInSwarm(start);
                    } on SuperTabFailure catch (failure) {
                      // As prepare: a request validation refused leaves no project.
                      if (saved['projectPrepared'] != true &&
                          const {
                            'VALIDATION_ERROR',
                            'UPDATE_REQUIRED',
                          }.contains(failure.code)) {
                        saved.remove('creationRequest');
                        saved['operationId'] = superTabOperationId();
                        await launch.persist();
                      }
                      rethrow;
                    } finally {
                      integration.projectVisibilityLocked =
                          saved['projectPrepared'] == true ||
                          saved['creationRequest'] != null;
                    }
                  },
            checkRepositoryOwner: launch.checkRepositoryOwner,
            createRepository: leadMachines == null
                ? null
                : (ask, task) async {
                    if (saved['projectPrepared'] != true &&
                        saved['creationRequest'] == null) {
                      saved['visibility'] =
                          integration.projectVisibility ?? 'public';
                    }
                    try {
                      return await launch.createRepository(ask, task);
                    } finally {
                      integration.projectVisibilityLocked =
                          saved['projectPrepared'] == true ||
                          saved['creationRequest'] != null;
                    }
                  },
            checkRepositoryAgain: launch.checkRepositoryAgain,
            creationId: saved['creationId'] as String? ?? superTabOperationId(),
            initialTask: saved['initialMessage'] as String?,
            swarmRole: saved['lead'] == true ? 'lead' : 'dev',
            swarmSkillMode: saved['skillMode'] as String? ?? 'orchestration',
            roleSuggestions: roleSuggestions,
            roleName: roleSuggestions == null
                ? null
                : saved['roleName'] as String?,
            actionLabel: saved['newAgent'] == true
                ? 'New agent'
                : saved['newProject'] == true
                ? 'New Project'
                : saved['lead'] == true && saved['coordinator'] != true
                ? 'New Swarm'
                : 'New Harness',
            // Routing reads quota for Claude Code and Codex only, so a Lead is one
            // of them; the agents it starts may be anything.
            engines: saved['lead'] == true || saved['newAgent'] == true
                ? const ['claude', 'codex']
                : null,
            agentKind: saved['newAgent'] == true
                ? saved['agentKind'] as String?
                : null,
            ownMachinesOnly: saved['newAgent'] == true,
            // + New agent's Product Manager makes a project too (audit
            // finding 14); the form shows the choice only while it is chosen.
            projectVisibility:
                saved['newAgent'] == true ||
                    saved['lead'] == true && saved['coordinator'] != true
                ? saved['visibility'] as String? ?? 'public'
                : null,
            projectVisibilityLocked:
                saved['projectPrepared'] == true ||
                saved['creationRequest'] != null,
            prepare: (machine, task, engine) async {
              // The choice is what the first request is sent as, and stays.
              if (saved['newAgent'] == true && !integration.agentKindLocked) {
                final lead = integration.agentKind == 'lead';
                saved['agentKind'] = lead ? 'lead' : 'member';
                saved['lead'] = lead;
                saved['newProject'] = lead;
                saved['newAgentAt'] ??= DateTime.now().millisecondsSinceEpoch;
                integration.agentKindLocked = true;
              }
              if (integration.leadMachines != null) {
                await launch.recheckLeadMachine(
                  integration,
                  machine,
                  engine: engine,
                );
              }
              if (integration.roleSuggestions != null) {
                final name = integration.roleName?.trim() ?? '';
                if (name.length > 40) {
                  throw const SuperTabFailure(
                    'ROLE_INVALID',
                    'A role name is at most 40 characters.',
                  );
                }
                if (name.isEmpty) {
                  saved.remove('roleName');
                } else {
                  saved['roleName'] = name;
                }
              }
              if (saved['projectPrepared'] != true &&
                  saved['creationRequest'] == null) {
                saved['visibility'] = integration.projectVisibility ?? 'public';
              }
              try {
                final prompt = await launch.prepare(machine, task, engine);
                integration.swarmSkillMode =
                    saved['skillMode'] as String? ?? 'orchestration';
                integration.swarmRole = saved['lead'] == true ? 'lead' : 'dev';
                return prompt;
              } on SuperTabFailure catch (failure) {
                if (failure.code == 'PROJECT_UNAVAILABLE' && launch.started) {
                  integration.discard = launch.discard;
                }
                // Validation rejects the request before applying it. A lost response
                // stays locked so retrying cannot create a second project or change
                // the visibility of a project that may already exist.
                if (saved['projectPrepared'] != true &&
                    const {
                      'VALIDATION_ERROR',
                      'UPDATE_REQUIRED',
                    }.contains(failure.code)) {
                  saved.remove('creationRequest');
                  saved['operationId'] = superTabOperationId();
                  await launch.persist();
                }
                rethrow;
              } finally {
                integration.projectVisibilityLocked =
                    saved['projectPrepared'] == true ||
                    saved['creationRequest'] != null;
              }
            },
            beforeSubmit: (machine, receipt) async {
              saved['machineId'] = machine;
              saved['creationId'] = receipt;
              saved['phase'] = 'starting';
              saved['engine'] = integration.engine;
              saved['folder'] = integration.folder;
              await launch.persist();
            },
            complete: (machine, harnessId) async {
              if (integration.launchModelRefused case final refused?) {
                saved['launchRefused'] = {
                  'model': refused.model,
                  'effort': refused.effort,
                };
              }
              try {
                await launch.join(machine, harnessId);
              } catch (_) {
                // The harness exists and its join did not finish: the journal now
                // holds it, and the person may rather drop it than retry.
                integration.discard = launch.discard;
                rethrow;
              }
            },
            stageAttachments: launch.stageAttachments,
            needsAttachmentReview: () => saved['filesState'] == 'sending',
            resolveAttachments: (resend) async {
              launch.checkAccount();
              saved['filesState'] = resend ? 'pending' : 'delivered';
              await launch.persist();
              await launch.resume();
            },
            resume: recovering
                ? () async {
                    try {
                      await launch.resume();
                    } on SuperTabFailure catch (failure) {
                      if (failure.code == 'CREATION_FAILED' ||
                          failure.code == 'CREATION_STOPPED') {
                        // Nothing of that start joins: the next one is a new agent, with a join of its own
                        // (hotfix #4709).
                        saved
                          ..remove('phase')
                          ..remove('creationId')
                          ..remove('harnessId')
                          ..remove('command')
                          ..['joinId'] = superTabOperationId();
                        await launch.persist();
                        integration.pending = false;
                        integration.resume = null;
                      }
                      rethrow;
                    }
                  }
                : null,
          )
          ..pending = recovering
          ..agentKindLocked =
              saved['newAgent'] == true && saved['newAgentAt'] != null
          ..leadMachines = leadMachines
          ..leadModels = leadModels
          ..newRepositoryOwners = newRepositoryOwners;
    if (recovering) {
      integration
        ..machineId = saved['machineId'] as String?
        ..engine = saved['engine'] as String?
        ..folder = saved['folder'] as String?
        ..pendingNote = saved['phase'] == 'joining'
            ? launch.startedNote
            : launch.waitingNote
        ..discard = launch.discard;
    }
    return integration;
  }

  /// A native start was asked for, so the journal must outlive this form.
  bool get started =>
      saved['phase'] == 'starting' || saved['phase'] == 'joining';

  /// The coordinator as the project calls it: never "Lead" on screen (Naming
  /// System; River, #2458).
  String get who => saved['lead'] == true
      ? saved['coordinatorName'] as String? ?? kDefaultCoordinatorName
      : 'harness';
  String get machineName {
    final machine = saved['machineId'] as String?;
    if (machine == null) return 'the machine';
    return machineNameOf(machine);
  }

  String machineNameOf(String machine) =>
      app.stateOf(machine)?.machine.displayName ?? machine;

  /// What a request whose harness stopped before it joined says (hotfix #4709): Start begins it again.
  SuperTabFailure get stopped => SuperTabFailure(
    'CREATION_STOPPED',
    'The $who stopped on $machineName before it joined. Press Start to try again.',
  );

  String get startedNote =>
      'The $who started on $machineName. Check status to add it to the project.';
  String get waitingNote {
    final title =
        saved['title'] ??
        (saved['newProject'] == true ? 'New project' : 'Swarm');
    return saved['lead'] == true
        ? 'Waiting for $machineName to start the $who for “$title”.'
        : 'Waiting for $machineName to start the harness.';
  }

  /// The Swarm's machines, one row per computer, then the person's others,
  /// best first. A new project's Product Manager starts on any of them (Ken,
  /// 10-29): a teammate's Mac runs it in its Harness Team account when that
  /// takes it now, else itself, as its owner (backend leadStart.ts).
  List<LeadMachine> leadMachinesOf(SuperTabSnapshot snapshot, {DateTime? now}) {
    final at = (now ?? DateTime.now()).millisecondsSinceEpoch;
    // A machine reports readiness and resources only once it has them.
    Map<String, dynamic> part(Object? value) =>
        value is Map ? superTabMap(value) : const {};
    LeadMachine row(String id, Map<String, dynamic> pool) {
      final reading = snapshot.readingPoolOf(id, accountId) ?? pool;
      final observation = part(reading['observation']);
      // As Add machine and the Buddy picker name it ("Studio", not "Studio.local").
      final name = superTabMachineName(pool['name'] as String? ?? id);
      final own = pool['contributorId'] == accountId;
      final connected = app.stateOf(id) != null;
      // Its host says it can start a Product Manager (backend leadStart.ts).
      final capable =
          (observation['capabilities'] as List?)?.contains('leadStart') == true;
      // Another person's Mac runs one in its Harness Team account when that
      // takes it now, else itself; a Team account listed as its own machine
      // only in 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,
            };
      bool fresh(Map<String, dynamic> observation) =>
          switch (observation['receivedAt']) {
            final num received =>
              at - received < kSuperTabMachineOfflineAfter.inMilliseconds,
            _ => false,
          };
      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' &&
          (mac['capabilities'] as List?)?.contains('leadStart') == true;
      // On a teammate's machine the server decides, by engine, where it runs
      // (backend leadStart.ts leadChoices), as the start itself does: Desktop
      // shows that rather than working it out (security reviews 1 and 2 of
      // #2228). A backend from before sends none.
      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 kLeadEngines) ?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.machines
                          .where((m) => m['machineId'] == shownHost)
                          .firstOrNull ??
                      pool)
          : teamReading && !team
          ? pool
          : reading;
      final hostReading = part(host['observation']);
      final online = fresh(hostReading);
      final running = hostReading['runningHarnessIds'];
      final max = host['maxAgents'];
      final checkouts = part(hostReading['readiness'])['checkouts'];
      final device = part(hostReading['resources'])['deviceType'];
      // The engines it can run there, read where it would run.
      final engineRefusals = server
          ? {
              for (final engine in kLeadEngines)
                if (refused[engine] ?? (decided[engine] == null ? '' : null)
                    case final why?)
                  engine: why.isEmpty ? 'Not offered by this Swarm' : why,
            }
          : leadEngineRefusals(
              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?,
                    ),
              },
              // Read by servers with engine health (#2192); absent before.
              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,
              },
            );
      return LeadMachine(
        id: id,
        name: name,
        online: online,
        // The server's count: it also holds pending starts and the Team
        // account sharing a Mac. A backend 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),
          ),
        },
        repositories: {
          if (checkouts is List)
            for (final checkout in checkouts)
              ?leadRepositoryKey(switch (part(checkout)['repository']) {
                final String repository => repository,
                _ => null,
              }),
        },
        // The Swarm's clone of each project there: its folder in the
        // machine's Swarm folder, in that machine's own path style.
        folders: {
          if (pool['cwd'] case final String root when checkouts is List)
            for (final checkout in checkouts.map(part))
              if ((
                    leadRepositoryKey(switch (checkout['repository']) {
                      final String repository => repository,
                      _ => null,
                    }),
                    checkout['folder'],
                  )
                  case (final String key, final String folder))
                key: (root.contains('\\') ? p.windows : p.posix).join(
                  root,
                  folder,
                ),
        },
        maySleep:
            superTabMachineSymbol(device is String ? device : null) ==
            'laptopcomputer',
        own: own,
        owner: own
            ? null
            : snapshot.people
                  .where((person) => person.id == pool['contributorId'])
                  .firstOrNull,
        native: own && connected,
        team: server ? shownHost != null && shownHost != id : team,
        engineRefusals: engineRefusals,
        unavailable: snapshot.paused
            ? kLeadSwarmPaused
            : own
            ? (connected
                  ? (pool['paused'] == true ? 'Paused in this Swarm' : null)
                  : capable
                  ? null
                  : 'Not connected to this computer')
            // 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 listed = [
      for (final pool in snapshot.machines)
        if (pool['machineId'] case final String id
            when snapshot.placeOf(id) == id && pool['removal'] == null)
          row(id, pool),
    ];
    return rankLeadMachines([
      ...listed,
      // A person's start may still name a machine of theirs the Swarm does
      // not list (backend agent.start), as New Project always could.
      for (final state in app.machineStates.values)
        if (!state.belongsToOtherAccount &&
            !listed.any((m) => m.id == state.machine.machineId))
          LeadMachine(
            id: state.machine.machineId,
            name: superTabMachineName(state.machine.displayName),
            online: !state.needsLink && !state.isOffline,
            freeAgents: null,
            inSwarm: false,
            unavailable: snapshot.paused ? kLeadSwarmPaused : null,
            // The Swarm reads nothing of it: this computer's own probe says
            // which engines are there. One that installs on Create runs.
            engineRefusals: leadEngineRefusals(
              readiness: {
                for (final engine in kLeadEngines)
                  if (state.engines[engine] case final known?)
                    engine: (
                      installed: known.installed || known.installable,
                      signedIn: known.signedIn,
                    ),
              },
            ),
          ),
    ], null);
  }

  /// The project document's role headings, less the coordinator's own. A read
  /// that fails leaves none: the field still takes any text.
  Future<List<String>> readRoleSuggestions(
    String tabId,
    SuperTabProject project,
  ) async {
    try {
      final answer = await app.superTabs.map(
        'GET',
        superTabInstructionsPath(tabId, project.id),
      );
      final text = answer['text'];
      if (text is! String) return const [];
      final own = {'pm', (project.coordinatorName ?? '').toLowerCase()};
      return [
        for (final name in superTabInstructionRoleNames(text))
          if (!own.contains(name.toLowerCase())) name,
      ];
    } catch (_) {
      return const [];
    }
  }

  /// The tab's routing-policy read as it answers ([LeadModelList.of] reads its
  /// `policy` and `catalog`), or null when it cannot be read: nothing is then
  /// ruled out by it.
  Future<Map<String, dynamic>?> readRoutingPolicy(String tabId) async {
    try {
      return await app.superTabs.map(
        'GET',
        '/api/super-tabs/$tabId/routing-policy',
      );
    } catch (_) {
      return null;
    }
  }

  /// Reads the Swarm again and refuses [machine] when it cannot take the
  /// Product Manager now: the list from when the form opened may be stale.
  /// With no fresh read nothing is created, since the machine is unchecked.
  Future<void> recheckLeadMachine(
    HarnessLaunchIntegration integration,
    String machine, {
    String? engine,
  }) async {
    final name =
        integration.leadMachines
            ?.where((m) => m.id == machine)
            .firstOrNull
            ?.name ??
        machineNameOf(machine);
    final SuperTabSnapshot fresh;
    try {
      fresh = await app.superTabs.readSnapshot(saved['tabId'] as String);
    } on SuperTabFailure catch (failure) {
      if (failure.code == 'ACCOUNT_CHANGED') rethrow;
      throw SuperTabFailure(
        'SWARM_UNREADABLE',
        'Couldn’t check $name for the Product Manager: ${failure.message} '
            'Try again.',
      );
    } catch (_) {
      throw SuperTabFailure(
        'SWARM_UNREADABLE',
        'Couldn’t check $name for the Product Manager: the Swarm didn’t '
            'answer. Try again.',
      );
    }
    checkAccount();
    integration.leadMachines = leadMachinesOf(fresh);
    checkLeadMachine(integration.leadMachines!, machine, engine: engine);
  }

  /// The upload a Swarm-started Product Manager's files take, in tests.
  @visibleForTesting
  static SuperTabUpload? uploadForTest;

  /// New Project's Product Manager started by the Swarm, not this Desktop
  /// (backend leadStart.ts): creates the project, posts the task and files
  /// to its chat, where such a Product Manager reads its request, and asks
  /// the Swarm to start it on [LeadSwarmStart.machineId]. Each step keeps
  /// its receipt in the journal, so a retry repeats none of them.
  Future<void> startInSwarm(LeadSwarmStart start) async {
    checkAccount();
    saved['initialMessage'] = start.task;
    await _createProject(start.task);
    final tabId = saved['tabId'] as String;
    final conversationId = saved['conversationId'] as String;
    Future<Map<String, dynamic>> send(String operationId, Map command) =>
        app.superTabs.map(
          'POST',
          '/api/super-tabs/$tabId/commands',
          body: {'operationId': operationId, 'command': command},
        );
    if (saved['taskPosted'] != true &&
        (start.task.isNotEmpty || start.files.isNotEmpty)) {
      // Written once, with its files' ids: a retry after a lost reply sends
      // this very request, so nothing is uploaded again.
      if (saved['taskRequest'] == null) {
        final upload = uploadForTest ?? app.superTabs.upload;
        final ids = [
          for (final file in start.files)
            superTabMap(
                  (await upload(
                    tabId: tabId,
                    conversationId: conversationId,
                    name: file.name,
                    mime: mimeForName(file.name),
                    file: file,
                    cancel: CancelToken(),
                    onProgress: (_) {},
                  ))['attachment'],
                )['id']
                as String,
        ];
        checkAccount();
        saved['taskRequest'] = {
          'operationId': superTabOperationId(),
          'command': {
            'type': 'message.send',
            'conversationId': conversationId,
            'text': start.task,
            'replyTo': null,
            'recipientIds': const <String>[],
            if (ids.isNotEmpty) 'attachmentIds': ids,
          },
        };
        await persist();
      }
      await _replay('taskRequest');
      saved['taskPosted'] = true;
      saved.remove('taskRequest');
      await persist();
    }
    // Kept as first sent until the Swarm answers it: after an unclear failure
    // a retry repeats it, perhaps already committed, rather than asking again.
    saved['leadStartRequest'] ??= {
      'operationId': superTabOperationId(),
      'command': {
        'type': 'lead.start',
        'projectId': saved['projectId'],
        'machineId': start.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': start.engine,
        'repositoryUrl': ?start.repositoryUrl,
      },
    };
    await persist();
    await _replay('leadStartRequest');
    final title = start.title ?? 'New project';
    saved['title'] = title;
    await persist();
    await send('${saved['joinId']}-name', {
      'type': 'project.rename',
      'projectId': saved['projectId'],
      'name': title,
    });
    final controller = await app.superTabs.open(tabId);
    await controller.refresh();
    checkAccount();
    controller.select(conversationId);
    await app.superTabs.storage.delete(key);
  }

  /// Opens GitHub's sign-in in the system browser, in tests a fake.
  @visibleForTesting
  static Future<bool> Function(Uri url)? openLinkForTest;

  /// New Repository's organizations for New Project (task #3374): the
  /// Swarm's own, or null when this server cannot create repositories, which
  /// one organization's check tells (an older server answers 404).
  Future<List<String>?> newRepositoryOwnersOf(SuperTabSnapshot snapshot) async {
    final owners = newRepositoryOwners(snapshot.projects);
    if (owners.isEmpty) return owners;
    try {
      final check = await checkRepositoryOwner(owners.first);
      return check.state == 'not-configured' ? null : owners;
    } catch (_) {
      // Unanswered says nothing of the server: the prompt checks again.
      return owners;
    }
  }

  /// Whether [owner] lets Harness create a repository there.
  Future<NewRepositoryOwnerCheck> checkRepositoryOwner(String owner) async {
    checkAccount();
    try {
      final answer = await app.superTabs.map(
        'GET',
        '/api/super-tabs/${saved['tabId']}/github/owners/'
            '${Uri.encodeComponent(owner)}',
      );
      checkAccount();
      return NewRepositoryOwnerCheck.read(owner, answer);
    } on SuperTabFailure catch (failure) {
      if (failure.statusCode == 404 && failure.code != 'NOT_AVAILABLE') {
        return NewRepositoryOwnerCheck('not-configured', owner: owner);
      }
      rethrow;
    }
  }

  /// The Swarm a create waits on, which Check again reads.
  SuperTabController? _repositoryWait;

  Future<void> checkRepositoryAgain() async => _repositoryWait?.refresh();

  /// New Project's New Repository (task #3374, design
  /// docs/plans/2026-11-05-new-repository-design.md): creates the project
  /// once, asks the server for the person's GitHub sign-in, opens it in their
  /// browser, and waits for the outcome on the project in the Swarm state.
  /// What was made stays in the journal, so a retry never creates it again;
  /// one after a failure asks anew.
  Future<NewRepositoryCreated> createRepository(
    NewRepositoryAsk ask,
    String task,
  ) async {
    checkAccount();
    if (saved['newRepository']
        case {
          'slug': final String slug,
          'repositoryUrl': final String url,
          'reachable': final bool reachable,
        }
        when slug == ask.slug) {
      return NewRepositoryCreated(url, reachable: reachable);
    }
    saved['initialMessage'] = task;
    await _createProject(task);
    final tabId = saved['tabId'] as String;
    final projectId = saved['projectId'] as String;
    final Map<String, dynamic> link;
    try {
      link = await app.superTabs.map(
        'POST',
        '/api/super-tabs/$tabId/projects/$projectId/github/repository',
        body: {'owner': ask.owner, 'name': ask.name, 'private': ask.private},
      );
    } on SuperTabFailure catch (failure) {
      throw await _repositoryRefusal(failure, ask);
    }
    checkAccount();
    final at = (link['at'] as num).toInt();
    final signIn = switch (link['authorizeUrl']) {
      final String url => Uri.tryParse(url),
      _ => null,
    };
    // Only GitHub's own page is opened (security review 1 of #3207).
    if (signIn == null || !newRepositorySignInLink(signIn)) {
      throw const SuperTabFailure(
        'GITHUB_LINK_REFUSED',
        kNewRepositoryNotGitHub,
      );
    }
    final open =
        openLinkForTest ??
        (Uri url) => launchUrl(url, mode: LaunchMode.externalApplication);
    if (!await open(signIn)) {
      throw const SuperTabFailure(
        'GITHUB_NOT_OPENED',
        'Couldn’t open GitHub. Try again.',
      );
    }
    final made = await _repositoryOutcome(tabId, projectId, ask, at);
    saved['newRepository'] = {
      'slug': ask.slug,
      'repositoryUrl': made.repositoryUrl,
      'reachable': made.reachable,
    };
    await persist();
    return made;
  }

  /// The ask's refusal before any sign-in, in the design's words.
  Future<SuperTabFailure> _repositoryRefusal(
    SuperTabFailure failure,
    NewRepositoryAsk ask,
  ) async => switch (failure.code) {
    'GITHUB_APP_NOT_INSTALLED' => NewRepositoryRefusal(
      failure.code,
      newRepositoryNotInstalled(ask.owner),
      installUrl: await checkRepositoryOwner(ask.owner)
          .then((check) => check.installUrl, onError: (Object _) => null),
    ),
    'GITHUB_APP_PERMISSIONS' => NewRepositoryRefusal(
      failure.code,
      newRepositoryNotAccepted(ask.owner),
    ),
    'GITHUB_APP_NOT_CONFIGURED' || 'GITHUB_APPROVAL_NOT_CONFIGURED' =>
      NewRepositoryRefusal(failure.code, kNewRepositoryUnavailable),
    'REPOSITORY_NAME' => NewRepositoryRefusal(
      failure.code,
      newRepositoryNameProblem(ask.name) ?? failure.message,
    ),
    _ => failure,
  };

  /// What the project's `repositoryCreation` says of the ask made at [at], as
  /// the open Swarm syncs it: nothing polls, and Check again reads it once.
  Future<NewRepositoryCreated> _repositoryOutcome(
    String tabId,
    String projectId,
    NewRepositoryAsk ask,
    int at,
  ) async {
    final controller = await app.superTabs.open(tabId);
    checkAccount();
    // An open Swarm may not have read the project made just now.
    await controller.refresh();
    checkAccount();
    final done = Completer<NewRepositoryOutcome>();
    void read() {
      final snapshot = controller.snapshot;
      if (done.isCompleted || snapshot == null) return;
      final project = snapshot.projects
          .where((p) => p.id == projectId)
          .firstOrNull;
      final outcome = project == null
          ? const NewRepositoryFailed(kNewRepositoryProjectGone)
          : newRepositoryOutcome(
              project.repositoryCreation,
              ask,
              at: at,
              now: DateTime.now(),
            );
      if (outcome is! NewRepositoryWaiting) done.complete(outcome);
    }

    _repositoryWait = controller;
    controller.addListener(read);
    // Only the clock moves an ask past its link's life: this reads nothing.
    final clock = Timer.periodic(const Duration(seconds: 15), (_) => read());
    read();
    try {
      return switch (await done.future) {
        final NewRepositoryCreated made => made,
        NewRepositoryFailed(:final message) => throw SuperTabFailure(
          'REPOSITORY_NOT_CREATED',
          message,
        ),
        NewRepositoryWaiting() => throw StateError('Still waiting'),
      };
    } finally {
      clock.cancel();
      controller.removeListener(read);
      if (identical(_repositoryWait, controller)) _repositoryWait = null;
    }
  }

  /// Sends the journal's request [key] exactly as it was first written: the
  /// server answers a repeated operation with its receipt, and refuses one
  /// whose request changed. Only a definite refusal drops it, so the next
  /// attempt (perhaps to another machine) is a new request; any other failure
  /// may have been committed and keeps it.
  Future<void> _replay(String key) async {
    try {
      await app.superTabs.map(
        'POST',
        '/api/super-tabs/${saved['tabId']}/commands',
        body: superTabMap(saved[key]),
      );
    } on SuperTabFailure catch (failure) {
      if (_refusedOutright(failure)) {
        saved.remove(key);
        await persist();
      }
      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;

  /// Refuses a machine the list cannot start the Product Manager on now.
  /// Refuses [machine] when it cannot start the Product Manager now, with
  /// [engine] when it is known.
  void checkLeadMachine(
    List<LeadMachine> machines,
    String machine, {
    String? engine,
  }) {
    final chosen = machines.where((m) => m.id == machine).firstOrNull;
    if (chosen == null) {
      throw const SuperTabFailure(
        'MACHINE_NOT_LISTED',
        'Choose one of this Swarm’s machines.',
      );
    }
    final refusal = engine == null ? null : chosen.engineRefusals[engine];
    if (chosen.startable && refusal == null) return;
    throw SuperTabFailure(
      'MACHINE_UNAVAILABLE',
      chosen.unavailable != null
          ? '${chosen.name}: ${chosen.unavailable}. Choose another machine.'
          : !chosen.online
          ? '${chosen.name} is offline. Choose another machine.'
          : chosen.leadEngines.isEmpty
          ? '${chosen.name}: ${leadMachineDetail(chosen, null)}. '
                'Choose another machine.'
          : !chosen.startable
          ? '${chosen.name} has no free agents. Choose another machine.'
          : '${chosen.name} can’t run ${leadEngineLabel(engine!)}: $refusal. '
                'Choose another engine.',
    );
  }

  void checkAccount() {
    if (app.currentUser?.id != accountId) {
      throw const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
    }
  }

  Future<void> persist() async {
    checkAccount();
    // A discarded request stays gone: a write still on its way must not bring it back (hotfix #4647).
    if (_dropped) return;
    await app.superTabs.storage.write(key, jsonEncode(saved));
    checkAccount();
  }

  /// A Personal start whose pane would need a tab the full desk cannot hold
  /// is refused here, before any agent runs (task #3099). A start already
  /// asked for is not: its agent may be running. A Product Manager started
  /// on a Swarm machine ([startInSwarm]) puts no pane on this desk, so it
  /// needs no tab.
  void refuseFullDesk() {
    if (started) return;
    final refusal = PersonalProjects.of(app).startRefusal(
      saved['tabId'] as String?,
      saved['conversationId'] as String?,
      newProject:
          saved['newProject'] == true && saved['projectPrepared'] != true,
    );
    if (refusal != null) {
      // Said in the log by its code alone: how often a full desk stops a
      // start is what warns that the desk's 24 tabs are near.
      appLog.warn('super-tabs', 'Personal start refused (TABS_FULL)');
      throw SuperTabFailure('TABS_FULL', refusal);
    }
  }

  Future<String> prepare(String machine, String task, [String? engine]) async {
    checkAccount();
    refuseFullDesk();
    if (app.stateOf(machine)?.belongsToOtherAccount == true) {
      throw const SuperTabFailure(
        'CONTRIBUTION_REQUIRED',
        'Choose one of your machines. To use another person’s machine in this Swarm, ask its owner to add the machine or an agent.',
      );
    }
    saved['initialMessage'] = task;
    saved['machineId'] = machine;
    await persist();
    if (saved['tabId'] == null) {
      saved['creationRequest'] ??= {
        'operationId': saved['operationId'],
        'name': 'Swarm',
        'projectVisibility': saved['visibility'] ?? 'public',
      };
      await persist();
      final created = await app.superTabs.map(
        'POST',
        '/api/super-tabs',
        body: superTabMap(saved['creationRequest']),
      );
      saved['tabId'] = created['id'];
      saved['projectPrepared'] = true;
      app.superTabs.deferTabDiscovery(saved['tabId'] as String);
      await persist();
    }
    await _createProject(task);
    await _openMemberChat(machine, engine);
    app.superTabs.deferTabDiscovery(saved['tabId'] as String);
    // Revalidate a journal's destination before native submission. A project
    // deleted on another computer must not leave an unattached native session.
    final snapshot = await app.superTabs.readSnapshot(saved['tabId'] as String);
    checkAccount();
    final member = saved['newAgent'] == true && saved['lead'] != true;
    if (member) await _ensureMemberChat(snapshot, machine, engine);
    final conversationId = saved['conversationId'] as String;
    if (!member && snapshot.conversation(conversationId) == null) {
      if (started) throw projectUnavailable;
      // Nothing can still be starting: reopening New Project should get a
      // fresh destination instead of loading this deleted project forever.
      await app.superTabs.storage.delete(key);
      checkAccount();
      throw const SuperTabFailure(
        'PROJECT_UNAVAILABLE',
        'This project is no longer available. Close this form and create a new project.',
      );
    }
    saved['skillMode'] =
        snapshot.projectFor(conversationId)?.skillMode ?? 'orchestration';
    // A role goes only to a Swarm that still has instructions: an older
    // backend's strict agent.add refuses the key.
    if (snapshot.projectFor(conversationId)?.hasInstructions != true) {
      saved.remove('roleName');
    }
    final prompt = superTabLaunchPrompt(
      tabId: saved['tabId'] as String,
      conversationId: saved['conversationId'] as String,
      lead: saved['lead'] == true,
    );
    saved['launchPrompt'] = prompt;
    await persist();
    return prompt;
  }

  /// A new project's creation, once: its receipt stays in the journal.
  Future<void> _createProject(String task) async {
    if (saved['newProject'] == true && saved['projectPrepared'] != true) {
      saved['creationRequest'] ??= {
        'operationId': saved['operationId'],
        'command': {
          'type': 'project.create',
          'name': 'New project',
          'visibility': saved['visibility'] ?? 'public',
          'brief': String.fromCharCodes(task.runes.take(4000)),
        },
      };
      await persist();
      final created = await app.superTabs.map(
        'POST',
        '/api/super-tabs/${saved['tabId']}/commands',
        body: superTabMap(saved['creationRequest']),
      );
      final result = superTabMap(created['result']);
      saved['projectId'] = result['projectId'];
      saved['conversationId'] = result['conversationId'];
      saved['projectPrepared'] = true;
      await persist();
    }
  }

  /// A Member's own chat, once (task #4196): opened with no server start, as
  /// this Desktop starts the agent itself. Its receipt stays in the journal.
  Future<void> _openMemberChat(String machine, String? engine) async {
    if (saved['newAgent'] != true ||
        saved['lead'] == true ||
        saved['chatPrepared'] == true) {
      return;
    }
    final base = engine ?? saved['engine'] as String? ?? 'claude';
    if (saved['chatRequest'] == null) {
      // The first free of Claude Code, Claude Code 2, …: two agents of one
      // engine read apart in the left pane.
      final tab = saved['tabId'] as String;
      final snapshot =
          app.superTabs.peek(tab)?.snapshot ??
          await app.superTabs.readSnapshot(tab);
      checkAccount();
      final taken = {
        for (final agent in snapshot.agents) ...[
          agent.name,
          ?agent.displayName,
        ],
      };
      final label = base == 'codex' ? 'Codex' : 'Claude Code';
      var name = label;
      for (var n = 2; taken.contains(name); n++) {
        name = '$label $n';
      }
      saved['chatRequest'] = {
        // A chat opened again after the last one went has an operation of its own: the same one would answer with the gone
        // chat's receipt (hotfix #4647).
        'operationId': switch (saved['chatAgain']) {
          final int again => '${saved['operationId']}-chat-$again',
          _ => '${saved['operationId']}-chat',
        },
        'command': {
          'type': 'agent.new',
          'kind': 'regular',
          'machineId': machine,
          'engine': base,
          'name': name,
          'local': true,
        },
      };
    }
    await persist();
    final Map<String, dynamic> created;
    try {
      created = await app.superTabs.map(
        'POST',
        '/api/super-tabs/${saved['tabId']}/commands',
        body: superTabMap(saved['chatRequest']),
      );
    } on SuperTabFailure catch (failure) {
      if (_refusedOutright(failure)) {
        saved.remove('chatRequest');
        await persist();
      }
      // A backend from before local Members refuses the field it does not know.
      if (failure.code == 'VALIDATION_ERROR') {
        throw const SuperTabFailure(
          'UPDATE_REQUIRED',
          'Update Harness to start a Member from here.',
        );
      }
      rethrow;
    }
    saved['conversationId'] = superTabMap(created['result'])['conversationId'];
    saved['chatPrepared'] = true;
    await persist();
  }

  /// A Member's own chat (hotfix #4647): a Swarm's first read can leave a quiet chat out, so only a read of the chat
  /// says whether it is gone. Gone, a fresh one opens: a Member has no project to lose, and the person is never left with
  /// nothing to do but discard. [snapshot] is read when not given.
  Future<void> _ensureMemberChat(
    SuperTabSnapshot? snapshot,
    String machine,
    String? engine,
  ) async {
    final chat = saved['conversationId'] as String?;
    if (chat == null) return;
    final read =
        snapshot ?? await app.superTabs.readSnapshot(saved['tabId'] as String);
    checkAccount();
    if (read.conversation(chat) != null || await _chatExists(chat)) return;
    saved
      ..remove('chatPrepared')
      ..remove('chatRequest')
      ..remove('conversationId')
      ..remove('command')
      ..['chatAgain'] = (saved['chatAgain'] as int? ?? 0) + 1;
    await persist();
    await _openMemberChat(machine, engine);
  }

  /// Whether the Swarm still has the chat [conversationId], by a read of the chat itself; a 404 or 403 says it is gone.
  Future<bool> _chatExists(String conversationId) async {
    try {
      await app.superTabs.map(
        'GET',
        '/api/super-tabs/${saved['tabId']}/conversations/'
            '${Uri.encodeComponent(conversationId)}/messages',
      );
      return true;
    } on SuperTabFailure catch (failure) {
      if (failure.statusCode == 404 || failure.statusCode == 403) return false;
      rethrow;
    }
  }

  // A started request's journal stays until the person discards it.
  static const memberChatUnavailable = SuperTabFailure(
    'PROJECT_UNAVAILABLE',
    'This agent’s chat is gone. Discard this request, then start the agent again.',
  );

  static const projectUnavailable = SuperTabFailure(
    'PROJECT_UNAVAILABLE',
    'This project is no longer available. Discard this request, then create a new project.',
  );

  Future<void> stageAttachments(
    List<HarnessAttachment> files,
    String prompt,
  ) async {
    checkAccount();
    saved['files'] = [
      for (final file in files)
        {'name': file.name, 'bytes': base64Encode(await file.readBytes())},
    ];
    saved['launchPrompt'] = prompt;
    saved['filesState'] = 'pending';
    await persist();
  }

  Future<void> complete(
    String machine,
    String harnessId, {
    Agent? recovered,
  }) async {
    checkAccount();
    // A resumed start joins the chat this journal holds: make sure it is still there (hotfix #4647). A first start's
    // prepare has just checked it.
    if (recovered != null &&
        saved['newAgent'] == true &&
        saved['lead'] != true) {
      await _ensureMemberChat(null, machine, saved['engine'] as String?);
    }
    saved['machineId'] = machine;
    saved['harnessId'] = harnessId;
    saved['phase'] = 'joining';
    final native =
        recovered ??
        app
            .stateOf(machine)
            ?.agents
            .where((a) => a.id == harnessId)
            .firstOrNull;
    if (native == null) {
      throw const SuperTabFailure(
        'AGENT_UNAVAILABLE',
        'Waiting for the new harness to appear on its machine.',
      );
    }
    // Its machine still lists it, but it is not running: adding it would give the Swarm an agent that never answers
    // (hotfix #4709).
    if (native.isStopped) throw stopped;
    // Whether it leads was read when the box opened. A project that got its
    // Product Manager since keeps it: agent.add would make this one its lead
    // (Hollis, review of #2803). This one was started as a PM, so it does not
    // join as a worker either; it keeps running, and its person decides.
    if (saved['coordinator'] == true) {
      final fresh = await app.superTabs.readSnapshot(saved['tabId'] as String);
      checkAccount();
      final project = fresh.projectFor(saved['conversationId'] as String);
      final lead = project == null ? null : fresh.leadOf(project.id);
      if (lead != null &&
          (lead.machineId != machine || lead.harnessId != harnessId)) {
        throw SuperTabFailure(
          'COORDINATOR_TAKEN',
          'Another $who joined this project while this one was starting. '
              'This one keeps running on $machineName: Discard request to '
              'leave it out of the project.',
        );
      }
    }
    final project = native.project ?? app.stateOf(machine)?.projectOf(native);
    saved['command'] ??= {
      'type': 'agent.add',
      'conversationId': saved['conversationId'],
      'machineId': machine,
      'harnessId': harnessId,
      'name': saved['lead'] == true ? 'Lead' : superTabAddName(native),
      'lead': saved['lead'],
      // A journal from an older Desktop keeps the id it chose.
      if (saved['roleId'] case final String roleId) 'roleId': roleId,
      if (saved['roleName'] case final String roleName) 'roleName': roleName,
      if (saved['lead'] == true && project != null)
        'project': {
          'cwd': project.root ?? project.cwd,
          'repositoryUrl': superTabRepositoryUrl(project.remote),
        },
      'configuration': {
        'engine': native.engine ?? '',
        'model': native.modelName,
        'effort': native.modelEffort,
        'contextWindow': null,
        'engineVersion': null,
      },
      if ((saved['initialMessage'] as String? ?? '').isNotEmpty)
        'initialMessage': saved['initialMessage'],
      // Its chat says it runs its engine's own model (backend agent.add).
      if (saved['lead'] == true && saved['launchRefused'] is Map)
        'launchRefused': saved['launchRefused'],
    };
    await persist();
    final tabId = saved['tabId'] as String;
    try {
      await app.superTabs.map(
        'POST',
        '/api/super-tabs/$tabId/commands',
        body: {'operationId': saved['joinId'], 'command': saved['command']},
      );
    } on SuperTabFailure catch (failure) {
      final command = saved['command'] as Map;
      if (failure.code != 'VALIDATION_ERROR' ||
          !command.containsKey('launchRefused')) {
        rethrow;
      }
      // A backend from before the note refuses the whole join for it, having
      // committed nothing: the join again without it, as a new operation.
      saved['command'] = Map.of(command)..remove('launchRefused');
      saved['joinId'] = '${saved['joinId']}-plain';
      await persist();
      await app.superTabs.map(
        'POST',
        '/api/super-tabs/$tabId/commands',
        body: {'operationId': saved['joinId'], 'command': saved['command']},
      );
    }
    // Waking the exact host starts only its authorized contributions. It is
    // safe to retry, and never grants machine access to the tab's members.
    await app.wakeSuperTabHost(machine);
    // A new Swarm or project takes its Lead's name; one already there keeps its own.
    if (saved['lead'] == true && saved['coordinator'] != true) {
      final name = Swarm.titleFor(native);
      final title =
          saved['title'] as String? ??
          (name == Swarm.defaultName ? 'New project' : name);
      saved['title'] = title;
      await persist();
      await app.superTabs.map(
        'POST',
        '/api/super-tabs/$tabId/commands',
        body: {
          'operationId': '${saved['joinId']}-name',
          'command': {
            'type': 'project.rename',
            'projectId': saved['projectId'] ?? 'lead',
            'name': title,
          },
        },
      );
      checkAccount();
      if (saved['newProject'] != true) {
        await app.superTabs.map(
          'POST',
          '/api/super-tabs/$tabId/commands',
          body: {
            'operationId': '${saved['joinId']}-swarm-name',
            'command': {
              'type': 'tab.rename',
              'name': saved['visibility'] == 'private' ? 'Swarm' : title,
            },
          },
        );
      }
    }
    final controller = await app.superTabs.open(tabId);
    await controller.refresh();
    checkAccount();
    final files = (saved['files'] as List? ?? []).map((value) {
      final file = superTabMap(value);
      return HarnessAttachment(
        file['name'] as String,
        base64Decode(file['bytes'] as String),
      );
    }).toList();
    if (files.isNotEmpty && saved['filesState'] != 'delivered') {
      if (saved['filesState'] == 'sending') {
        throw const SuperTabFailure(
          'FILES_UNCONFIRMED',
          'The harness started, but file delivery was interrupted. Open its terminal to check before sending the files or request again.',
        );
      }
      saved['filesState'] = 'sending';
      await persist();
      final problem = await app.deliverBackgroundAttachments(
        machineId: machine,
        agentId: harnessId,
        files: files,
        task: saved['launchPrompt'] as String,
      );
      checkAccount();
      if (problem != null) throw SuperTabFailure('FILES_UNCONFIRMED', problem);
      saved['filesState'] = 'delivered';
      saved.remove('files');
      await persist();
    }
    if (saved['lead'] == true &&
        saved['newProject'] != true &&
        saved['coordinator'] != true) {
      app.bindSuperTab(
        swarmId,
        tabId,
        saved['visibility'] == 'private' ? 'Swarm' : saved['title'] as String,
      );
    }
    // The pane goes to its project's own tab in Personal (task #3099). A
    // failure there never undoes the join: the agent is in its project.
    if (controller.snapshot?.projectFor(saved['conversationId'] as String)
        case final project?) {
      try {
        await PersonalProjects.of(app)
            .placeInProjectTab(controller, project.id, machine, harnessId);
      } catch (error) {
        appLog.warn(
          'super-tabs',
          'Personal project tab placement failed (${error.runtimeType})',
        );
      }
    }
    controller.select(saved['conversationId'] as String);
    // How long + New agent took to a running agent in its chat: the measure
    // that warns first if it slows again (task #4196). No names or ids.
    if (saved['newAgentAt'] case final int at) {
      final ms = DateTime.now().millisecondsSinceEpoch - at;
      appLog.info(
        'super-tabs',
        'New agent (${saved['agentKind']}) running in $ms ms',
      );
    }
    await app.superTabs.storage.delete(key);
  }

  /// [complete] in the person's words. The harness exists, so whatever went
  /// wrong is the join, which Check status retries with the same receipt.
  Future<void> join(
    String machine,
    String harnessId, {
    Agent? recovered,
  }) async {
    try {
      await complete(machine, harnessId, recovered: recovered);
    } on SuperTabFailure catch (failure) {
      // The backend no longer has the conversation: a Member's own chat has no project to create again (#4647).
      if (failure.code == 'NOT_FOUND') {
        throw saved['newAgent'] == true && saved['lead'] != true
            ? memberChatUnavailable
            : projectUnavailable;
      }
      if (const {
        'ACCOUNT_CHANGED',
        'AGENT_UNAVAILABLE',
        'CREATION_STOPPED',
        'COORDINATOR_TAKEN',
        'FILES_UNCONFIRMED',
      }.contains(failure.code)) {
        rethrow;
      }
      throw _joinFailed(failure);
    } catch (failure) {
      throw _joinFailed(failure);
    }
  }

  /// The join's failure in the person's words: what happened, and what to do.
  /// A server's own error is never a reason to give up on the harness, and a
  /// refusal names the server's reason (Tony, #2458: "An internal server error
  /// occurred" told him neither).
  SuperTabFailure _joinFailed(Object failure) {
    final reason = '$failure'.replaceFirst(RegExp(r'\.$'), '');
    return SuperTabFailure('JOIN_FAILED', switch (failure) {
      SuperTabFailure(statusCode: >= 500) =>
        'The $who started on $machineName and keeps running there, but the '
            'Harness server had an error adding it to the project. Check '
            'status to try again.',
      SuperTabFailure(statusCode: >= 400) when reason.isNotEmpty =>
        'The $who started on $machineName and keeps running there, but the '
            'project did not take it: $reason. Discard request, or Check '
            'status once that changes.',
      _ =>
        'The $who started on $machineName. Joining it to the project failed: '
            '$reason. Check status to try again.',
    });
  }

  Future<void> resume() async {
    checkAccount();
    final machine = saved['machineId'] as String;
    final Agent native;
    try {
      native = await app.recoverSuperTabCreation(
        machine,
        saved['creationId'] as String,
        cancelIfMissing:
            saved['phase'] == 'starting' &&
            (saved['launchPrompt'] as String? ?? '').trim().length >
                kFirstTaskMaxLength &&
            (saved['files'] as List? ?? const []).isEmpty,
      );
    } on SuperTabFailure catch (failure) {
      if (failure.code == 'CREATION_STOPPED') throw stopped;
      if (failure.code != 'CREATION_PENDING') rethrow;
      throw SuperTabFailure(
        'CREATION_PENDING',
        '$machineName has not started the $who yet.',
      );
    } catch (_) {
      throw SuperTabFailure(
        'MACHINE_UNREACHABLE',
        'Could not reach $machineName. Check that it is online, then check status again.',
      );
    }
    await join(machine, native.id, recovered: native);
  }

  /// [HarnessLaunchIntegration.discard]: a request that has not started is
  /// cancelled on its machine first; one that started keeps running there.
  Future<String?> discard({bool anyway = false}) async {
    checkAccount();
    // Its project goes too only when nothing can still join it: a started
    // Lead keeps running and points at it, and one that may still start would.
    var nothingWillJoin =
        saved['phase'] != 'starting' && saved['phase'] != 'joining';
    if (saved['phase'] == 'joining' && !anyway) {
      return 'The $who keeps running on $machineName. Remove this request?';
    }
    if (saved['phase'] == 'starting' && !anyway) {
      final creationId = saved['creationId'] as String;
      final Map<String, dynamic> receipt;
      try {
        receipt = await app.cancelSuperTabCreation(
          saved['machineId'] as String,
          creationId,
        );
      } on SuperTabFailure {
        rethrow;
      } catch (_) {
        return 'Could not reach $machineName, so it may still start the $who. Discard anyway?';
      }
      final state = receipt['creationId'] == creationId
          ? receipt['state']
          : null;
      // A started harness can still join, so the request stays.
      if (state == 'created') {
        throw SuperTabFailure('CREATION_STARTED', startedNote);
      }
      // Unavailable: it started and is gone again, so nothing is left to keep.
      if (!const {
        'cancelled',
        'missing',
        'failed',
        'unavailable',
      }.contains(state)) {
        return '$machineName is already starting the $who and could not stop it. Discard anyway?';
      }
      nothingWillJoin = true;
    }
    if (nothingWillJoin) {
      await _deleteEmptyProject();
      await _archiveEmptyChat();
    }
    _dropped = true;
    await app.superTabs.storage.delete(key);
    checkAccount();
    return null;
  }

  /// Set once [discard] dropped the request: [persist] then writes nothing.
  bool _dropped = false;

  /// A Member's chat nothing joined is archived. Best effort, as below: the
  /// person can still archive it from the chat.
  Future<void> _archiveEmptyChat() async {
    final chat = saved['conversationId'];
    if (saved['chatPrepared'] != true || chat is! String) return;
    try {
      await app.superTabs.map(
        'POST',
        '/api/super-tabs/${saved['tabId']}/commands',
        body: {
          'operationId': '${saved['operationId']}-discard',
          'command': {
            'type': 'conversation.archive',
            'conversationId': chat,
            'archived': true,
          },
        },
      );
    } catch (_) {
      // Unreachable or refused: the chat stays.
    }
    checkAccount();
  }

  /// A new project nothing joined is only a name in the Swarm. Best effort:
  /// a project left behind can still be deleted from its options, and must
  /// not keep the person in this request.
  Future<void> _deleteEmptyProject() async {
    final projectId = saved['projectId'];
    if (saved['newProject'] != true ||
        saved['projectPrepared'] != true ||
        projectId is! String) {
      return;
    }
    try {
      final snapshot = await app.superTabs.readSnapshot(
        saved['tabId'] as String,
      );
      checkAccount();
      if (!snapshot.projects.any((p) => p.id == projectId) ||
          snapshot.agents.any((a) => a.projectId == projectId)) {
        return;
      }
      await app.superTabs.map(
        'POST',
        '/api/super-tabs/${saved['tabId']}/commands',
        body: {
          'operationId': '${saved['operationId']}-discard',
          'command': {'type': 'project.delete', 'projectId': projectId},
        },
      );
    } catch (_) {
      // Unreachable, busy or not the owner's: the project stays.
    }
    checkAccount();
  }
}