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.

37.7 KB
Raw Blame
import 'dart:async';

import 'package:flutter/material.dart';

import '../shared/theme/app_theme.dart' as grid;
import '../shared/widgets/app_dialog.dart';
import '../shared/widgets/app_select_field.dart';
import '../state/app_state.dart';
import '../widgets/desktop_chrome.dart';
import 'private_project_lock.dart';
import 'controller.dart';
import 'buddy_machines.dart';
import 'buddy_model.dart';
import 'buddy_engine.dart';
import 'buddy_restart.dart' show readerBuddy;
import 'dialog_scope.dart';
import 'identity.dart';
import 'model.dart';

/// The engines a Buddy runs on (spec: Buddies, 10-28), each offered alike:
/// a Buddy runs with its owner's full access on their own machine, Codex as
/// Claude Code (Ken, 11-04, #2832).
const kBuddyEngines = {'claude': 'Claude', 'codex': 'Codex'};

/// An engine as people read it: "Claude", "Codex".
String buddyEngineName(String engine) =>
    kBuddyEngines[engine] ??
    (engine.isEmpty ? 'Agent' : engine[0].toUpperCase() + engine.substring(1));

/// The projects where the signed-in person may add a Buddy: those where they
/// have none running.
List<SuperTabProject> buddyProjects(SuperTabController c) => [
  for (final project in c.snapshot?.projects ?? const <SuperTabProject>[])
    if (c.buddy(project.id) == null) project,
];

/// A person by the name the Swarm shows: the name they set, else their
/// username.
String buddyPersonName(SuperTabController c, String personId) {
  return c.snapshot?.people
          .where((p) => p.id == personId)
          .firstOrNull
          ?.shownName ??
      'its owner';
}

/// The machine [machineId]'s name as the dialog and the chat show it.
String buddyMachineName(
  SuperTabController c,
  String machineId, {
  AppNotifier? app,
}) {
  // The name its person gave it, else the Swarm's (docs/naming-system.md). A
  // machine of the reader's own outside the Swarm is in no Swarm list
  // (backend buddyOnly), so their account names it.
  final given = app?.stateOf(machineId)?.machine.displayName;
  final name = given != null && given.isNotEmpty
      ? given
      : c.snapshot?.pool(machineId)?['name'];
  return name is String && name.isNotEmpty
      ? superTabMachineName(name)
      : 'another machine';
}

/// Add a Buddy: project, one of the reader's own machines, and engine. With
/// [app], every machine of their account is offered, this computer first; one
/// outside the Swarm stays out of it (buddyMachines).
Future<void> showAddBuddy(
  BuildContext context,
  SuperTabController c, {
  String? projectId,
  AppNotifier? app,
}) => showAppDialog<void>(
  context: context,
  builder: (context) => SuperTabDialogScope(
    controller: c,
    child: _AddBuddyDialog(controller: c, projectId: projectId, app: app),
  ),
);

class _AddBuddyDialog extends StatefulWidget {
  const _AddBuddyDialog({required this.controller, this.projectId, this.app});
  final SuperTabController controller;
  final String? projectId;
  final AppNotifier? app;

  @override
  State<_AddBuddyDialog> createState() => _AddBuddyDialogState();
}

class _AddBuddyDialogState extends State<_AddBuddyDialog> {
  SuperTabController get c => widget.controller;

  /// The fields' labels share one column.
  static const _labelWidth = 72.0;
  String? _project, _machine;
  String _engine = 'claude';
  bool _busy = false;
  String? _error;
  late final _adder = BuddyMachineAdder(widget.controller, widget.app);

  @override
  void initState() {
    super.initState();
    final projects = buddyProjects(c);
    _project =
        projects.where((p) => p.id == widget.projectId).firstOrNull?.id ??
        projects.where((p) => p.id == c.currentProjectId).firstOrNull?.id ??
        projects.firstOrNull?.id;
    _machine = _machines.firstOrNull?.id;
    c.addListener(_swarmChanged);
  }

  @override
  void dispose() {
    c.removeListener(_swarmChanged);
    super.dispose();
  }

  /// The Swarm changed under the open dialog: its machines may have too.
  void _swarmChanged() {
    if (mounted) setState(() {});
  }

  List<BuddyMachine> get _machines => buddyMachines(c, app: widget.app);

  /// The chosen machine while it is still one the reader may use, else the
  /// first that is; null when none is left.
  BuddyMachine? get _picked => pickedBuddyMachine(_machines, _machine);

  Future<void> _submit() async {
    final project = _project, machine = _picked;
    if (_busy || project == null || machine == null) return;
    setState(() {
      _busy = true;
      _error = null;
    });
    final (:id, :setup, error: addError) = await _adder.resolve(
      machine,
      alive: () => mounted,
    );
    if (!mounted) return;
    if (id == null) {
      setState(() {
        _busy = false;
        _error = addError;
      });
      return;
    }
    final added = await c.addBuddy(
      projectId: project,
      machineId: id,
      engine: _engine,
      setup: setup,
    );
    // Its host reads the Swarm now rather than on its next pass.
    if (added && setup != null) unawaited(widget.app?.wakeSuperTabHost(id));
    if (!mounted) return;
    if (added) {
      Navigator.pop(context);
      return;
    }
    setState(() {
      _busy = false;
      _error = c.operationError ?? 'Could not add the Buddy. Try again.';
    });
  }

  @override
  Widget build(BuildContext context) {
    grid.AppTheme.watch(context);
    final projects = buddyProjects(c);
    final machines = _machines;
    final projectName =
        projects.where((p) => p.id == _project).firstOrNull?.name ?? '';
    Widget label(String text) => SizedBox(
      width: _labelWidth,
      child: Text(
        text,
        style: DesktopChrome.control(color: DesktopChrome.muted),
      ),
    );
    return AlertDialog(
      title: const Text('Add a Buddy'),
      content: SizedBox(
        width: 440,
        child: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                'A private agent to think things through with. It runs on '
                'your own machine, reads #$projectName and your chat with '
                'it, and posts to the '
                '${c.snapshot?.coordinatorNameOf(_project ?? '') ?? kDefaultCoordinatorName} '
                'only when you ask.',
                style: DesktopChrome.text(),
              ),
              const SizedBox(height: 16),
              Row(
                children: [
                  label('Project'),
                  Expanded(
                    child: AppSelectField<String>(
                      key: const ValueKey('super-buddy-project'),
                      value: _project ?? '',
                      semanticLabel: 'Project',
                      textStyle: DesktopChrome.control(),
                      options: [
                        for (final p in projects)
                          SelectOption(value: p.id, label: p.name),
                      ],
                      onChanged: (value) {
                        if (!_busy) setState(() => _project = value);
                      },
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 12),
              Row(
                // With no machine the label sits on the line it names.
                crossAxisAlignment: machines.isEmpty
                    ? CrossAxisAlignment.start
                    : CrossAxisAlignment.center,
                children: [
                  label('Machine'),
                  Expanded(
                    child: machines.isEmpty
                        ? BuddyNoMachine(machines: machines)
                        : BuddyMachineField(
                            key: const ValueKey('super-buddy-machine'),
                            machines: machines,
                            value: _picked?.id,
                            busy: _busy,
                            onChanged: (value) {
                              if (!_busy) setState(() => _machine = value);
                            },
                          ),
                  ),
                ],
              ),
              if (machines.isNotEmpty && _picked == null) ...[
                const SizedBox(height: 4),
                Padding(
                  padding: const EdgeInsets.only(left: _labelWidth),
                  child: BuddyNoMachine(machines: machines),
                ),
              ],
              const SizedBox(height: 12),
              Row(
                children: [
                  label('Agent'),
                  Expanded(
                    child: RadioGroup<String>(
                      groupValue: _engine,
                      onChanged: (value) {
                        if (!_busy && value != null) {
                          setState(() => _engine = value);
                        }
                      },
                      child: Row(
                        children: [
                          for (final MapEntry(:key, :value)
                              in kBuddyEngines.entries)
                            Flexible(
                              child: RadioListTile<String>(
                                value: key,
                                enabled: !_busy,
                                dense: true,
                                contentPadding: EdgeInsets.zero,
                                title: Text(value),
                              ),
                            ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
              if (_error case final error?) ...[
                const SizedBox(height: 12),
                Text(
                  error,
                  key: const ValueKey('super-buddy-error'),
                  style: DesktopChrome.control(),
                ),
              ],
            ],
          ),
        ),
      ),
      actions: [
        TextButton(
          onPressed: _busy ? null : () => Navigator.pop(context),
          child: const Text('Cancel'),
        ),
        FilledButton(
          onPressed: _busy || _project == null || _picked == null
              ? null
              : () => unawaited(_submit()),
          child: Text(_busy ? 'Adding…' : 'Add Buddy'),
        ),
      ],
    );
  }
}

/// Asks before removing the reader's Buddy in [projectId]; its chat stays.
Future<void> confirmRemoveBuddy(
  BuildContext context,
  SuperTabController c,
  String projectId, {
  String? conversationId,
}) {
  final chat = conversationId == null
      ? null
      : c.snapshot?.conversation(conversationId);
  final buddy = chat == null
      ? readerBuddy(c, projectId)
      : chat.agentIds
            .map((id) => c.snapshot?.agent(id))
            .whereType<SuperTabAgent>()
            .where((a) => a.isMainBuddy)
            .firstOrNull;
  return showAppDialog<void>(
    context: context,
    builder: (context) => _BuddyDialogScope(
      controller: c,
      projectId: projectId,
      child: _RemoveBuddyDialog(
        controller: c,
        projectId: projectId,
        conversationId: conversationId,
        // Named as the dialog opens: once removed, the Buddy is gone.
        name: buddy == null ? null : buddy.displayName ?? buddy.name,
      ),
    ),
  );
}

class _RemoveBuddyDialog extends StatefulWidget {
  const _RemoveBuddyDialog({
    required this.controller,
    required this.projectId,
    required this.conversationId,
    required this.name,
  });
  final SuperTabController controller;
  final String projectId;
  final String? conversationId;

  /// The Buddy's shown name; null when it is not known.
  final String? name;

  @override
  State<_RemoveBuddyDialog> createState() => _RemoveBuddyDialogState();
}

class _RemoveBuddyDialogState extends State<_RemoveBuddyDialog> {
  SuperTabController get c => widget.controller;
  bool _busy = false;
  String? _error;

  Future<void> _remove() async {
    if (_busy) return;
    setState(() {
      _busy = true;
      _error = null;
    });
    final removed = await c.removeBuddy(
      widget.projectId,
      conversationId: widget.conversationId,
    );
    if (!mounted) return;
    if (removed) {
      Navigator.pop(context);
      return;
    }
    setState(() {
      _busy = false;
      _error = c.operationError ?? "Couldn't remove the Buddy. Try again.";
    });
  }

  @override
  Widget build(BuildContext context) {
    grid.AppTheme.watch(context);
    final name = widget.name;
    return PopScope(
      canPop: !_busy,
      child: AlertDialog(
        title: Text('Remove ${name ?? 'your Buddy'}?'),
        content: SizedBox(
          width: 400,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '${name ?? 'Your Buddy'} stops. Your chat stays, and your '
                'next Buddy here picks it up.',
                style: DesktopChrome.text(),
              ),
              if (_error case final error?) ...[
                const SizedBox(height: 12),
                Text(
                  error,
                  key: const ValueKey('super-buddy-remove-error'),
                  style: DesktopChrome.control(
                    color: grid.AppPalette.dangerFill,
                  ),
                ),
              ],
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: _busy ? null : () => Navigator.pop(context),
            child: const Text('Cancel'),
          ),
          FilledButton(
            style: grid.dangerButtonStyle(),
            onPressed: _busy ? null : () => unawaited(_remove()),
            child: Text(_busy ? 'Removing…' : 'Remove'),
          ),
        ],
      ),
    );
  }
}

/// Rename the reader's Buddy in [projectId] (mockup confirmed by Diego,
/// 10-29): the name everyone in the Swarm sees; empty gives it a fresh real
/// name (task #4568). The backend checks the name and says why it refuses.
Future<void> showRenameBuddy(
  BuildContext context,
  SuperTabController c,
  String projectId, {
  String? conversationId,
}) => showAppDialog<void>(
  context: context,
  builder: (context) => _BuddyDialogScope(
    controller: c,
    projectId: projectId,
    child: _RenameBuddyDialog(
      controller: c,
      projectId: projectId,
      conversationId: conversationId,
    ),
  ),
);

/// A Buddy dialog's scope: its project while the project is there, or the
/// one Buddy's chat while that is there. The one Buddy belongs to no project
/// (its key is [SuperTabController.kSwarmBuddyKey]), so a scope that wanted a
/// project showed "This action is no longer available." in place of Rename
/// Buddy and Remove Buddy (task #2428, 11-03).
class _BuddyDialogScope extends StatelessWidget {
  const _BuddyDialogScope({
    required this.controller,
    required this.projectId,
    required this.child,
  });

  final SuperTabController controller;
  final String projectId;
  final Widget child;

  @override
  Widget build(BuildContext context) {
    final swarm = projectId == SuperTabController.kSwarmBuddyKey;
    return SuperTabDialogScope(
      controller: controller,
      projectId: swarm ? null : projectId,
      conversationId: swarm ? controller.buddyChat(projectId)?.id : null,
      child: child,
    );
  }
}

class _RenameBuddyDialog extends StatefulWidget {
  const _RenameBuddyDialog({
    required this.controller,
    required this.projectId,
    this.conversationId,
  });
  final SuperTabController controller;
  final String projectId;

  /// One Buddy of several (#3818); null for the default.
  final String? conversationId;

  @override
  State<_RenameBuddyDialog> createState() => _RenameBuddyDialogState();
}

class _RenameBuddyDialogState extends State<_RenameBuddyDialog> {
  SuperTabController get c => widget.controller;

  /// The backend's limit: a longer name is refused there anyway.
  static const _maxLength = 32;
  late final _chat = widget.conversationId == null
      ? c.buddyChat(widget.projectId)
      : c.snapshot?.conversation(widget.conversationId!);
  late final _name = TextEditingController(text: _chat?.buddyName ?? '');

  /// The name it goes by now, as its chat's header shows it.
  String? get _shown => switch ((_chat, c.snapshot)) {
    (final chat?, final snapshot?) => switch (superTabChatBuddy(c, chat)) {
      final agent? => snapshot.agentName(agent.id, fallback: agent.name),
      null => chat.buddyName,
    },
    _ => null,
  };
  bool _busy = false;
  String? _error;

  @override
  void dispose() {
    _name.dispose();
    super.dispose();
  }

  Future<void> _submit() async {
    if (_busy) return;
    setState(() {
      _busy = true;
      _error = null;
    });
    final renamed = await c.renameBuddy(
      widget.projectId,
      _name.text,
      conversationId: widget.conversationId,
    );
    if (!mounted) return;
    if (renamed) {
      Navigator.pop(context);
      return;
    }
    setState(() {
      _busy = false;
      _error = c.operationError ?? 'Could not rename the Buddy. Try again.';
    });
  }

  @override
  Widget build(BuildContext context) {
    grid.AppTheme.watch(context);
    final shown = _shown;
    return AlertDialog(
      title: Text(shown == null ? 'Rename your agent' : 'Rename $shown'),
      content: SizedBox(
        width: 440,
        // Scrolls in a short window or at large text, as Add a Buddy does.
        child: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                'Everyone in this Swarm sees this name.',
                style: DesktopChrome.text(),
              ),
              const SizedBox(height: 12),
              TextField(
                key: const ValueKey('super-buddy-name'),
                controller: _name,
                autofocus: true,
                enabled: !_busy,
                maxLength: _maxLength,
                decoration: InputDecoration(hintText: shown, counterText: ''),
                onSubmitted: (_) => _submit(),
              ),
              const SizedBox(height: 4),
              Text(
                'Leave it empty for a new name.',
                style: DesktopChrome.control(color: DesktopChrome.muted),
              ),
              if (_error case final error?) ...[
                const SizedBox(height: 12),
                Text(
                  error,
                  // The Buddy card's error colour.
                  style: DesktopChrome.control(
                    color: grid.AppPalette.dangerFill,
                  ),
                ),
              ],
            ],
          ),
        ),
      ),
      actions: [
        TextButton(
          onPressed: _busy ? null : () => Navigator.pop(context),
          child: const Text('Cancel'),
        ),
        FilledButton(
          onPressed: _busy ? null : _submit,
          child: Text(_busy ? 'Saving…' : 'Save'),
        ),
      ],
    );
  }
}

/// Under a Buddy chat's header: what it runs on and who else can see its
/// terminal, and, while it is down, a way to start it again. Before its
/// agent is there, how its start is going (backend: the start carries the
/// add's progress and failure).
/// The Buddy that [chat] is with: the reader's own main Buddy in the Swarm's one Buddy chat, else its project's.
SuperTabAgent? superTabChatBuddy(
  SuperTabController c,
  SuperTabConversation chat,
) => chat.isSwarmBuddyChat && c.snapshot!.buddyCap != null
    ? chat.agentIds
          .map(c.snapshot!.agent)
          .whereType<SuperTabAgent>()
          .where((a) => a.isMainBuddy && a.buddyOf == c.accountId)
          .firstOrNull
    : c.buddy(chat.projectId);

class SuperTabBuddyBar extends StatelessWidget {
  const SuperTabBuddyBar({
    super.key,
    required this.controller,
    required this.chat,
    this.app,
    this.line = true,
  });
  final SuperTabController controller;
  final SuperTabConversation chat;

  /// The bar's line of engine, model, machine and who reads the chat. Off under the middle chat's one-row header,
  /// which carries the pickers and nothing else (anh Dee, #4204); the limit and Start again rows stay.
  final bool line;

  /// For the Start bar's Add this Mac, as Add a Buddy has it (#2105).
  final AppNotifier? app;

  EdgeInsets get _padding => const EdgeInsets.fromLTRB(
    grid.AppDesktop.panelPadding,
    grid.AppDesktop.controlGap,
    grid.AppDesktop.panelPadding,
    grid.AppDesktop.menuInset,
  );

  /// A start under way, or one that failed with Start again; with none, the
  /// Start bar: the chat is there before any Buddy (Lead's ruling, 10-29).
  Widget _starting(SuperTabController c) {
    final start = c.buddyStart(chat.projectId);
    final error = start?['error'];
    if (start == null || (error is! String && start['harnessId'] != null)) {
      return _BuddyStart(
        // One bar per chat: another project's Buddy chat gets a bar of its
        // own, and leaving this one stops its start (Diego, 10-30: a Buddy
        // was created in whichever chat was open when setup ended).
        key: ValueKey(('super-buddy-start', chat.id)),
        controller: c,
        projectId: chat.projectId,
        padding: _padding,
        app: app,
      );
    }
    final request = superTabMap(start['request']);
    final engine = request['engine'] as String? ?? '';
    final machineId = request['machineId'] as String? ?? '';
    final busy = !c.canWrite || c.saving || c.hasPendingAction;
    return Padding(
      key: const ValueKey('super-buddy-bar'),
      padding: _padding,
      child: Row(
        children: [
          Expanded(
            child: Text(
              error is String
                  ? "Couldn't start: $error"
                  : 'Starting ${buddyEngineName(engine)} on '
                        '${buddyMachineName(c, machineId, app: app)}…',
              style: DesktopChrome.control(),
            ),
          ),
          if (error is String)
            TextButton(
              onPressed: busy || machineId.isEmpty
                  ? null
                  : () => unawaited(
                      c.addBuddy(
                        projectId: chat.projectId,
                        machineId: machineId,
                        engine: engine,
                      ),
                    ),
              child: const Text('Start again'),
            ),
        ],
      ),
    );
  }

  /// The words the Buddy's machine reports for a switch the Buddy guard held
  /// (cli superTabs/buddyModel.ts refusal(), task #3256), as the backend's
  /// line in the Buddy chat begins (backend superTabs/buddyModel.ts).
  static const _heldSwitch =
      "Couldn't switch your Buddy: Start your Buddy again to switch its model";

  /// How far back the bar looks for that line: one page of the chat. The read
  /// runs on every build, so it is bounded (AGENTS.md standard 4); a refusal
  /// under more newer messages than this offers nothing, and nothing is
  /// removed.
  static const _heldSwitchReach = 100;

  /// Whether [agent]'s last switch failed because it must be started again:
  /// its newest system line in this chat says so, and no switch is under way.
  /// Its machine writes that line as the Buddy itself, so a later line (a
  /// switch that landed, another failure) settles it, and a Buddy started
  /// again, a new agent, never inherits it. Scholes, 11-05: the line alone
  /// told him to start his Buddy again, with no way to do it while it ran.
  ///
  /// Only from the chat's newest messages (Guide's review of #3171): a window
  /// opened at an older read mark holds an older page, and the line that
  /// settled the switch may be among the newer ones it has not read. The
  /// cheap checks come first, and the held rows are read from the end without
  /// a copy ([SuperTabController.newestFirst]), so the scan stops at this
  /// Buddy's newest system line.
  bool _mustStartAgain(SuperTabController c, SuperTabAgent agent) {
    if (!chat.isSwarmBuddyChat ||
        agent.modelRequest != null ||
        agent.switchRequest != null) {
      return false;
    }
    final conversation = c.snapshot?.conversation(chat.id);
    if (conversation == null ||
        c.hasNewer(chat.id) ||
        c.awaitsNewest(chat.id)) {
      return false;
    }
    final held = c.newestFirst(chat.id);
    final newest =
        conversation.lastMainSequence ?? conversation.lastMessageSequence;
    if ((held.firstOrNull?.sequence ?? -1) < newest) return false;
    for (final m in held.take(_heldSwitchReach)) {
      if (m.source['kind'] == 'system' && m.author['id'] == agent.id) {
        return m.text.startsWith(_heldSwitch);
      }
    }
    return false;
  }

  /// Why Start again cannot run now, in words, or null when it can: new work
  /// paused in the Swarm, or [agent]'s machine paused or offline there.
  String? _restartHeld(
    SuperTabController c,
    SuperTabAgent agent,
    String machine,
  ) {
    if (c.snapshot!.paused) {
      return 'New work is paused. Start your Buddy again once it resumes.';
    }
    final target = buddyMachines(
      c,
      app: app,
    ).where((m) => m.id == agent.machineId).firstOrNull;
    final block = target == null ? null : buddyMachineBlock(target);
    return block == null
        ? null
        : "$machine is $block. Start your Buddy again once it's back.";
  }

  /// A running Buddy refuses a second start (backend BUDDY_EXISTS): it is
  /// removed, then started on the same machine and engine. Its chat and its
  /// name stay. Unlike a down Buddy's Start again, which the server replaces
  /// in one command, these are two: the machine and engine are kept first
  /// ([_restartTargets]), so a start refused after the removal, or a removal
  /// whose answer was lost, leaves the Start bar on them, one click away.
  Future<void> _startAgain(SuperTabController c, SuperTabAgent agent) async {
    final projectId = chat.projectId;
    (_restartTargets[c] ??= {})[projectId] = (
      machineId: agent.machineId,
      engine: agent.engine,
    );
    if (!await c.removeBuddy(projectId)) return;
    if (await c.addBuddy(
      projectId: projectId,
      machineId: agent.machineId,
      engine: agent.engine,
    )) {
      _restartTargets[c]?.remove(projectId);
    }
  }

  @override
  Widget build(BuildContext context) {
    grid.AppTheme.watch(context);
    final c = controller;
    final agent = superTabChatBuddy(c, chat);
    if (agent == null) return _starting(c);
    final name = c.snapshot!.agentName(agent.id, fallback: agent.name);
    final machine = buddyMachineName(c, agent.machineId, app: app);
    final project = c.snapshot!.projects
        .where((p) => p.id == chat.projectId)
        .firstOrNull;
    final access = agent.machineOwnerId == c.accountId
        ? 'only you can read this chat'
        : '${buddyPersonName(c, agent.machineOwnerId)} can see its terminal';
    final where = [
      if (chat.isSwarmBuddyChat && buddyEngineCapable(c.snapshot!, agent))
        machine
      else
        '${buddyEngineName(agent.engine)} on $machine',
      if (project != null) '#${project.name}',
      // The one Buddy for the whole Swarm (spec 2026-10-31-one-buddy-per-swarm).
      if (chat.isSwarmBuddyChat) 'reads all your projects',
      access,
    ].join(' · ');
    final busy = !c.canWrite || c.saving || c.hasPendingAction;
    final offer = agent.downSince == null && _mustStartAgain(c, agent);
    final held = offer ? _restartHeld(c, agent, machine) : null;
    final limited =
        chat.isSwarmBuddyChat &&
        agent.gridModel == null &&
        agent.downSince == null &&
        agent.switchRequest == null &&
        agent.modelRequest == null &&
        agent.limitedUntil?.isAfter(DateTime.now()) == true &&
        buddyEngineCapable(c.snapshot!, agent);
    if (!line && !limited && !offer && agent.downSince == null) {
      return const SizedBox.shrink();
    }
    return Padding(
      key: const ValueKey('super-buddy-bar'),
      padding: _padding,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        mainAxisSize: MainAxisSize.min,
        children: [
          // The one Buddy switches between its person's subscription and a
          // model shared in the Swarm (task #2354); a project's Buddy cannot.
          if (!line)
            const SizedBox.shrink()
          else if (chat.isSwarmBuddyChat)
            BuddyModelLine(
              controller: c,
              agent: agent,
              machine: machine,
              rest: where,
            )
          else if (project?.isPrivate == true)
            Text.rich(
              TextSpan(
                style: DesktopChrome.metadata(),
                children: [
                  TextSpan(
                    text: '${buddyEngineName(agent.engine)} on $machine · ',
                  ),
                  WidgetSpan(
                    alignment: PlaceholderAlignment.middle,
                    child: PrivateProjectLock(
                      size: 12,
                      color: DesktopChrome.muted,
                    ),
                  ),
                  TextSpan(text: ' ${project!.name} · $access'),
                ],
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            )
          else
            Text(where, style: DesktopChrome.metadata()),
          if (limited)
            Row(
              key: const ValueKey('super-buddy-engine-limit'),
              children: [
                Expanded(
                  child: Text(
                    'Limit reached.',
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: DesktopChrome.metadata(),
                  ),
                ),
                BuddyEnginePicker(
                  controller: c,
                  agent: agent,
                  limitAction: true,
                ),
              ],
            ),
          if (offer)
            Row(
              key: const ValueKey('super-buddy-start-again'),
              children: [
                Expanded(
                  child: Text(
                    held ?? 'Start your Buddy again to switch its model.',
                    style: DesktopChrome.control(),
                  ),
                ),
                // The server refuses a start while new work is paused, in the
                // Swarm or on the Buddy's machine: the Buddy is not removed
                // for a start that cannot follow (reviews of #3171).
                TextButton(
                  onPressed: busy || held != null
                      ? null
                      : () => unawaited(_startAgain(c, agent)),
                  child: const Text('Start again'),
                ),
              ],
            ),
          if (agent.downSince != null)
            Row(
              children: [
                Expanded(
                  child: Text(
                    '$name is offline. Your chat stays.',
                    style: DesktopChrome.control(),
                  ),
                ),
                TextButton(
                  onPressed: busy
                      ? null
                      : () => unawaited(
                          c.addBuddy(
                            projectId: chat.projectId,
                            machineId: agent.machineId,
                            engine: agent.engine,
                          ),
                        ),
                  child: const Text('Start again'),
                ),
              ],
            ),
        ],
      ),
    );
  }
}

/// The machine and engine of a Buddy removed to start again (the Buddy bar's
/// Start again), by its project key, until a start of it is accepted: per
/// controller, so another account's never shows. In memory only: it serves
/// the restart under way in this window.
final _restartTargets =
    Expando<Map<String, ({String machineId, String engine})>>(
      'buddy restart targets',
    );

/// A Buddy chat with no Buddy: one click starts one, on the reader's own
/// machine and with Claude unless they pick otherwise (mockup A, Lead 10-29).
/// A viewer, who adds nothing, sees no bar.
class _BuddyStart extends StatefulWidget {
  const _BuddyStart({
    super.key,
    required this.controller,
    required this.projectId,
    required this.padding,
    required this.app,
  });
  final SuperTabController controller;
  final String projectId;
  final EdgeInsets padding;
  final AppNotifier? app;

  @override
  State<_BuddyStart> createState() => _BuddyStartState();
}

class _BuddyStartState extends State<_BuddyStart> {
  SuperTabController get c => widget.controller;
  late final _adder = BuddyMachineAdder(widget.controller, widget.app);
  String? _machine, _error;
  String _engine = 'claude';
  bool _adding = false;

  /// [_machine] is a restart's target, kept while it cannot be used, until
  /// the reader chooses another (Guide's second review of #3171).
  bool _keepTarget = false;

  @override
  void initState() {
    super.initState();
    // A Buddy removed to start again whose start did not follow: back on the
    // machine and engine it ran on.
    if (_restartTargets[c]?[widget.projectId] case final target?) {
      _machine = target.machineId;
      _engine = target.engine;
      _keepTarget = true;
    }
  }

  /// Starts the Buddy on [machine], first preparing it when it is one of the
  /// reader's machines outside the Swarm. A failed setup says why and starts
  /// nothing. The Buddy is for the project whose chat was clicked: once the
  /// bar shows another chat, the start stops and sends nothing.
  Future<void> _start(BuddyMachine machine) async {
    if (_adding) return;
    final projectId = widget.projectId;
    bool here() => mounted && widget.projectId == projectId;
    setState(() {
      _adding = true;
      _error = null;
    });
    final (:id, :setup, :error) = await _adder.resolve(machine, alive: here);
    if (!mounted) return;
    final stillHere = here();
    setState(() {
      _adding = false;
      // Another chat's bar never shows this start's error.
      _error = stillHere ? error : null;
    });
    if (id == null || !stillHere) return;
    final app = widget.app;
    unawaited(
      c
          .addBuddy(
            projectId: projectId,
            machineId: id,
            engine: _engine,
            setup: setup,
          )
          .then((added) {
            if (added) _restartTargets[c]?.remove(projectId);
            // Its host reads the Swarm now rather than on its next pass.
            if (added && setup != null) unawaited(app?.wakeSuperTabHost(id));
          }),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (!c.canWrite) return const SizedBox.shrink();
    final machines = buddyMachines(c, app: widget.app);
    final kept = _keepTarget
        ? machines.where((m) => m.id == _machine).firstOrNull
        : null;
    final keptBlock = kept == null ? null : buddyMachineBlock(kept);
    final machine = kept ?? pickedBuddyMachine(machines, _machine);
    final busy = c.saving || c.hasPendingAction || _adding;
    return Padding(
      key: const ValueKey('super-buddy-start'),
      padding: widget.padding,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            'Start your agent to brainstorm here',
            style: DesktopChrome.control(medium: true),
          ),
          const SizedBox(height: 8),
          if (machines.isEmpty)
            BuddyNoMachine(machines: machines)
          else
            // Wraps in a narrow pane: the Buddy chat beside the Board is about 300 px wide (task #3787).
            Wrap(
              spacing: grid.AppDesktop.controlGap,
              runSpacing: grid.AppDesktop.controlGap,
              crossAxisAlignment: WrapCrossAlignment.center,
              children: [
                BuddyMachineField(
                  key: const ValueKey('super-buddy-start-machine'),
                  machines: machines,
                  value: machine?.id,
                  busy: busy,
                  fitNames: true,
                  onChanged: (value) {
                    if (busy) return;
                    setState(() {
                      _machine = value;
                      _keepTarget = false;
                    });
                  },
                ),
                SizedBox(
                  width: 120,
                  child: AppSelectField<String>(
                    key: const ValueKey('super-buddy-start-engine'),
                    value: _engine,
                    semanticLabel: 'Agent',
                    textStyle: DesktopChrome.control(),
                    options: [
                      for (final MapEntry(:key, :value)
                          in kBuddyEngines.entries)
                        SelectOption(value: key, label: value),
                    ],
                    onChanged: (value) {
                      if (!busy) setState(() => _engine = value);
                    },
                  ),
                ),
                FilledButton(
                  onPressed: busy || machine == null || keptBlock != null
                      ? null
                      : () => unawaited(_start(machine)),
                  child: const Text('Start'),
                ),
              ],
            ),
          if (keptBlock != null) ...[
            const SizedBox(height: 4),
            Text(
              '${kept!.name} is $keptBlock. Your Buddy starts there once '
              "it's back, or choose another machine.",
              style: DesktopChrome.control(),
            ),
          ],
          if (machines.isNotEmpty && machine == null) ...[
            const SizedBox(height: 4),
            BuddyNoMachine(machines: machines),
          ],
          if (_error case final error?) ...[
            const SizedBox(height: 4),
            Text(
              error,
              key: const ValueKey('super-buddy-start-error'),
              style: DesktopChrome.control(),
            ),
          ],
        ],
      ),
    );
  }
}