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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Desktop: Restart Buddy (with launch flags), Rename and Remove in Swarm v3's Buddy chat (#4328) (#3486)
0xken156b21110cfbbf
diff --git a/desktop/lib/super_tabs/buddy_card.dart b/desktop/lib/super_tabs/buddy_card.dartnew file mode 100644index 000000000..49df55466--- /dev/null+++ b/desktop/lib/super_tabs/buddy_card.dart@@ -0,0 +1,503 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import '../core/models.dart' show Agent;+import '../shared/theme/app_icons.dart';+import '../shared/theme/app_theme.dart' as grid;+import '../state/app_state.dart';+import '../state/swarm_navigation.dart' show externalEngineName;+import '../widgets/desktop_chrome.dart';+import 'buddies.dart'+ show buddyMachineName, confirmRemoveBuddy, showRenameBuddy;+import 'buddy_restart.dart';+import 'controller.dart';+import 'identity.dart';+import 'launch_flags_field.dart';++/// The Buddy pane's name on the Board, as a button: the Buddy's avatar, its+/// [label] and a chevron. It owns the card it opens under itself (spec+/// 2026-11-06-board-buddy-card): status, machine, engine, the launch flags as+/// chips, and Restart, Rename and Remove. Esc, a click outside or a second+/// click closes it.+class BuddyCardButton extends StatefulWidget {+ const BuddyCardButton({+ super.key,+ required this.controller,+ required this.projectId,+ this.app,+ required this.label,+ });++ final SuperTabController controller;++ /// The Buddy chat's project, the one the old menu passed to Restart Buddy.+ final String projectId;+ final AppNotifier? app;+ final String label;++ static const cardWidth = 340.0;++ @override+ State<BuddyCardButton> createState() => _BuddyCardButtonState();+}++class _BuddyCardButtonState extends State<BuddyCardButton> {+ static const _gap = grid.AppDesktop.menuInset;+ static const _inset = grid.AppDesktop.groupGap;++ /// Rename and Remove fit beside Restart in the card's width.+ static final _compact = TextButton.styleFrom(+ minimumSize: const Size(0, grid.AppControl.height),+ padding: const EdgeInsets.symmetric(horizontal: grid.AppDesktop.controlGap),+ );++ final _fieldKey = GlobalKey<LaunchFlagsFieldState>();+ final _portal = OverlayPortalController();+ final _link = LayerLink();+ final _buttonFocus = FocusNode(debugLabel: 'Buddy card button');+ final _cardFocus = FocusNode(debugLabel: 'Buddy card');++ /// How far left the card sits so it stays inside the window.+ var _shift = 0.0;+ List<String> _words = const [];+ String? _marked, _message;+ var _busy = false, _flagsFocused = false, _warning = false;++ SuperTabController get c => widget.controller;+ AppNotifier? get app => widget.app;++ @override+ void dispose() {+ _buttonFocus.dispose();+ _cardFocus.dispose();+ super.dispose();+ }++ Agent? get _agent => buddyMachineAgent(c, widget.projectId, app);++ void _open() {+ final box = context.findRenderObject() as RenderBox?;+ final overlay =+ Overlay.maybeOf(context)?.context.findRenderObject() as RenderBox?;+ _shift = 0;+ if (box != null && overlay != null && box.hasSize) {+ final left = box.localToGlobal(Offset.zero, ancestor: overlay).dx;+ final over = left + BuddyCardButton.cardWidth + _gap - overlay.size.width;+ if (over > 0) _shift = over;+ }+ // A restart still in flight keeps its words, status and message across a+ // close and reopen, so a second press cannot send a second restart.+ setState(() {+ _flagsFocused = false;+ if (_busy) return;+ _words = [...?_agent?.launchArgs];+ _marked = _message = null;+ _warning = false;+ });+ _portal.show();+ // The card takes the focus from the button so Esc and Tab act in it.+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted && _portal.isShowing) _cardFocus.requestFocus();+ });+ }++ void _close() {+ if (!_portal.isShowing) return;+ _portal.hide();+ _buttonFocus.requestFocus();+ }++ KeyEventResult _key(FocusNode _, KeyEvent event) {+ if (event is KeyDownEvent &&+ event.logicalKey == LogicalKeyboardKey.escape &&+ _portal.isShowing) {+ _close();+ return KeyEventResult.handled;+ }+ return KeyEventResult.ignored;+ }++ Future<void> _restart(Agent agent) async {+ final app = this.app;+ if (_busy || app == null) return;+ // Text typed but not yet a chip is part of the flags.+ final field = _fieldKey.currentState;+ final words = field == null ? _words : field.takePending();+ if (words == null) {+ setState(() {+ _marked = null;+ _warning = false;+ _message = 'Close the quote in the launch flags, or remove it.';+ });+ return;+ }+ setState(() {+ _busy = true;+ _message = _marked = null;+ _words = words;+ });+ final result = await restartBuddyWithFlags(+ c,+ widget.projectId,+ app,+ text: launchArgsLine(words),+ saved: launchArgsLine(agent.launchArgs),+ );+ // The card may have been closed meanwhile: the result is kept for the+ // next open.+ if (!mounted) return;+ if (result.outcome == BuddyRestartOutcome.done) {+ setState(() => _busy = false);+ _close();+ return;+ }+ setState(() {+ _busy = false;+ _message = result.message;+ _warning = result.outcome == BuddyRestartOutcome.ignored;+ _marked = result.outcome == BuddyRestartOutcome.refused+ ? _named(result.message)+ : null;+ });+ }++ /// The chip the daemon's [detail] starts with, compared before any `=`.+ String? _named(String? detail) {+ final first = detail?.trim().split(RegExp(r'\s')).first;+ if (first == null || first.isEmpty) return null;+ String head(String word) => word.split('=').first;+ return _words.where((w) => head(w) == head(first)).firstOrNull;+ }++ void _then(Future<void> Function() action) {+ _close();+ unawaited(action());+ }++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final listenable = Listenable.merge([c, ?app]);+ return CompositedTransformTarget(+ link: _link,+ child: Focus(+ canRequestFocus: false,+ skipTraversal: true,+ onKeyEvent: _key,+ child: ListenableBuilder(+ listenable: listenable,+ builder: (context, _) => OverlayPortal(+ controller: _portal,+ overlayChildBuilder: (_) => _overlay(context),+ child: _button(context),+ ),+ ),+ ),+ );+ }++ Widget _button(BuildContext context) {+ final buddy = readerBuddy(c, widget.projectId);+ return Semantics(+ button: true,+ label: '${widget.label}, Buddy options',+ excludeSemantics: true,+ child: InkWell(+ key: const ValueKey('super-board-buddy-button'),+ focusNode: _buttonFocus,+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),+ onTap: () => _portal.isShowing ? _close() : _open(),+ child: Padding(+ padding: const EdgeInsets.all(_gap),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ _avatar(buddy, AppIcons.inlineSize + _gap),+ const SizedBox(width: _gap),+ Flexible(+ child: Text(+ widget.label,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control().copyWith(+ fontWeight: grid.AppFont.semibold,+ ),+ ),+ ),+ const SizedBox(width: _gap),+ Icon(+ AppIcons.chevronDown,+ size: AppIcons.inlineSize,+ color: DesktopChrome.muted,+ ),+ ],+ ),+ ),+ ),+ );+ }++ Widget _avatar(dynamic buddy, double size) => buddy == null+ ? SuperTabAvatar(+ identity: 'buddy:${widget.projectId}',+ name: widget.label,+ size: size,+ pattern: true,+ )+ : SuperTabAvatar.agent(+ buddy,+ name: widget.label,+ size: size,+ engineBadge: false,+ );++ Widget _overlay(BuildContext context) => Positioned.fill(+ child: Stack(+ children: [+ Positioned.fill(+ child: GestureDetector(+ key: const ValueKey('super-buddy-card-barrier'),+ behavior: HitTestBehavior.opaque,+ onTap: _close,+ ),+ ),+ CompositedTransformFollower(+ link: _link,+ showWhenUnlinked: false,+ targetAnchor: Alignment.bottomLeft,+ followerAnchor: Alignment.topLeft,+ offset: Offset(-_shift, _gap),+ child: Align(+ alignment: Alignment.topLeft,+ child: Focus(+ focusNode: _cardFocus,+ onKeyEvent: _key,+ child: FocusTraversalGroup(child: _card(context)),+ ),+ ),+ ),+ ],+ ),+ );++ Widget _card(BuildContext context) {+ final highContrast = MediaQuery.highContrastOf(context);+ final buddy = readerBuddy(c, widget.projectId);+ final agent = _agent;+ final editable = c.canWrite && !c.saving && !c.hasPendingAction;+ final canRestart =+ editable &&+ agent != null &&+ buddy != null &&+ buddy.harnessId.isNotEmpty &&+ buddy.machineId.isNotEmpty;+ final live = agent != null && !agent.isStopped;+ final machine = buddy == null+ ? 'its machine'+ : buddyMachineName(c, buddy.machineId, app: app);+ final engine = externalEngineName(agent?.engine ?? buddy?.engine ?? '');+ final dot = _busy+ ? grid.AppPalette.warn+ : live+ ? grid.AppPalette.online+ : DesktopChrome.hint;+ final status = _busy+ ? 'Restarting…'+ : live+ ? 'Running'+ : 'Stopped';+ final muted = DesktopChrome.control(color: DesktopChrome.muted);+ Widget fact(String label, String value) => Padding(+ padding: const EdgeInsets.only(top: _gap),+ child: Row(+ children: [+ Text(label, style: muted),+ const SizedBox(width: _gap),+ Flexible(+ child: Text(+ value,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control(medium: true),+ ),+ ),+ ],+ ),+ );+ return SizedBox(+ width: BuddyCardButton.cardWidth,+ child: DecoratedBox(+ key: const ValueKey('super-buddy-card'),+ decoration: BoxDecoration(+ color: grid.AppMenu.fill,+ borderRadius: BorderRadius.circular(grid.AppMenu.panelRadius),+ border: Border.all(+ color: highContrast+ ? DesktopChrome.foreground.withValues(alpha: .55)+ : grid.AppMenu.rim,+ ),+ boxShadow: grid.AppSurface.shadow,+ ),+ child: Material(+ type: MaterialType.transparency,+ child: Padding(+ padding: const EdgeInsets.all(_inset),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Row(+ children: [+ _avatar(buddy, grid.AppControl.heightField),+ const SizedBox(width: grid.AppDesktop.controlGap),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ widget.label,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control().copyWith(+ fontWeight: grid.AppFont.semibold,+ ),+ ),+ Row(+ children: [+ DecoratedBox(+ decoration: BoxDecoration(+ color: dot,+ shape: BoxShape.circle,+ ),+ child: const SizedBox.square(dimension: _gap),+ ),+ const SizedBox(width: _gap),+ Text(status, style: DesktopChrome.metadata()),+ ],+ ),+ ],+ ),+ ),+ ],+ ),+ fact('Runs on', machine),+ if (canRestart) ..._flags(agent, engine, machine),+ if (_message case final message?) ...[+ const SizedBox(height: _gap),+ Text(+ message,+ key: const ValueKey('super-buddy-card-message'),+ style: DesktopChrome.control(+ color: _warning+ ? grid.AppPalette.warn+ : grid.AppPalette.dangerFill,+ ),+ ),+ ],+ const SizedBox(height: _inset),+ _buttons(agent, canRestart: canRestart, editable: editable),+ ],+ ),+ ),+ ),+ ),+ );+ }++ List<Widget> _flags(Agent agent, String engine, String machine) => [+ const SizedBox(height: _inset),+ Text('Launch flags', style: DesktopChrome.control(medium: true)),+ const SizedBox(height: _gap),+ LaunchFlagsField(+ key: _fieldKey,+ words: _words,+ readOnly: _busy,+ marked: _marked,+ onChanged: (words) => setState(() {+ _words = words;+ _marked = null;+ }),+ onFocusChanged: (focused) {+ if (mounted) setState(() => _flagsFocused = focused);+ },+ ),+ const SizedBox(height: _gap),+ Text(+ _flagsFocused+ ? 'Press Enter or Space to add · ⌫ removes the last flag'+ : "Added to $engine's command line each time this Buddy starts on "+ '$machine. Your Buddy runs with full permissions. Don\'t put '+ 'secrets here: other people on that computer can see them.',+ style: DesktopChrome.metadata(),+ ),+ ];++ Widget _buttons(+ Agent? agent, {+ required bool canRestart,+ required bool editable,+ }) {+ final stopped = agent?.isStopped ?? true;+ return Row(+ children: [+ // Restart and Rename on the left; Remove is pushed to the right edge.+ Expanded(+ child: Wrap(+ spacing: _gap,+ runSpacing: _gap,+ crossAxisAlignment: WrapCrossAlignment.center,+ children: [+ if (canRestart)+ FilledButton.icon(+ key: const ValueKey('super-buddy-card-restart'),+ onPressed: _busy ? null : () => unawaited(_restart(agent!)),+ icon: _busy+ ? const SizedBox.square(+ dimension: AppIcons.inlineSize,+ child: CircularProgressIndicator(strokeWidth: 2),+ )+ : const Icon(+ AppIcons.rotateCw,+ size: AppIcons.inlineSize,+ ),+ label: Text(+ _busy+ ? 'Restarting'+ : stopped+ ? 'Start'+ : 'Restart',+ ),+ ),+ TextButton(+ key: const ValueKey('super-buddy-card-rename'),+ style: _compact,+ onPressed: editable && !_busy+ ? () => _then(+ () => showRenameBuddy(context, c, widget.projectId),+ )+ : null,+ child: const Text('Rename'),+ ),+ ],+ ),+ ),+ const SizedBox(width: _gap),+ TextButton(+ key: const ValueKey('super-buddy-card-remove'),+ style: _compact.copyWith(+ foregroundColor: WidgetStatePropertyAll(grid.AppPalette.dangerFill),+ ),+ onPressed:+ editable && !_busy && readerBuddy(c, widget.projectId) != null+ ? () => _then(+ () => confirmRemoveBuddy(context, c, widget.projectId),+ )+ : null,+ child: const Text('Remove'),+ ),+ ],+ );+ }+}diff --git a/desktop/lib/super_tabs/buddy_restart.dart b/desktop/lib/super_tabs/buddy_restart.dartindex 18e6511c5..f592e3419 100644--- a/desktop/lib/super_tabs/buddy_restart.dart+++ b/desktop/lib/super_tabs/buddy_restart.dart@@ -11,6 +11,7 @@ import '../widgets/desktop_chrome.dart';import 'buddies.dart' show buddyMachineName;import 'controller.dart';import 'dialog_scope.dart';+import 'model.dart' show SuperTabAgent;/// Restart the reader's Buddy in [projectId] with extra launch flags, which the/// machine keeps and applies on every later start of it (spec@@ -44,6 +45,147 @@ String launchArgsLine(Iterable<String> words) => words).join(' ');+/// [line] split the way a shell splits words: whitespace, single and double+/// quotes and backslash escapes, no expansion. Null for an unclosed quote or a+/// trailing backslash. The inverse of [launchArgsLine].+List<String>? splitLaunchArgs(String line) {+ final words = <String>[];+ final word = StringBuffer();+ var inWord = false;+ String? quote;+ for (var i = 0; i < line.length; i++) {+ final ch = line[i];+ if (quote == "'") {+ if (ch == "'") {+ quote = null;+ } else {+ word.write(ch);+ }+ } else if (quote == '"') {+ if (ch == '"') {+ quote = null;+ } else if (ch == r'\') {+ if (i + 1 >= line.length) return null;+ final next = line[i + 1];+ if (next == '"' || next == r'\') {+ word.write(next);+ i++;+ } else {+ word.write(ch);+ }+ } else {+ word.write(ch);+ }+ } else if (ch == "'" || ch == '"') {+ quote = ch;+ inWord = true;+ } else if (ch == r'\') {+ if (i + 1 >= line.length) return null;+ word.write(line[++i]);+ inWord = true;+ } else if (RegExp(r'\s').hasMatch(ch)) {+ if (inWord) words.add(word.toString());+ word.clear();+ inWord = false;+ } else {+ word.write(ch);+ inWord = true;+ }+ }+ if (quote != null) return null;+ if (inWord) words.add(word.toString());+ return words;+}++/// The reader's Buddy behind their Buddy chat in [projectId]: the main Buddy+/// that chat names, so with several Buddies (#3818) it is that chat's, not+/// another's; else the reader's Buddy in [projectId].+SuperTabAgent? readerBuddy(SuperTabController c, String projectId) {+ final snapshot = c.snapshot;+ final named = c+ .buddyChat(projectId)+ ?.agentIds+ .map((id) => snapshot?.agent(id))+ .whereType<SuperTabAgent>()+ .where((a) => a.isMainBuddy && a.buddyOf == c.accountId)+ .firstOrNull;+ return named ?? c.buddy(projectId);+}++/// The machine's agent behind the reader's Buddy in [projectId], if loaded.+Agent? buddyMachineAgent(+ SuperTabController c,+ String projectId,+ AppNotifier? app,+) {+ final buddy = readerBuddy(c, projectId);+ if (buddy == null) return null;+ return app+ ?.stateOf(buddy.machineId)+ ?.agents+ .where((a) => a.id == buddy.harnessId)+ .firstOrNull;+}++enum BuddyRestartOutcome { done, ignored, refused, notStarted, failed }++class BuddyRestartResult {+ const BuddyRestartResult(this.outcome, [this.message]);+ final BuddyRestartOutcome outcome;++ /// The exact line to show; null on [BuddyRestartOutcome.done].+ final String? message;+}++/// Restart (or resume) the reader's Buddy in [projectId] with the flags in+/// [text]; [saved] is the line the machine holds now.+Future<BuddyRestartResult> restartBuddyWithFlags(+ SuperTabController c,+ String projectId,+ AppNotifier app, {+ required String text,+ required String saved,+}) async {+ final buddy = readerBuddy(c, projectId);+ if (buddy == null) {+ return const BuddyRestartResult(+ BuddyRestartOutcome.failed,+ 'Restart is not available here.',+ );+ }+ // Nothing to clear and nothing to add is a plain restart, which an older+ // daemon does as well as a new one.+ final result = await app.restartAgent(+ buddy.machineId,+ buddy.harnessId,+ // Every press is a new intent: an earlier attempt that never confirmed+ // must not turn this one into a status check without the flags.+ attempt: app.restartAttempt(buddy.machineId, buddy.harnessId, fresh: true),+ launchArgs: text.isEmpty && saved.isEmpty ? null : text,+ );+ if (result.error == null && !result.launchArgsIgnored) {+ return const BuddyRestartResult(BuddyRestartOutcome.done);+ }+ if (result.launchArgsIgnored) {+ final machine = buddyMachineName(c, buddy.machineId, app: app);+ return BuddyRestartResult(+ BuddyRestartOutcome.ignored,+ 'Update Harness on $machine to use launch flags.',+ );+ }+ if (result.launchArgsRefused) {+ return BuddyRestartResult(BuddyRestartOutcome.refused, result.error);+ }+ if (result.engineNotStarted) {+ return const BuddyRestartResult(+ BuddyRestartOutcome.notStarted,+ "The Buddy didn't start with these flags. Fix or clear them and "+ 'restart.',+ );+ }+ return BuddyRestartResult(BuddyRestartOutcome.failed, result.error);+}+class _RestartBuddyDialog extends StatefulWidget {const _RestartBuddyDialog({required this.controller,@@ -62,15 +204,7 @@ class _RestartBuddyDialogState extends State<_RestartBuddyDialog> {SuperTabController get c => widget.controller;AppNotifier? get app => widget.app;- Agent? get _machineAgent {- final buddy = c.buddy(widget.projectId);- if (buddy == null) return null;- return app- ?.stateOf(buddy.machineId)- ?.agents- .where((a) => a.id == buddy.harnessId)- .firstOrNull;- }+ Agent? get _machineAgent => buddyMachineAgent(c, widget.projectId, app);late final _flags = TextEditingController(text: launchArgsLine(_machineAgent?.launchArgs ?? const []),@@ -88,10 +222,9 @@ class _RestartBuddyDialogState extends State<_RestartBuddyDialog> {}Future<void> _submit() async {- final buddy = c.buddy(widget.projectId);final app = this.app;if (_busy) return;- if (buddy == null || app == null) {+ if (app == null) {setState(() => _error = 'Restart is not available here.');return;}@@ -99,44 +232,28 @@ class _RestartBuddyDialogState extends State<_RestartBuddyDialog> {_busy = true;_error = null;});- final text = _flags.text.trim();- // Nothing to clear and nothing to add is a plain restart, which an older- // daemon does it as well as a new one.- final result = await app.restartAgent(- buddy.machineId,- buddy.harnessId,- // Every press is a new intent: an earlier attempt that never confirmed- // must not turn this one into a status check without the flags.- attempt: app.restartAttempt(- buddy.machineId,- buddy.harnessId,- fresh: true,- ),- launchArgs: text.isEmpty && _saved.isEmpty ? null : text,+ final result = await restartBuddyWithFlags(+ c,+ widget.projectId,+ app,+ text: _flags.text.trim(),+ saved: _saved,);if (!mounted) return;- if (result.error == null && !result.launchArgsIgnored) {+ if (result.outcome == BuddyRestartOutcome.done) {Navigator.pop(context);return;}- final machine = buddyMachineName(c, buddy.machineId, app: app);setState(() {_busy = false;- _error = result.launchArgsIgnored- ? 'Update Harness on $machine to use launch flags.'- : result.launchArgsRefused- ? result.error- : !result.engineNotStarted- ? result.error- : "The Buddy didn't start with these flags. Fix or clear them and "- 'restart.';+ _error = result.message;});}@overrideWidget build(BuildContext context) {grid.AppTheme.watch(context);- final buddy = c.buddy(widget.projectId);+ final buddy = readerBuddy(c, widget.projectId);final engine = externalEngineName(_machineAgent?.engine ?? buddy?.engine ?? '',);diff --git a/desktop/lib/super_tabs/chat/agent_chat_header.dart b/desktop/lib/super_tabs/chat/agent_chat_header.dartindex 3d68f0483..3c2deca2b 100644--- a/desktop/lib/super_tabs/chat/agent_chat_header.dart+++ b/desktop/lib/super_tabs/chat/agent_chat_header.dart@@ -21,6 +21,7 @@ class SuperTabAgentChatHeader extends StatelessWidget {required this.group,this.menu,this.app,+ this.title,});final SuperTabController controller;@@ -32,6 +33,9 @@ class SuperTabAgentChatHeader extends StatelessWidget {/// For the model picker's line that asks to add the Buddy's machine to the Swarm.final AppNotifier? app;+ /// In place of the avatar and the name, given the name: the reader's own Buddy chat's Buddy card button (view.dart).+ final Widget Function(String name)? title;+@overrideWidget build(BuildContext context) {grid.AppTheme.watch(context);@@ -63,7 +67,11 @@ class SuperTabAgentChatHeader extends StatelessWidget {child: Row(children: [const SizedBox(width: grid.AppDesktop.controlGap),- if (agent != null) ...[+ if (title case final title?)+ Expanded(+ child: Align(alignment: Alignment.centerLeft, child: title(name)),+ )+ else if (agent != null) ...[SuperTabAvatar.agent(agent,size: SuperTabAvatar.rowSize,@@ -71,16 +79,17 @@ class SuperTabAgentChatHeader extends StatelessWidget {),const SizedBox(width: grid.AppDesktop.menuInset),],- Expanded(- child: Text(- name,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: DesktopChrome.control().copyWith(- fontWeight: grid.AppFont.semibold,+ if (title == null)+ Expanded(+ child: Text(+ name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control().copyWith(+ fontWeight: grid.AppFont.semibold,+ ),),),- ),if (buddy != null && group.isSwarmBuddyChat)BuddyModelLine(controller: c,diff --git a/desktop/lib/super_tabs/launch_flags_field.dart b/desktop/lib/super_tabs/launch_flags_field.dartnew file mode 100644index 000000000..9300edb3e--- /dev/null+++ b/desktop/lib/super_tabs/launch_flags_field.dart@@ -0,0 +1,247 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import '../shared/theme/app_icons.dart';+import '../shared/theme/app_theme.dart' as grid;+import '../widgets/desktop_chrome.dart';+import 'buddy_restart.dart' show splitLaunchArgs;++/// A Buddy's launch flags as chips (spec 2026-11-06-board-buddy-card): each+/// word a monospace chip with a ×, then an input. Enter or Space turns the+/// typed text into chips, split as a shell would; an unclosed quote waits for+/// more typing; Backspace in the empty input removes the last chip.+class LaunchFlagsField extends StatefulWidget {+ const LaunchFlagsField({+ super.key,+ required this.words,+ required this.onChanged,+ this.readOnly = false,+ this.marked,+ this.onFocusChanged,+ });++ final List<String> words;+ final ValueChanged<List<String>> onChanged;+ final bool readOnly;++ /// The word to show in the error style.+ final String? marked;++ /// The input gained or lost focus, for the help line under the field.+ final ValueChanged<bool>? onFocusChanged;++ @override+ State<LaunchFlagsField> createState() => LaunchFlagsFieldState();+}++class LaunchFlagsFieldState extends State<LaunchFlagsField> {+ final _text = TextEditingController();+ final _focus = FocusNode(debugLabel: 'Launch flag input');++ /// Whether the owner was last told the input has focus.+ var _told = false;++ @override+ void initState() {+ super.initState();+ _focus.addListener(_focusMoved);+ }++ @override+ void dispose() {+ // A field that goes away while focused ends the focus for its owner.+ // Told after the frame: the owner cannot rebuild while the tree unmounts.+ if (_told) {+ final told = widget.onFocusChanged;+ WidgetsBinding.instance.addPostFrameCallback((_) => told?.call(false));+ }+ _focus+ ..removeListener(_focusMoved)+ ..dispose();+ _text.dispose();+ super.dispose();+ }++ void _focusMoved() {+ _told = _focus.hasFocus;+ widget.onFocusChanged?.call(_told);+ if (mounted) setState(() {});+ }++ /// Turn the typed text into chips. False when it is empty or holds an+ /// unclosed quote, which is left as typed.+ bool _commit() {+ final words = splitLaunchArgs(_text.text);+ if (words == null || words.isEmpty) return false;+ _text.clear();+ widget.onChanged([...widget.words, ...words]);+ return true;+ }++ /// The chips with any typed text turned into chips too, for a caller that+ /// acts on them (Restart). Null for an unclosed quote, which stays as typed.+ List<String>? takePending() {+ final words = splitLaunchArgs(_text.text);+ if (words == null) return null;+ if (words.isEmpty) return widget.words;+ final all = [...widget.words, ...words];+ _text.clear();+ widget.onChanged(all);+ return all;+ }++ void _typed(String value) {+ // A space after an odd run of backslashes is escaped: part of the word.+ final escaped = RegExp(r'(?<!\\)(\\\\)*\\\s$').hasMatch(value);+ if (value.isNotEmpty && RegExp(r'\s$').hasMatch(value) && !escaped) {+ if (!_commit() && value.trim().isEmpty) _text.clear();+ }+ }++ void _submitted() {+ _commit();+ // Enter would drop the focus; the next flag is typed straight away.+ if (!widget.readOnly) _focus.requestFocus();+ }++ KeyEventResult _key(FocusNode _, KeyEvent event) {+ if (event is KeyDownEvent &&+ event.logicalKey == LogicalKeyboardKey.backspace &&+ _text.text.isEmpty &&+ widget.words.isNotEmpty &&+ !widget.readOnly) {+ widget.onChanged(widget.words.sublist(0, widget.words.length - 1));+ return KeyEventResult.handled;+ }+ return KeyEventResult.ignored;+ }++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ return GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: widget.readOnly ? null : _focus.requestFocus,+ child: DecoratedBox(+ decoration: BoxDecoration(+ color: DesktopChrome.field,+ borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),+ border: Border.all(+ color: _focus.hasFocus+ ? DesktopChrome.foreground+ : DesktopChrome.rim,+ ),+ ),+ child: Padding(+ padding: const EdgeInsets.all(grid.AppDesktop.controlGap),+ child: Wrap(+ spacing: grid.AppDesktop.menuInset,+ runSpacing: grid.AppDesktop.menuInset,+ crossAxisAlignment: WrapCrossAlignment.center,+ children: [+ for (final (i, word) in widget.words.indexed)+ KeyedSubtree(+ key: ValueKey('launch-flag-chip-$i'),+ child: _Chip(+ word: word,+ marked: widget.marked != null && word == widget.marked,+ removeKey: ValueKey('launch-flag-remove-$i'),+ onRemove: widget.readOnly+ ? null+ : () => widget.onChanged([+ for (final (j, w) in widget.words.indexed)+ if (j != i) w,+ ]),+ ),+ ),+ ConstrainedBox(+ constraints: const BoxConstraints(+ minWidth: grid.AppControl.heightField * 3,+ maxWidth: grid.AppControl.heightField * 5,+ ),+ child: IntrinsicWidth(+ child: Focus(+ onKeyEvent: _key,+ child: TextField(+ key: const ValueKey('launch-flag-input'),+ controller: _text,+ focusNode: _focus,+ enabled: !widget.readOnly,+ style: grid.AppType.mono(color: DesktopChrome.foreground),+ cursorColor: DesktopChrome.foreground,+ decoration: InputDecoration(+ isDense: true,+ border: InputBorder.none,+ enabledBorder: InputBorder.none,+ focusedBorder: InputBorder.none,+ disabledBorder: InputBorder.none,+ filled: false,+ contentPadding: EdgeInsets.zero,+ hintText: 'add a flag…',+ hintStyle: grid.AppType.mono(color: DesktopChrome.hint),+ ),+ onChanged: _typed,+ onSubmitted: (_) => _submitted(),+ ),+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ );+ }+}++class _Chip extends StatelessWidget {+ const _Chip({+ required this.word,+ required this.marked,+ required this.removeKey,+ required this.onRemove,+ });++ final String word;+ final bool marked;+ final Key removeKey;+ final VoidCallback? onRemove;++ @override+ Widget build(BuildContext context) {+ final ink = marked ? grid.AppPalette.dangerFill : DesktopChrome.foreground;+ return DecoratedBox(+ decoration: BoxDecoration(+ color: marked+ ? grid.AppPalette.dangerFill.withValues(alpha: .12)+ : DesktopChrome.selection,+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),+ border: Border.all(+ color: marked ? grid.AppPalette.dangerFill : DesktopChrome.rim,+ ),+ ),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Padding(+ padding: const EdgeInsets.only(left: grid.AppDesktop.controlGap),+ child: Text(word, style: grid.AppType.mono(color: ink)),+ ),+ InkResponse(+ key: removeKey,+ onTap: onRemove,+ radius: AppIcons.inlineSize,+ child: Padding(+ padding: const EdgeInsets.all(grid.AppDesktop.menuInset),+ child: Icon(+ AppIcons.close,+ size: AppIcons.closeSize,+ color: marked ? ink : DesktopChrome.muted,+ ),+ ),+ ),+ ],+ ),+ );+ }+}diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex bc8fe0a72..fd8df7344 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -85,6 +85,7 @@ import 'message_row.dart';import 'message_receipt.dart';import 'notifications.dart';import 'buddies.dart';+import 'buddy_card.dart';import 'buddy_restart.dart';import 'decisions.dart';import 'day_pill.dart';@@ -3673,6 +3674,17 @@ class _SuperTabViewState extends State<SuperTabView>group: group,menu: _options(group),app: widget.app,+ // The reader's own Buddy chat: its name opens the Buddy card (Restart with launch flags, Rename, Remove),+ // which nothing else here reaches.+ title: _isBuddyChat(group)+ ? (name) => BuddyCardButton(+ key: ValueKey(group.id),+ controller: c,+ projectId: group.projectId,+ app: widget.app,+ label: name,+ )+ : null,)elseconst SizedBox(height: 44),@@ -3686,6 +3698,8 @@ class _SuperTabViewState extends State<SuperTabView>final group = c.selected;final project = c.snapshot?.projectById(_boardProjectId ?? '');final onBuddy = group?.isBuddyChat == true;+ // The Buddy card opens only on the reader's own Buddy chat.+ final ownBuddy = group != null && _isBuddyChat(group);// A card's task in a project on the Board: its priority and pause, by role (#3820).final steered =group != null &&@@ -3722,16 +3736,28 @@ class _SuperTabViewState extends State<SuperTabView>icon: const Icon(AppIcons.arrowLeft, size: 16),label: const Text('Your Buddy'),),- Expanded(- child: Text(- onBuddy ? 'Your Buddy' : (group?.label ?? ''),- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: DesktopChrome.control().copyWith(- fontWeight: grid.AppFont.semibold,+ if (ownBuddy) ...[+ Flexible(+ child: BuddyCardButton(+ key: ValueKey(group.id),+ controller: c,+ projectId: group.projectId,+ app: widget.app,+ label: 'Your Buddy',+ ),+ ),+ const Spacer(),+ ] else+ Expanded(+ child: Text(+ onBuddy ? 'Your Buddy' : (group?.label ?? ''),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control().copyWith(+ fontWeight: grid.AppFont.semibold,+ ),),),- ),const SizedBox(width: 8),],),@@ -4433,26 +4459,35 @@ class _SuperTabViewState extends State<SuperTabView>if (_isBuddyChat(group)) ...[// A Buddy chat is the reader's own: the Buddy itself to name, any// time, and to remove. Nothing to archive, and no way to a Chat with- // PM (Ken, 10-28).- if (editable)- item(- 'Rename Buddy…',- () => unawaited(showRenameBuddy(context, c, group.projectId)),- ),- if (editable &&- (c.buddy(group.projectId)?.harnessId.isNotEmpty ?? false) &&- c.buddy(group.projectId)!.machineId.isNotEmpty)- item(- 'Restart Buddy…',- () => unawaited(- showRestartBuddy(context, c, group.projectId, app: widget.app),+ // PM (Ken, 10-28). The Board gives the Buddy chat its card, which+ // holds these three, so its menu does not repeat them (#4328).+ if (!widget.board) ...[+ if (editable)+ item(+ 'Rename Buddy…',+ () => unawaited(showRenameBuddy(context, c, group.projectId)),),- ),- if (editable && c.buddy(group.projectId) != null)- item(- 'Remove Buddy',- () => unawaited(confirmRemoveBuddy(context, c, group.projectId)),- ),+ if (editable &&+ (c.buddy(group.projectId)?.harnessId.isNotEmpty ?? false) &&+ c.buddy(group.projectId)!.machineId.isNotEmpty)+ item(+ 'Restart Buddy…',+ () => unawaited(+ showRestartBuddy(+ context,+ c,+ group.projectId,+ app: widget.app,+ ),+ ),+ ),+ if (editable && c.buddy(group.projectId) != null)+ item(+ 'Remove Buddy',+ () =>+ unawaited(confirmRemoveBuddy(context, c, group.projectId)),+ ),+ ],// The one Buddy's chat lists the person's older chats in projects// they still read, each read only (spec: history).if (group.isSwarmBuddyChat)diff --git a/desktop/test/launch_flags_field_test.dart b/desktop/test/launch_flags_field_test.dartnew file mode 100644index 000000000..f57af332c--- /dev/null+++ b/desktop/test/launch_flags_field_test.dart@@ -0,0 +1,177 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/launch_flags_field.dart';++/// The Buddy card's launch flags as chips (spec 2026-11-06-board-buddy-card).+void main() {+ final input = find.byKey(const ValueKey('launch-flag-input'));++ Future<List<List<String>>> show(+ WidgetTester tester, {+ List<String> words = const ['--chrome'],+ bool readOnly = false,+ String? marked,+ }) async {+ final changes = <List<String>>[];+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(),+ home: Scaffold(+ body: Center(+ child: SizedBox(+ width: 360,+ child: LaunchFlagsField(+ words: words,+ readOnly: readOnly,+ marked: marked,+ onChanged: changes.add,+ ),+ ),+ ),+ ),+ ),+ );+ return changes;+ }++ testWidgets('a saved word is a chip, and the input has a hint', (+ tester,+ ) async {+ await show(tester);+ expect(+ find.descendant(+ of: find.byKey(const ValueKey('launch-flag-chip-0')),+ matching: find.text('--chrome'),+ ),+ findsOneWidget,+ );+ expect(find.text('add a flag…'), findsOneWidget);+ });++ testWidgets('Enter adds the typed flag and clears the input', (tester) async {+ final changes = await show(tester);+ await tester.enterText(input, '--foo');+ await tester.testTextInput.receiveAction(TextInputAction.done);+ await tester.pump();+ expect(changes.single, ['--chrome', '--foo']);+ expect(tester.widget<TextField>(input).controller!.text, isEmpty);+ });++ testWidgets('a space adds the typed flag', (tester) async {+ final changes = await show(tester);+ await tester.enterText(input, '--bar ');+ await tester.pump();+ expect(changes.single, ['--chrome', '--bar']);+ expect(tester.widget<TextField>(input).controller!.text, isEmpty);+ });++ testWidgets('a quoted flag becomes chips as a shell would split it', (+ tester,+ ) async {+ final changes = await show(tester);+ await tester.enterText(input, '--add-dir "a b"');+ await tester.testTextInput.receiveAction(TextInputAction.done);+ await tester.pump();+ expect(changes.single, ['--chrome', '--add-dir', 'a b']);+ });++ testWidgets('a space inside an unclosed quote adds nothing', (tester) async {+ final changes = await show(tester);+ await tester.enterText(input, '--x "a ');+ await tester.pump();+ expect(changes, isEmpty);+ expect(tester.widget<TextField>(input).controller!.text, '--x "a ');+ // Enter on it keeps the text too.+ await tester.testTextInput.receiveAction(TextInputAction.done);+ await tester.pump();+ expect(changes, isEmpty);+ expect(tester.widget<TextField>(input).controller!.text, '--x "a ');+ expect(tester.takeException(), isNull);+ });++ testWidgets('an escaped trailing space stays inside the word', (+ tester,+ ) async {+ final changes = await show(tester);+ await tester.enterText(input, r'--add-dir a\ ');+ await tester.pump();+ expect(changes, isEmpty);+ await tester.enterText(input, r'--add-dir a\ b ');+ await tester.pump();+ expect(changes.single, ['--chrome', '--add-dir', 'a b']);+ });++ testWidgets('the focus callback ends when the field goes away', (+ tester,+ ) async {+ final focus = <bool>[];+ Widget app(bool shown) => MaterialApp(+ theme: grid.buildAppTheme(),+ home: Scaffold(+ body: shown+ ? LaunchFlagsField(+ words: const [],+ onChanged: (_) {},+ onFocusChanged: focus.add,+ )+ : const SizedBox(),+ ),+ );+ await tester.pumpWidget(app(true));+ await tester.tap(input);+ await tester.pump();+ expect(focus.last, isTrue);+ await tester.pumpWidget(app(false));+ await tester.pump();+ expect(focus.last, isFalse);+ });++ testWidgets('Backspace in the empty input removes the last chip', (+ tester,+ ) async {+ final changes = await show(tester);+ await tester.tap(input);+ await tester.pump();+ await tester.sendKeyEvent(LogicalKeyboardKey.backspace);+ await tester.pump();+ expect(changes.single, <String>[]);+ });++ testWidgets('the × removes its chip', (tester) async {+ final changes = await show(tester);+ await tester.tap(find.byKey(const ValueKey('launch-flag-remove-0')));+ await tester.pump();+ expect(changes.single, <String>[]);+ });++ testWidgets('read only disables the input and the ×', (tester) async {+ final changes = await show(tester, readOnly: true);+ expect(tester.widget<TextField>(input).enabled, isFalse);+ await tester.tap(+ find.byKey(const ValueKey('launch-flag-remove-0')),+ warnIfMissed: false,+ );+ await tester.pump();+ expect(changes, isEmpty);+ });++ testWidgets('a marked chip is drawn in the danger style', (tester) async {+ await show(tester, words: ['--chrome', '--model'], marked: '--model');+ Color? rim(int i) {+ final box = tester.widget<DecoratedBox>(+ find+ .descendant(+ of: find.byKey(ValueKey('launch-flag-chip-$i')),+ matching: find.byType(DecoratedBox),+ )+ .first,+ );+ return ((box.decoration as BoxDecoration).border! as Border).top.color;+ }++ expect(rim(1), grid.AppPalette.dangerFill);+ expect(rim(0), isNot(grid.AppPalette.dangerFill));+ });+}diff --git a/desktop/test/super_tab_board_buddy_card_test.dart b/desktop/test/super_tab_board_buddy_card_test.dartnew file mode 100644index 000000000..3d1cb5103--- /dev/null+++ b/desktop/test/super_tab_board_buddy_card_test.dart@@ -0,0 +1,724 @@+import 'dart:io';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/state/app_state.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/view.dart';+import 'package:harness/ws/ws_conn.dart';++import 'super_tab_activity_lists_test.dart' show swarm;+import 'support/buddy_fixture.dart';+import 'support/restart_connection.dart';+import 'support/capture.dart';+import 'support/super_tab_fixture.dart';+import 'swarm_state_test.dart' show createApp;++/// The Board's Buddy card (spec 2026-11-06-board-buddy-card): Restart with+/// launch flags as chips, Rename and Remove, from the Buddy pane's name.+void main() {+ late RestartConnection connection;+ late AppNotifier app;++ Finder key(String k) => find.byKey(ValueKey(k));+ final button = key('super-board-buddy-button');+ final card = key('super-buddy-card');+ final restart = key('super-buddy-card-restart');+ final input = key('launch-flag-input');++ setUp(() {+ connection = RestartConnection();+ app = createApp(connected: true, connectionForTest: (_) => connection);+ app.stateOf('m')!.agents = [+ const Agent(+ id: 'h-wren',+ name: 'Wren',+ engine: 'claude',+ terminalAvailable: true,+ launchArgs: ['--chrome'],+ ),+ ];+ });+ tearDown(() => app.dispose());++ Future<void> settle(WidgetTester tester) async {+ for (var i = 0; i < 3; i++) {+ await tester.runAsync(+ () => Future<void>.delayed(const Duration(milliseconds: 30)),+ );+ await tester.pump(const Duration(milliseconds: 50));+ }+ }++ Future<SuperTabController> show(+ WidgetTester tester, {+ String machineId = 'm',+ Brightness brightness = Brightness.light,+ }) async {+ await tester.binding.setSurfaceSize(const Size(1500, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ // The app's own palette, which the Material theme alone does not switch.+ final before = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = before);+ final server = swarm();+ server.state['buddies'] = true;+ giveBuddy(server, person: 'owner', machineId: machineId);+ (server.state['conversations'] as List)+ .cast<Map<String, dynamic>>()+ .firstWhere((g) => g['id'] == 'offline')+ .addAll({+ 'number': 42,+ 'assignment': {'id': 'a1', 'agentId': 'kestrel', 'status': 'working'},+ });+ final c = server.controller(+ account: 'owner',+ initial: {+ 'tabId': 'tab',+ 'accountId': 'owner',+ 'selectedId': 'lead',+ // v3 folds Projects while the person has an agent.+ 'projectsGroupOpen': true,+ },+ );+ await tester.runAsync(c.refresh);+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: brightness),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ app: app,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Mac Studio',+ board: true,+ ),+ ),+ ),+ );+ await settle(tester);+ await tester.tap(key('super-group-lead'));+ await settle(tester);+ return c;+ }++ Future<void> end(WidgetTester tester, SuperTabController c) async {+ await tester.pumpWidget(const SizedBox());+ c.dispose();+ await tester.pump(const Duration(seconds: 5));+ }++ Future<void> open(WidgetTester tester) async {+ await tester.tap(button);+ await settle(tester);+ }++ String creationId() => connection.requests.last['creationId'] as String;++ Future<void> addFlag(WidgetTester tester, String flag) async {+ await tester.enterText(input, '$flag ');+ await tester.pump();+ }++ testWidgets('the Buddy pane name opens a card with its facts', (+ tester,+ ) async {+ final c = await show(tester);+ expect(card, findsNothing);+ await open(tester);+ expect(card, findsOneWidget);+ expect(find.text('Running'), findsOneWidget);+ expect(find.text('Runs on'), findsOneWidget);+ expect(find.text('Test host'), findsWidgets);+ // The facts line under the header shows and switches the engine.+ expect(find.text('Engine'), findsNothing);+ expect(+ find.descendant(+ of: key('launch-flag-chip-0'),+ matching: find.text('--chrome'),+ ),+ findsOneWidget,+ );+ expect(find.text('Launch flags'), findsOneWidget);+ await end(tester, c);+ });++ testWidgets("the help line is the dialog's, and changes with focus", (+ tester,+ ) async {+ final c = await show(tester);+ await open(tester);+ expect(+ find.text(+ "Added to Claude Code's command line each time this Buddy starts on "+ 'Test host. Your Buddy runs with full permissions. Don\'t put secrets '+ 'here: other people on that computer can see them.',+ ),+ findsOneWidget,+ );+ await tester.tap(input);+ await tester.pump();+ expect(+ find.text('Press Enter or Space to add · ⌫ removes the last flag'),+ findsOneWidget,+ );+ await end(tester, c);+ });++ testWidgets("a task card's chat has no Buddy button", (tester) async {+ final c = await show(tester);+ expect(button, findsOneWidget);+ await tester.tap(key('super-task-card-offline'));+ await settle(tester);+ expect(c.selectedId, 'offline');+ expect(button, findsNothing);+ await end(tester, c);+ });++ testWidgets('Esc closes the card', (tester) async {+ final c = await show(tester);+ await open(tester);+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await settle(tester);+ expect(card, findsNothing);+ await end(tester, c);+ });++ testWidgets('a second click on the name closes it', (tester) async {+ final c = await show(tester);+ await open(tester);+ await tester.tap(button);+ await settle(tester);+ expect(card, findsNothing);+ await end(tester, c);+ });++ testWidgets('moving the pane to a task card closes an open card', (+ tester,+ ) async {+ final c = await show(tester);+ await open(tester);+ expect(card, findsOneWidget);+ await tester.runAsync(() => c.select('offline'));+ await settle(tester);+ expect(button, findsNothing);+ expect(card, findsNothing);+ await end(tester, c);+ });++ group('Swarm v3: the Buddy chat in the middle', () {+ /// The reader's one Buddy for the Swarm (spec 2026-10-31-one-buddy-per-swarm), opened from My agents, with the+ /// Tasks slot on the right, as the app lays it out.+ Future<SuperTabController> middle(+ WidgetTester tester, {+ Brightness brightness = Brightness.light,+ }) async {+ await tester.binding.setSurfaceSize(const Size(1600, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ // The app's own palette, which the Material theme alone does not switch.+ final before = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = before);+ final server = swarm();+ server.state['buddies'] = true;+ server.state['swarmBuddy'] = true;+ (server.state['agents'] as List).add({+ 'id': 'wren',+ 'name': 'Wren',+ 'buddyScope': 'swarm',+ 'buddyOf': {'personId': 'owner', 'generation': 'fixture'},+ 'machineId': 'm',+ 'harnessId': 'h-wren',+ 'contributorId': 'owner',+ 'machineOwnerId': 'owner',+ 'configuration': {'engine': 'claude', 'model': 'default'},+ });+ (server.state['conversations'] as List).add({+ ...conversationFixture('swarm-buddy-owner', 'Buddy'),+ 'kind': 'swarm-buddy',+ 'buddyOwnerId': 'owner',+ 'agentIds': ['wren'],+ });+ // An agent of the reader's at work on a task, in My agents too.+ (server.state['agents'] as List).add({+ 'id': 'kestrel',+ 'projectId': 'lead',+ 'name': 'Kestrel',+ 'machineId': 'm',+ 'harnessId': 'h-kestrel',+ 'contributorId': 'owner',+ 'configuration': {'engine': 'codex'},+ });+ (server.state['conversations'] as List)+ .cast<Map<String, dynamic>>()+ .firstWhere((g) => g['id'] == 'offline')['assignment'] = {+ 'id': 'a1',+ 'agentId': 'kestrel',+ 'status': 'working',+ };+ final c = server.controller(+ account: 'owner',+ initial: {'tabId': 'tab', 'accountId': 'owner', 'selectedId': 'lead'},+ );+ await tester.runAsync(c.refresh);+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: brightness),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ app: app,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Mac Studio',+ board: true,+ rightPane: (_) => const SizedBox.expand(),+ ),+ ),+ ),+ );+ await settle(tester);+ await tester.tap(key('super-swarm-buddy'));+ await settle(tester);+ return c;+ }++ testWidgets("the middle header's name opens the card", (tester) async {+ final c = await middle(tester);+ expect(c.selectedId, 'swarm-buddy-owner');+ expect(+ find.descendant(of: key('super-middle-chat'), matching: button),+ findsOneWidget,+ );+ await open(tester);+ expect(card, findsOneWidget);+ expect(find.text('Running'), findsOneWidget);+ expect(+ find.descendant(+ of: key('launch-flag-chip-0'),+ matching: find.text('--chrome'),+ ),+ findsOneWidget,+ );+ await end(tester, c);+ });++ testWidgets('Restart restarts the Buddy that chat names, with the chips', (+ tester,+ ) async {+ final c = await middle(tester);+ await open(tester);+ await addFlag(tester, '--foo');+ await tester.tap(restart);+ await tester.pump();+ expect(connection.types.single, 'agent_restart');+ expect(connection.requests.single['agentId'], 'h-wren');+ expect(connection.requests.single['launchArgs'], '--chrome --foo');+ connection.restartReplies.single.complete({+ ...restartReceipt(creationId(), agentId: 'h-wren'),+ 'launchArgs': ['--chrome', '--foo'],+ });+ await settle(tester);+ expect(card, findsNothing);+ await end(tester, c);+ });++ testWidgets('the open card over the middle Buddy chat, dark', (+ tester,+ ) async {+ final c = await middle(tester, brightness: Brightness.dark);+ await open(tester);+ await captureWindow(+ tester,+ Platform.environment['HARNESS_SUPER_TAB_CAPTURE'],+ 'buddy-card-middle-dark',+ );+ expect(card, findsOneWidget);+ await end(tester, c);+ });++ testWidgets('the open card over the middle Buddy chat, light', (+ tester,+ ) async {+ final c = await middle(tester);+ await open(tester);+ await captureWindow(+ tester,+ Platform.environment['HARNESS_SUPER_TAB_CAPTURE'],+ 'buddy-card-middle-light',+ );+ expect(card, findsOneWidget);+ await end(tester, c);+ });++ testWidgets(+ "the Buddy chat's menu beside the card does not repeat Rename, Restart or Remove",+ (tester) async {+ final c = await middle(tester);+ await tester.tap(+ find.descendant(+ of: key('super-middle-chat'),+ matching: find.byTooltip('Buddy options'),+ ),+ );+ await settle(tester);+ expect(find.text('Rename Buddy…'), findsNothing);+ expect(find.text('Restart Buddy…'), findsNothing);+ expect(find.text('Remove Buddy'), findsNothing);+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await settle(tester);+ await end(tester, c);+ },+ );++ testWidgets("another agent's chat in the middle keeps its plain header", (+ tester,+ ) async {+ final c = await middle(tester);+ await tester.tap(key('super-agent-kestrel'));+ await settle(tester);+ expect(c.selectedId, 'offline');+ expect(key('super-middle-chat'), findsOneWidget);+ expect(button, findsNothing);+ await end(tester, c);+ });+ });++ testWidgets('Restart sends the chips as one line and closes on success', (+ tester,+ ) async {+ final c = await show(tester);+ await open(tester);+ await addFlag(tester, '--foo');+ await tester.tap(restart);+ await tester.pump();+ expect(connection.types.single, 'agent_restart');+ expect(connection.requests.single['agentId'], 'h-wren');+ expect(connection.requests.single['launchArgs'], '--chrome --foo');+ expect(find.text('Restarting…'), findsOneWidget);+ expect(find.text('Restarting'), findsOneWidget);+ expect(+ tester.widget<TextField>(input).enabled,+ isFalse,+ reason: 'read only while it runs',+ );+ connection.restartReplies.single.complete({+ ...restartReceipt(creationId(), agentId: 'h-wren'),+ 'launchArgs': ['--chrome', '--foo'],+ });+ await settle(tester);+ expect(card, findsNothing);+ await end(tester, c);+ });++ testWidgets(+ 'a Buddy that never saved flags shows none, and Restart sends none',+ (tester) async {+ app.stateOf('m')!.agents = [+ const Agent(+ id: 'h-wren',+ name: 'Wren',+ engine: 'claude',+ terminalAvailable: true,+ ),+ ];+ final c = await show(tester);+ await open(tester);+ expect(+ key('launch-flag-chip-0'),+ findsNothing,+ reason: 'no default flags',+ );+ await tester.tap(restart);+ await tester.pump();+ expect(connection.types.single, 'agent_restart');+ expect(connection.requests.single.containsKey('launchArgs'), isFalse);+ connection.restartReplies.single.complete(+ restartReceipt(creationId(), agentId: 'h-wren'),+ );+ await settle(tester);+ expect(card, findsNothing);+ await end(tester, c);+ },+ );++ testWidgets('a restart in flight survives closing and reopening the card', (+ tester,+ ) async {+ final c = await show(tester);+ await open(tester);+ await tester.tap(restart);+ await tester.pump();+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await settle(tester);+ expect(card, findsNothing);+ await open(tester);+ expect(tester.widget<FilledButton>(restart).onPressed, isNull);+ expect(find.text('Restarting…'), findsOneWidget);+ await tester.tap(restart, warnIfMissed: false);+ await tester.pump();+ expect(connection.types, ['agent_restart']);+ connection.restartReplies.single.complete({+ ...restartReceipt(creationId(), agentId: 'h-wren'),+ 'launchArgs': ['--chrome'],+ });+ await settle(tester);+ expect(card, findsNothing);+ await open(tester);+ expect(tester.widget<FilledButton>(restart).onPressed, isNotNull);+ expect(find.text('Restarting…'), findsNothing);+ expect(tester.takeException(), isNull);+ await end(tester, c);+ });++ testWidgets('Enter in an empty flags input does not restart', (tester) async {+ final c = await show(tester);+ await open(tester);+ await tester.tap(input);+ await tester.pump();+ await tester.testTextInput.receiveAction(TextInputAction.done);+ await tester.pump();+ expect(connection.requests, isEmpty);+ expect(card, findsOneWidget);+ await end(tester, c);+ });++ testWidgets('text typed but not yet a chip is sent with Restart', (+ tester,+ ) async {+ final c = await show(tester);+ await open(tester);+ await tester.enterText(input, '--foo');+ await tester.pump();+ await tester.tap(restart);+ await tester.pump();+ expect(connection.requests.single['launchArgs'], '--chrome --foo');+ await end(tester, c);+ });++ testWidgets('typed text with an unclosed quote blocks Restart', (+ tester,+ ) async {+ final c = await show(tester);+ await open(tester);+ await tester.enterText(input, '--x "a');+ await tester.pump();+ await tester.tap(restart);+ await tester.pump();+ expect(connection.requests, isEmpty);+ expect(+ find.text('Close the quote in the launch flags, or remove it.'),+ findsOneWidget,+ );+ expect(card, findsOneWidget);+ await end(tester, c);+ });++ testWidgets('Remove sits at the right edge, apart from Rename', (+ tester,+ ) async {+ final c = await show(tester);+ await open(tester);+ final rename = tester.getRect(key('super-buddy-card-rename'));+ final remove = tester.getRect(key('super-buddy-card-remove'));+ final cardBox = tester.getRect(card);+ expect(remove.left, greaterThan(rename.right + 8));+ expect(cardBox.right - remove.right, lessThan(24));+ expect(tester.takeException(), isNull);+ await end(tester, c);+ });++ testWidgets('a stopped Buddy says Stopped and Start resumes with the flags', (+ tester,+ ) async {+ app.stateOf('m')!.agents = [+ const Agent(+ id: 'h-wren',+ name: 'Wren',+ engine: 'claude',+ status: 'stopped',+ launchArgs: ['--chrome'],+ ),+ ];+ final c = await show(tester);+ await open(tester);+ expect(find.text('Stopped'), findsOneWidget);+ expect(find.text('Running'), findsNothing);+ expect(+ find.descendant(of: restart, matching: find.text('Start')),+ findsOneWidget,+ );+ await tester.tap(restart);+ await tester.pump();+ expect(connection.types.single, 'agent_resume');+ expect(connection.requests.single['launchArgs'], '--chrome');+ connection.restartReplies.single.complete({+ ...restartReceipt(creationId(), agentId: 'h-wren'),+ 'launchArgs': ['--chrome'],+ });+ await settle(tester);+ expect(card, findsNothing);+ await end(tester, c);+ });++ testWidgets('a refusal shows the detail and marks the named chip', (+ tester,+ ) async {+ final c = await show(tester);+ await open(tester);+ await addFlag(tester, '--model');+ await tester.tap(restart);+ await tester.pump();+ connection.restartReplies.single.completeError(+ const WsRequestFailure(+ responseType: 'agent_restart_result',+ code: 'INVALID_LAUNCH_ARGS',+ detail: "--model is set by Harness and can't be added here.",+ ),+ );+ await settle(tester);+ expect(+ find.text("--model is set by Harness and can't be added here."),+ findsOneWidget,+ );+ final box = tester.widget<DecoratedBox>(+ find+ .descendant(+ of: key('launch-flag-chip-1'),+ matching: find.byType(DecoratedBox),+ )+ .first,+ );+ expect(+ ((box.decoration as BoxDecoration).border! as Border).top.color,+ grid.AppPalette.dangerFill,+ );+ expect(card, findsOneWidget);+ await end(tester, c);+ });++ testWidgets('an engine that did not start says to fix or clear the flags', (+ tester,+ ) async {+ final c = await show(tester);+ await open(tester);+ await tester.tap(restart);+ await tester.pump();+ connection.restartReplies.single.complete({+ 'creationId': creationId(),+ 'state': 'unconfirmed',+ });+ await settle(tester);+ expect(+ find.text(+ "The Buddy didn't start with these flags. Fix or clear them and "+ 'restart.',+ ),+ findsOneWidget,+ );+ await end(tester, c);+ });++ testWidgets('a reply with no echo says to update Harness on the machine', (+ tester,+ ) async {+ final c = await show(tester);+ await open(tester);+ await tester.tap(restart);+ await tester.pump();+ connection.restartReplies.single.complete(+ restartReceipt(creationId(), agentId: 'h-wren'),+ );+ await settle(tester);+ expect(+ find.text('Update Harness on Test host to use launch flags.'),+ findsOneWidget,+ );+ await end(tester, c);+ });++ testWidgets('after a failure a second Restart is a fresh attempt with the '+ 'current chips', (tester) async {+ final c = await show(tester);+ await open(tester);+ await addFlag(tester, '--bad');+ await tester.tap(restart);+ await tester.pump();+ final first = creationId();+ connection.restartReplies.single.complete({+ 'creationId': first,+ 'state': 'unconfirmed',+ });+ await settle(tester);+ await tester.tap(key('launch-flag-remove-1'));+ await tester.pump();+ await tester.tap(restart);+ await tester.pump();+ expect(connection.checks, isEmpty);+ expect(connection.requests, hasLength(2));+ expect(connection.requests.last['launchArgs'], '--chrome');+ expect(creationId(), isNot(first));+ connection.restartReplies.last.complete({+ ...restartReceipt(creationId(), agentId: 'h-wren'),+ 'launchArgs': ['--chrome'],+ });+ await settle(tester);+ expect(card, findsNothing);+ await end(tester, c);+ });++ testWidgets('Rename opens the rename dialog', (tester) async {+ final c = await show(tester);+ await open(tester);+ await tester.tap(key('super-buddy-card-rename'));+ await settle(tester);+ expect(find.text('Rename your Buddy'), findsOneWidget);+ await end(tester, c);+ });++ testWidgets('Remove opens the remove confirm', (tester) async {+ final c = await show(tester);+ await open(tester);+ await tester.tap(key('super-buddy-card-remove'));+ await settle(tester);+ expect(find.text('Remove Buddy?'), findsOneWidget);+ await end(tester, c);+ });++ testWidgets('a Buddy whose machine agent is unknown shows Stopped and no '+ 'flags', (tester) async {+ app.stateOf('m')!.agents = [];+ final c = await show(tester);+ await open(tester);+ expect(card, findsOneWidget);+ expect(find.text('Stopped'), findsOneWidget);+ expect(input, findsNothing);+ expect(restart, findsNothing);+ expect(tester.takeException(), isNull);+ await end(tester, c);+ });++ // Writes nothing unless HARNESS_SUPER_TAB_CAPTURE names a folder.+ final shots = Platform.environment['HARNESS_SUPER_TAB_CAPTURE'];+ if (shots != null) setUpAll(() => loadCaptureFonts(shots));+ testWidgets('the open card in the light theme', (tester) async {+ final c = await show(tester);+ await open(tester);+ await captureWindow(tester, shots, 'buddy-card-light');+ expect(card, findsOneWidget);+ await end(tester, c);+ });+ testWidgets('the open card in the dark theme', (tester) async {+ final c = await show(tester, brightness: Brightness.dark);+ await open(tester);+ await captureWindow(tester, shots, 'buddy-card-dark');+ expect(card, findsOneWidget);+ await end(tester, c);+ });+}diff --git a/desktop/test/super_tab_buddy_restart_test.dart b/desktop/test/super_tab_buddy_restart_test.dartindex 1518e833d..f5d47c70f 100644--- a/desktop/test/super_tab_buddy_restart_test.dart+++ b/desktop/test/super_tab_buddy_restart_test.dart@@ -3,7 +3,13 @@ import 'package:flutter_test/flutter_test.dart';import 'package:harness/core/models.dart';import 'package:harness/shared/theme/app_theme.dart' as grid;import 'package:harness/state/app_state.dart';-import 'package:harness/super_tabs/buddy_restart.dart' show launchArgsLine;+import 'package:harness/super_tabs/buddy_restart.dart'+ show+ BuddyRestartOutcome,+ BuddyRestartResult,+ launchArgsLine,+ restartBuddyWithFlags,+ splitLaunchArgs;import 'package:harness/super_tabs/controller.dart';import 'package:harness/super_tabs/view.dart';import 'package:harness/ws/ws_conn.dart';@@ -443,4 +449,111 @@ void main() {"--add-dir '/a b' 'it'\\''s' ''",);});++ group('splitLaunchArgs', () {+ test('splits on whitespace', () {+ expect(splitLaunchArgs('--chrome'), ['--chrome']);+ expect(splitLaunchArgs(' '), <String>[]);+ });++ test('reads quotes and backslash escapes', () {+ expect(splitLaunchArgs('--add-dir "a b" --x=\'y z\' c\\ d'), [+ '--add-dir',+ 'a b',+ '--x=y z',+ 'c d',+ ]);+ });++ test('an unclosed quote or a trailing backslash is null', () {+ expect(splitLaunchArgs('--x "a'), isNull);+ expect(splitLaunchArgs('a\\'), isNull);+ });++ test('is the inverse of launchArgsLine', () {+ final w = ['--add-dir', 'a b', "it's", r'back\slash'];+ expect(splitLaunchArgs(launchArgsLine(w)), w);+ });+ });++ group('restartBuddyWithFlags', () {+ Future<BuddyRestartResult> run(+ WidgetTester tester,+ SuperTabController c,+ Future<void> Function() reply,+ ) async {+ final result = restartBuddyWithFlags(+ c,+ 'lead',+ app,+ text: '--chrome',+ saved: '--chrome',+ );+ await tester.pump();+ await reply();+ await tester.pumpAndSettle();+ return result;+ }++ testWidgets('success is done', (tester) async {+ final c = await show(tester, swarm());+ final result = await run(tester, c, () async {+ connection.restartReplies.single.complete({+ ...restartReceipt(creationId(), agentId: 'h-wren'),+ 'launchArgs': ['--chrome'],+ });+ });+ expect(result.outcome, BuddyRestartOutcome.done);+ expect(result.message, isNull);+ await close(tester, c);+ });++ testWidgets('a refusal carries the daemon detail', (tester) async {+ final c = await show(tester, swarm());+ final result = await run(tester, c, () async {+ connection.restartReplies.single.completeError(+ const WsRequestFailure(+ responseType: 'agent_restart_result',+ code: 'INVALID_LAUNCH_ARGS',+ detail: "--model is set by Harness and can't be added here.",+ ),+ );+ });+ final r = result;+ expect(r.outcome, BuddyRestartOutcome.refused);+ expect(r.message, "--model is set by Harness and can't be added here.");+ await close(tester, c);+ });++ testWidgets('an unconfirmed receipt is notStarted', (tester) async {+ final c = await show(tester, swarm());+ final result = await run(tester, c, () async {+ connection.restartReplies.single.complete({+ 'creationId': creationId(),+ 'state': 'unconfirmed',+ });+ });+ final r = result;+ expect(r.outcome, BuddyRestartOutcome.notStarted);+ expect(+ r.message,+ "The Buddy didn't start with these flags. Fix or clear them and "+ 'restart.',+ );+ await close(tester, c);+ });++ testWidgets('a reply with no echo is ignored', (tester) async {+ final c = await show(tester, swarm());+ final result = await run(tester, c, () async {+ connection.restartReplies.single.complete(+ restartReceipt(creationId(), agentId: 'h-wren'),+ );+ });+ final r = result;+ expect(r.outcome, BuddyRestartOutcome.ignored);+ expect(r.message, 'Update Harness on Test host to use launch flags.');+ await close(tester, c);+ });+ });}diff --git a/docs/plans/2026-11-06-board-buddy-card-plan.md b/docs/plans/2026-11-06-board-buddy-card-plan.mdnew file mode 100644index 000000000..e60ee5ce2--- /dev/null+++ b/docs/plans/2026-11-06-board-buddy-card-plan.md@@ -0,0 +1,186 @@+# Board Buddy card Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Put Restart Buddy (with launch flags as chips), Rename and Remove back on Desktop's Board: a Buddy card that+opens from the Buddy pane's name.++**Architecture:**+- Task 1 extracts the dialog's restart and result logic and adds a shell-word splitter (`buddy_restart.dart`).+- Task 2 builds the chip field (`launch_flags_field.dart`).+- Task 3 builds the card and turns the Board's Buddy pane header into its button (`buddy_card.dart`, `view.dart`+ `_boardChat`), reusing the anchored-card pattern of `identity_card.dart`.++**Tech Stack:** Flutter (Desktop), flutter_test.++**Spec:** `docs/specs/2026-11-06-board-buddy-card.md` (mockup `desktop/mockup/buddy-card-flags.html`).++## Global Constraints++- **Copy, verbatim:**+ - "Running", "Stopped", "Restarting…";+ - "Runs on", "Engine", "Launch flags", "add a flag…";+ - "Press Enter or Space to add · ⌫ removes the last flag";+ - the help line "Added to <engine>'s command line each time this Buddy starts on <machine>. Your Buddy runs with full+ permissions. Don't put secrets here: other people on that computer can see them.";+ - buttons "Restart" / "Start" / "Restarting", "Rename", "Remove";+ - result lines "Update Harness on <machine> to use launch flags." and "The Buddy didn't start with these flags. Fix or+ clear them and restart."+- **Board only:** the card appears only in `SuperTabView.board` mode, on the right pane's header while the Buddy chat is+ shown.+- **Old dialog unchanged:** `showRestartBuddy` keeps its behaviour for the old layout. The existing+ `test/super_tab_buddy_restart_test.dart` must stay green.+- **Desktop design system:** `DesktopChrome`, `AppType`, `grid.AppTheme.watch`, shared widgets. No raw `EdgeInsets` or+ colours where `scripts/check-ui-style.py` forbids them.++## Review Focus++1. **A chip that holds a space or a quote.** It must round-trip through `launchArgsLine` and the splitter unchanged+ (`--add-dir "a b"` → chips `--add-dir`, `a b` → line `--add-dir 'a b'`). Pinned in Task 1.+2. **An unclosed quote while typing** (`--x "a`). Space must not split it; Enter on it shows nothing broken and keeps+ the text. Pinned in Task 2.+3. **The card opened while a card's chat is shown, or the pane switching while it is open.** The header is not a button+ then; an open card closes when the pane leaves the Buddy chat. Pinned in Task 3.+4. **A restart that fails, then a second press.** The second press must send the edited chips again (a fresh attempt),+ not a status check. Pinned in Task 3.+5. **No machine agent known** (the Buddy's machine not loaded). The card shows name and "Stopped", no flags field, no+ Restart, and never throws. Pinned in Task 3.++---++### Task 1: Shared restart and a shell-word splitter++**Files:**+- Modify: `desktop/lib/super_tabs/buddy_restart.dart`+- Test: `desktop/test/super_tab_buddy_restart_test.dart` (existing; add cases)++**Interfaces:**+- Produces:+ - `List<String>? splitLaunchArgs(String line)`: shell-word split (whitespace, single and double quotes, backslash+ escapes, no expansion). Returns null for an unclosed quote or a trailing backslash. Inverse of `launchArgsLine`.+ - `Agent? buddyMachineAgent(SuperTabController c, String projectId, AppNotifier? app)`: what the dialog's+ `_machineAgent` reads today.+ - `enum BuddyRestartOutcome { done, ignored, refused, notStarted, failed }`.+ - `class BuddyRestartResult { final BuddyRestartOutcome outcome; final String? message; }`. `message` is the exact line+ to show, null on `done`.+ - `Future<BuddyRestartResult> restartBuddyWithFlags(SuperTabController c, String projectId, AppNotifier app,+ {required String text, required String saved})`: the dialog's `_submit` body (fresh attempt; `launchArgs` null when+ `text` and `saved` are both empty) and its result copy.+- The dialog's `_submit` calls `restartBuddyWithFlags`; the dialog's behaviour is unchanged.++- [ ] **Step 1: Write the failing tests** (in super_tab_buddy_restart_test.dart, a `group('splitLaunchArgs')`):+ - `splitLaunchArgs('--chrome')` == `['--chrome']`; `splitLaunchArgs(' ')` == `[]`.+ - `splitLaunchArgs('--add-dir "a b" --x=\'y z\' c\\ d')` == `['--add-dir', 'a b', '--x=y z', 'c d']`.+ - `splitLaunchArgs('--x "a')` == null; `splitLaunchArgs('a\\')` == null.+ - Round trip: for `['--add-dir', 'a b', "it's", r'back\slash']`, `splitLaunchArgs(launchArgsLine(w))` == `w`.+ - `restartBuddyWithFlags`, with the fake connection the file already uses:+ - success gives `done`;+ - an `INVALID_LAUNCH_ARGS` reply gives `refused` with the daemon detail as message;+ - an unconfirmed receipt gives `notStarted` with the exact line;+ - a created reply with no echo gives `ignored` with "Update Harness on <machine> to use launch flags.".+- [ ] **Step 2: Run** `cd desktop && flutter test test/super_tab_buddy_restart_test.dart`. Expected: the new cases FAIL+ (undefined names).+- [ ] **Step 3: Implement** the four names above in `buddy_restart.dart`. Move the dialog's `_submit` logic into+ `restartBuddyWithFlags` and the dialog's `_machineAgent` into `buddyMachineAgent`, and call them from the dialog.+- [ ] **Step 4: Run** the same command plus+ `flutter test test/agent_restart_launch_args_test.dart && flutter analyze lib/super_tabs/buddy_restart.dart`.+ Expected: all pass, no issues.+- [ ] **Step 5: Commit**+ ```bash+ git add desktop/lib/super_tabs/buddy_restart.dart desktop/test/super_tab_buddy_restart_test.dart+ git commit -m "desktop: Buddy restart shared by the dialog and a card, and a launch-flag word splitter"+ ```++### Task 2: The launch flags chip field++**Files:**+- Create: `desktop/lib/super_tabs/launch_flags_field.dart`+- Test: `desktop/test/launch_flags_field_test.dart`++**Interfaces:**+- Consumes: `splitLaunchArgs` (Task 1).+- Produces:+ - `class LaunchFlagsField extends StatefulWidget`, with constructor+ `({Key? key, required List<String> words, required ValueChanged<List<String>> onChanged, bool readOnly = false, String? marked, VoidCallback? onSubmitted})`.+ - `marked` is the word to show in the error style.+ - Keys: each chip `ValueKey('launch-flag-chip-$index')`, its × `ValueKey('launch-flag-remove-$index')`, the input+ `ValueKey('launch-flag-input')`.++- [ ] **Step 1: Write the failing tests** (testWidgets, the widget alone in a `MaterialApp` with the app theme):+ - `words: ['--chrome']` shows one chip reading `--chrome` and the hint "add a flag…".+ - Typing `--foo` then Enter calls `onChanged(['--chrome', '--foo'])` and clears the input. Typing `--bar` then a space+ does the same with `--bar`.+ - Typing `--add-dir "a b"` then Enter gives `['--chrome', '--add-dir', 'a b']`.+ - Typing `--x "a` then a space adds nothing and keeps the text `--x "a ` (unclosed quote).+ - Backspace in the empty input calls `onChanged([])` with `words: ['--chrome']`.+ - Tapping `launch-flag-remove-0` calls `onChanged([])`.+ - `readOnly: true` disables the input and the ×.+ - `marked: '--model'` gives that chip the error style: find it and check its decoration colour against the theme's+ danger token used elsewhere in super_tabs.+ - While the input has focus, the help line reads "Press Enter or Space to add · ⌫ removes the last flag". If the help+ line lives in the card instead, move this assertion to Task 3 and note it.+- [ ] **Step 2: Run** `cd desktop && flutter test test/launch_flags_field_test.dart`. Expected: FAIL (file missing).+- [ ] **Step 3: Implement `LaunchFlagsField`.** A `Wrap` of chips (monospace via `AppType`) followed by a borderless+ `TextField`, in a bordered box using the field tokens other super_tabs inputs use.+- [ ] **Step 4: Run** the same test plus `flutter analyze lib/super_tabs/launch_flags_field.dart`. Expected: PASS, no+ issues.+- [ ] **Step 5: Commit**+ ```bash+ git add desktop/lib/super_tabs/launch_flags_field.dart desktop/test/launch_flags_field_test.dart+ git commit -m "desktop: launch flags as chips"+ ```++### Task 3: The Buddy card and the Board's Buddy pane header++**Files:**+- Create: `desktop/lib/super_tabs/buddy_card.dart`+- Modify: `desktop/lib/super_tabs/view.dart`: `_boardChat` (~line 3590), the header `Expanded(child: Text(onBuddy ? 'Your Buddy' : ...))`+- Test: `desktop/test/super_tab_board_buddy_card_test.dart`++**Interfaces:**+- Consumes:+ - from Task 1: `buddyMachineAgent`, `restartBuddyWithFlags`, `BuddyRestartOutcome`, `launchArgsLine`;+ - from Task 2: `LaunchFlagsField`;+ - existing: `buddyMachineName`, `externalEngineName`, `showRenameBuddy`, `confirmRemoveBuddy`.+- Produces:+ - `class BuddyCardButton extends StatefulWidget`, with constructor+ `({required SuperTabController controller, required String projectId, AppNotifier? app, required String label})`.+ - It draws the header button (avatar, `label`, chevron) and owns the anchored card. Follow `identity_card.dart`'s+ anchored-card pattern (`OverlayPortal`).+ - Keys: button `ValueKey('super-board-buddy-button')`; card `ValueKey('super-buddy-card')`; Restart+ `ValueKey('super-buddy-card-restart')`; Rename `ValueKey('super-buddy-card-rename')`; Remove+ `ValueKey('super-buddy-card-remove')`.+ - `projectId` is the Buddy chat's `group.projectId`, the same one the old menu passed to `showRestartBuddy`.++- [ ] **Step 1: Write the failing tests.** Build the Board as desktop/test/super_tab_board_layout_test.dart does, with+ the machine and agent fakes of super_tab_buddy_restart_test.dart.+ - On the Board with the Buddy chat shown, tapping `super-board-buddy-button` shows `super-buddy-card` with "Running",+ "Runs on" + the machine name, "Engine" + "Claude Code", and a chip `--chrome` (the agent's saved `launchArgs`).+ - After opening a task card's chat (as the layout test does), `super-board-buddy-button` is not found.+ - Esc closes the card. Switching the pane to a task card's chat while the card is open closes it.+ - Adding a chip `--foo` and tapping Restart sends `agent_restart` with `launchArgs: '--chrome --foo'`. Success closes+ the card.+ - A stopped Buddy (agent not live) shows "Stopped" and a button reading "Start". It sends `agent_resume` with+ `launchArgs`.+ - Refused (`INVALID_LAUNCH_ARGS`, detail `--model is set by Harness and can't be added here.`): the detail shows and+ the `--model` chip is marked. Unconfirmed: the didn't-start line shows. No echo: the "Update Harness on <machine>…"+ line shows.+ - After a failure, a second Restart sends a new `agent_restart` (new creationId) with the current chips.+ - Rename opens the existing rename dialog; Remove opens the existing remove confirm.+ - A Buddy whose machine agent is unknown shows "Stopped", no `launch-flag-input`, no `super-buddy-card-restart`, and+ no exception.+- [ ] **Step 2: Run** `cd desktop && flutter test test/super_tab_board_buddy_card_test.dart`. Expected: FAIL.+- [ ] **Step 3: Implement `BuddyCardButton`** in buddy_card.dart, and use it in `_boardChat` in place of the header+ `Text` when `onBuddy`. Leave the non-Buddy branch as is.+- [ ] **Step 4: Run**+ ```+ flutter test test/super_tab_board_buddy_card_test.dart test/super_tab_board_layout_test.dart test/super_tab_buddy_restart_test.dart test/launch_flags_field_test.dart test/agent_restart_launch_args_test.dart test/super_tab_tasks_view_test.dart+ flutter analyze lib/super_tabs+ python3 ../scripts/check-ui-style.py --only desktop/lib/super_tabs+ ```+ Expected: all pass, no new analyze issues in touched files, style check passes.+- [ ] **Step 5: Commit**+ ```bash+ git add desktop/lib/super_tabs/buddy_card.dart desktop/lib/super_tabs/view.dart desktop/test/super_tab_board_buddy_card_test.dart+ git commit -m "desktop: the Board's Buddy card: Restart with launch flags, Rename, Remove"+ ```diff --git a/docs/specs/2026-11-06-board-buddy-card.md b/docs/specs/2026-11-06-board-buddy-card.mdnew file mode 100644index 000000000..85236c3bd--- /dev/null+++ b/docs/specs/2026-11-06-board-buddy-card.md@@ -0,0 +1,81 @@+# The Buddy card on the Board, with launch flags as chips (Diego, 2026-11-06)++## Why++On the Board (#3365) the person's Buddy chat sits in the right pane. That pane's header holds only "Your Buddy" and a+hide icon. The Buddy chat's old header menu (Rename Buddy…, Restart Buddy…, Remove Buddy) is not reachable there.+That menu is in `view.dart`, inside `if (_isBuddyChat(group))`, and is only drawn for the old chat layout. So Restart+Buddy with extra launch flags (#3351, e.g. `--chrome`) disappeared from Desktop.++Mockups: `desktop/mockup/buddy-restart-board.html` (options), `desktop/mockup/buddy-card-flags.html` (chosen: option B's+card, with option C's chip field for the flags).++## Behaviour++### The header+- Swarm v3 (#3445, 2026-11-07) opens the Buddy chat in the middle, from My agents, under a header that is only the words+ "Your Buddy" (`_middleChat`), so nothing on Desktop reached Restart Buddy any more. Mockup:+ `desktop/mockup/buddy-card-v3.html`.+- In that middle header, and in the Board's right pane while it shows the Buddy chat, the title becomes a button: the+ Buddy's avatar, "Your Buddy", and a chevron.+- Clicking it opens the Buddy card, anchored under it. Esc, a click outside, or a second click closes it.+- While a card's chat is shown (the "‹ Your Buddy" back button), the header stays as today, with no card.++### The Buddy card+Top to bottom:+- **Name and status.** The status is "Running" with a green dot when the Buddy's machine agent is live, "Stopped" with+ a grey dot otherwise, and "Restarting…" with an amber dot while a restart runs.+- **Runs on:** the machine name (`buddyMachineName`).+- No Engine row: the facts line under the header already shows and switches the engine.+- **Launch flags:** the chip field below, with the help line under it. The help line is the dialog's copy:+ "Added to <engine>'s command line each time this Buddy starts on <machine>. Your Buddy runs with full permissions.+ Don't put secrets here: other people on that computer can see them." While the field has focus, the help line reads+ "Press Enter or Space to add · ⌫ removes the last flag".+- **Buttons:** **Restart** (primary; it reads **Start** when the Buddy is stopped), **Rename** (`showRenameBuddy`), and+ **Remove** at the right in the destructive style (`confirmRemoveBuddy`).++What the card shows when it applies:+- The Buddy is the main Buddy the chat names (`readerBuddy`), so with several Buddies (#3818) it is that chat's; a+ per-project Buddy chat falls back to `c.buddy(projectId)`.+- The flags field and Restart/Start show only for the reader's own Buddy with an agent on a machine (`c.buddy(...)` with+ a non-empty `harnessId` and `machineId`, as the old menu item required) whose machine agent is loaded, so the card+ knows its saved flags and whether it runs (audit). The card opens only on the reader's own Buddy chat.+- Rename and Remove follow the old menu's rule (`editable`).++### The chip field+- Each saved word (the machine agent's `Agent.launchArgs`) is a chip in monospace with a × that removes it. There are+ no default flags: a Buddy that never saved any shows an empty field.+- After the chips, an input with the hint "add a flag…".+- Enter or Space turns the typed text into chips. Enter never restarts the Buddy; only the Restart button does. The text is split as a shell would split it, so `--add-dir "a b"` gives+ two chips, `--add-dir` and `a b`. An unclosed quote waits for more typing instead of splitting.+- Backspace in an empty input removes the last chip.+- While a restart runs, the field is read-only.+- After a refusal (`INVALID_LAUNCH_ARGS`), the chip the daemon names (the detail's first word, compared to each chip's+ word before any `=`) is marked red until the field changes.++### Restart+- Restart sends the chips as one line (`launchArgsLine(words)`), on the same path the dialog uses:+ - `AppNotifier.restartAgent` with a fresh `restartAttempt`;+ - `launchArgs` omitted when nothing is saved and there are no chips;+ - a stopped Buddy is resumed with the flags, as today.+- While it runs, the button shows a spinner and "Restarting", and Rename and Remove are disabled. Closing and reopening+ the card keeps that state until the restart answers. Text typed but not yet a chip is added before sending; an+ unclosed quote stops the restart with "Close the quote in the launch flags, or remove it."+- Results, shown in the card under the field with the dialog's copy:+ - **success:** the card closes;+ - **`launchArgsIgnored`:** amber line "Update Harness on <machine> to use launch flags.";+ - **refused:** red line with the daemon's detail, and the named chip marked red;+ - **`engineNotStarted`:** red line "The Buddy didn't start with these flags. Fix or clear them and restart.";+ - **any other error:** a red line with `result.error`.+- The restart and its result copy are one shared piece of code, called by both the card and the old dialog. The dialog+ stays for the old chat layout (web), unchanged in behaviour.++## Design++- **Growth, read cost, scale:** none. The card reads what the controller and `AppNotifier` already hold. Nothing new is+ stored.+- **Compatibility:** the same daemon requests as #3351. An older daemon gives the "Update Harness" line, as today.+- **Platforms:** Desktop's Board layout only (`SuperTabView.board`): the middle Buddy chat and the Board's right pane. The web keeps the old menu and dialog.+- **Audience:** the card's actions apply only to the reader's own Buddy, as the menu did.+- **Failure:** every failure is shown in the card and nothing closes on its own. A lost reply shows its error and+ Restart can be pressed again (each press is a fresh intent).