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
Make sharing prominent and simplify its form (#414)
Dee1f83e66f4f05
diff --git a/desktop/design/images/share-form-access.png b/desktop/design/images/share-form-access.pngnew file mode 100644index 000000000..170f10791Binary files /dev/null and b/desktop/design/images/share-form-access.png differdiff --git a/desktop/design/images/share-form-compact.png b/desktop/design/images/share-form-compact.pngnew file mode 100644index 000000000..628922548Binary files /dev/null and b/desktop/design/images/share-form-compact.png differdiff --git a/desktop/design/images/share-form-narrow.png b/desktop/design/images/share-form-narrow.pngnew file mode 100644index 000000000..87d4ec978Binary files /dev/null and b/desktop/design/images/share-form-narrow.png differdiff --git a/desktop/design/images/workspace-share-button.png b/desktop/design/images/workspace-share-button.pngnew file mode 100644index 000000000..d00b086e4Binary files /dev/null and b/desktop/design/images/workspace-share-button.png differdiff --git a/desktop/design/terminal-dialogs.md b/desktop/design/terminal-dialogs.mdindex 6f8aee505..005d09568 100644--- a/desktop/design/terminal-dialogs.md+++ b/desktop/design/terminal-dialogs.md@@ -269,6 +269,22 @@ Keep lists virtualized and retain cached row controls. Arrow movement updatesthe old and new highlights; it should not rebuild the editor or whole catalog.Calculate reveal and paging from the actual measured item extent.+## Share an agent++Share follows the Cmd-N form: the agent name, aligned Access and People fields,+collapsed Options, and Copy link selected. Access opens Private/Public choices+beside the form. Browsing choices never changes access; accepting one applies it+and returns to Copy link. People owns an email editor and the existing invitations.+Options reveals invitation expiry, Comments, and Stop sharing. Expiry applies+to new email invitations, not to the public link. Keep online guidance visible.+Up/Down move within a pane, Tab switches panes, Enter accepts, and Escape backs+out or dismisses. Narrow windows replace the form with the active chooser.+Opening or cancelling the form alone never changes permissions or creates a link.+++++## Review a dialog changeCheck the result with the user's terminal font and colors, an alternate scheme,@@ -289,6 +305,9 @@ Reuse the relevant existing checks:preview navigation and narrow layouts.- [`keymap_runtime_test.dart`](../test/keymap_runtime_test.dart): shortcutrouting and focus ownership.+- [`share_harness_test.dart`](../test/share_harness_test.dart) and+ [`share_toolbar_test.dart`](../test/share_toolbar_test.dart): sharing flows,+ cell layout, responsive draft preservation, shortcuts, and focused-agent scope.When checking a native build, restart into the rebuilt app before judging theresult. An existing process does not pick up a new build automatically.diff --git a/desktop/design/terminal-workspace.md b/desktop/design/terminal-workspace.mdindex cff5c7395..0e7a8dc0f 100644--- a/desktop/design/terminal-workspace.md+++ b/desktop/design/terminal-workspace.md@@ -47,7 +47,9 @@ Keep mouse access useful without adding duplicate floating controls. Clickabletext shows a hand cursor and bold text on hover, press, and keyboard focus.Preserve the underlying colors, including filled status segments. Reserve bothtext weights during layout so emphasis never shifts neighboring controls.-Resting controls stay unboxed. Tooltips describe the+Resting controls stay unboxed, except the persistent Share action: its flat+primary accent fill makes collaboration visible at the top-right corner.+Tooltips describe theaction, not merely the text. Omit a tooltip that repeats the visible name;show the full name when truncated, or a different underlying name. A modelselector says `Switch model · Subscription or local models`; include its fulldiff --git a/desktop/design/workspace-status-bar.md b/desktop/design/workspace-status-bar.mdindex fd6298397..a27005a3c 100644--- a/desktop/design/workspace-status-bar.md+++ b/desktop/design/workspace-status-bar.md@@ -4,7 +4,7 @@ One shared status line, using compact monospace text and measured character cellFollow the [terminal workspace design system](terminal-workspace.md).```text-1:api 2:web 3:blender + M2 autonomous-harness (main)+1:api 2:web 3:blender + M2 autonomous-harness (main) [ Share ]```## Tabs on the left@@ -95,7 +95,20 @@ Pane edges have no floating split buttons. Split Right and Split Down remainkeyboard commands (Cmd-R and Cmd-D by default), with File menu and command-searchaccess. Keep the resize gaps available for resizing.-Restart Harness and Share Harness belong in File. Fork remains available in+Share is a persistent primary action at the far right of the top bar, with a+flat accent fill, white text, and the same fixed font and control height as the+other bar actions. Reserve its width before allocating tabs and context. Web+keeps Download app as a secondary text action immediately before Share.+Clicking Share or pressing Cmd-Shift-S (Alt-Shift-S on web) opens the existing+public/private link dialog for the focused agent. The tooltip and accessibility+label name that agent; the shortcut hint follows remaps. A dependent viewer+shares its owner. Empty tabs and view-only shared agents keep a disabled button.+Opening Share alone does not create a link or change access. Native macOS and+Flutter use the same command, labels, resolved colors, and availability.++++Restart Harness and Share Harness also belong in File. Fork remains available incommand search. Viewer and message-composer toggles belong in View and commandsearch. These actions apply to the focused pane; sharing and viewer visibilityfollow a dependent viewer's owner.@@ -235,7 +248,7 @@ References: [Zsh prompt parameters](https://zsh.sourceforge.io/Doc/Release/Param[Powerlevel10k](https://github.com/romkatv/powerlevel10k).Pane headers keep task identity and the hover-only close action. The top bar-contains tabs, New Tab, and focused model/machine/project/branch/PR context.+contains tabs, New Tab, focused model/machine/project/branch/PR context, and Share.Do not add a standalone Search label or category icons at the right edge.Context links open the corresponding scope in the unified picker. Globalsearch remains available through Cmd-P and the app menu.diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex e96c4a307..6786d4277 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -64,6 +64,7 @@ import '../widgets/workspace_status_line.dart';import '../widgets/workspace_bar_control.dart';import '../widgets/session_work_dialog.dart';import '../widgets/web_download_button.dart';+import '../widgets/workspace_share_button.dart';import '../widgets/grid_model_picker.dart';import '../store/store_mark.dart';import '../store/store_screen.dart';@@ -506,6 +507,7 @@ class _SwarmScreenState extends State<SwarmScreen> {void _keymapChanged() {_syncKeymap();+ if (_native) _syncNative();if (mounted) setState(() {});_search?.refreshCommands();}@@ -1148,6 +1150,21 @@ class _SwarmScreenState extends State<SwarmScreen> {'canReopen': app.canReopenLastClosed,'canFind': _canFindTerminal,'canClosePane': app.focusedPane != null,+ 'shareAction': {+ 'text': WorkspaceShareButton.text,+ 'label': _shareLabel(focused),+ 'tooltip': _shareTooltip(focused),+ 'enabled': _canExecuteCommand('agent.share'),+ 'paneId': focused?.pane.id,+ 'machineId': focused?.pane.machineId,+ 'agentId': focused?.agentId,+ 'background': WorkspaceShareButton.backgroundFor(+ _canExecuteCommand('agent.share'),+ ).toARGB32(),+ 'foreground': WorkspaceShareButton.foregroundFor(+ _canExecuteCommand('agent.share'),+ ).toARGB32(),+ },'paneActions': {'restartAgent': _canExecuteCommand('agent.restart'),'shareAgent': _canExecuteCommand('agent.share'),@@ -1363,6 +1380,15 @@ class _SwarmScreenState extends State<SwarmScreen> {return;}final args = call.arguments is Map ? call.arguments as Map : const {};+ if (call.method == 'shareAgent' && args.containsKey('paneId')) {+ final focused = WorkspacePaneContext.focused(app);+ if (focused == null ||+ focused.pane.id != args['paneId'] ||+ focused.pane.machineId != args['machineId'] ||+ focused.agentId != args['agentId']) {+ return;+ }+ }if (call.method == 'focusedModel') {if (args['paneId'] is int) {final expectedPane = args['paneId'];@@ -1830,6 +1856,20 @@ class _SwarmScreenState extends State<SwarmScreen> {);});+ String _shareLabel(WorkspacePaneContext? focused) =>+ focused?.agent == null ? 'Share' : 'Share ${focused!.agent!.displayName}';++ String _shareTooltip(WorkspacePaneContext? focused) {+ if (focused?.agent == null) return 'Focus an agent to share it';+ if (app.stateOf(focused!.pane.machineId)?.machine.isShared != false) {+ return 'Only the owner can share this agent';+ }+ return [+ _shareLabel(focused),+ _keymap.hint('agent.share'),+ ].whereType<String>().join(' · ');+ }+void _toggleFocusedViewer() {final focused = WorkspacePaneContext.focused(app);if (focused?.agentId case final id?) {@@ -3896,6 +3936,7 @@ class _SwarmScreenState extends State<SwarmScreen> {ShortcutAction.newTerminal: _newTerminal,ShortcutAction.cloneAgent: _cloneAgent,ShortcutAction.restartAgent: _restartAgent,+ ShortcutAction.shareAgent: _shareAgent,ShortcutAction.routeTask: () =>_dialog(() => showTaskPalette(context, app)),ShortcutAction.orchestrate: () =>@@ -3945,7 +3986,6 @@ class _SwarmScreenState extends State<SwarmScreen> {},'agent.stop': () => _editAgent(stop: true),'agent.fork': _forkAgent,- 'agent.share': _shareAgent,'pane.toggle_viewer': _toggleFocusedViewer,'pane.toggle_composer': () {if (app.focusedPaneId case final id?) app.toggleComposer(id);@@ -4752,9 +4792,10 @@ class _SwarmScreenState extends State<SwarmScreen> {final downloadWidth = kIsWeb? WebDownloadButton.widthOf(context) + cell.width: 0.0;+ final shareWidth = WorkspaceShareButton.widthOf(context) + cell.width;final contentWidth = math.max(0.0,- constraints.maxWidth - cell.width * 7 - downloadWidth,+ constraints.maxWidth - cell.width * 7 - downloadWidth - shareWidth,);final tabBudget = contentWidth * .45;_tabWidths = [@@ -4900,7 +4941,9 @@ class _SwarmScreenState extends State<SwarmScreen> {mainAxisSize: MainAxisSize.min,mainAxisAlignment: MainAxisAlignment.end,children: [- if (modelPickerSupports(focused.engine)) ...[+ if (modelPickerSupports(focused.engine) &&+ constraints.maxWidth >=+ cell.width * 12) ...[ConstrainedBox(constraints: BoxConstraints(maxWidth: constraints.maxWidth * .35,@@ -4956,6 +4999,15 @@ class _SwarmScreenState extends State<SwarmScreen> {const WebDownloadButton(),],SizedBox(width: cell.width),+ WorkspaceShareButton(+ key: const ValueKey('workspace-share-button'),+ label: _shareLabel(focused),+ tooltip: _shareTooltip(focused),+ onPressed: _canExecuteCommand('agent.share')+ ? () => _runShortcut('agent.share')+ : null,+ ),+ SizedBox(width: cell.width),],),),diff --git a/desktop/lib/sharing/share_harness_dialog.dart b/desktop/lib/sharing/share_harness_dialog.dartindex b611c8e9a..9ae18448a 100644--- a/desktop/lib/sharing/share_harness_dialog.dart+++ b/desktop/lib/sharing/share_harness_dialog.dart@@ -1,10 +1,15 @@import 'dart:async';+import 'dart:math' as math;import 'package:flutter/services.dart';import 'package:flutter/material.dart';import '../shared/theme/app_theme.dart' as grid;+import '../shortcuts/app_keymap.dart';+import '../shortcuts/keymap.dart';+import '../shortcuts/keymap_commands.dart';+import '../shortcuts/keymap_keyboard.dart';import '../terminal/terminal_text.dart';import '../terminal/terminal_theme.dart';import '../terminal/terminal_theme_store.dart';@@ -47,14 +52,29 @@ class ShareHarnessDialog extends StatefulWidget {State<ShareHarnessDialog> createState() => _ShareHarnessDialogState();}+enum _ShareRow { access, people, options, expiry, comments, stop, copy, retry }+class _ShareHarnessDialogState extends State<ShareHarnessDialog> {+ final _focus = FocusNode(debugLabel: 'share-form');+ final _emailFocus = FocusNode(debugLabel: 'share-emails');+ final _commentsFocus = FocusNode(debugLabel: 'share-comments');+ final _commentsKey = GlobalKey();+ final _formScroll = ScrollController();+ final _sideScroll = ScrollController();+ final _rowKeys = {for (final row in _ShareRow.values) row: GlobalKey()};+ final _choiceKeys = <int, GlobalKey>{};+ _ShareRow _row = _ShareRow.copy;+ bool _options = false, _picking = false, _hideChoices = false;+ int _choice = 0;+ double _column = 8, _line = 20;+final _emails = TextEditingController();List<Map<String, dynamic>> _shares = [];bool _loading = true, _busy = false;String? _error, _notice;int _days = 30;Map<String, dynamic>? _link;- bool _collaboration = false, _comments = false, _manualCopy = false;+ bool _collaboration = false, _manualCopy = false;Timer? _presence;int _revision = 0;bool _refreshing = false;@@ -71,6 +91,11 @@ class _ShareHarnessDialogState extends State<ShareHarnessDialog> {void dispose() {_presence?.cancel();_emails.dispose();+ _focus.dispose();+ _emailFocus.dispose();+ _commentsFocus.dispose();+ _formScroll.dispose();+ _sideScroll.dispose();super.dispose();}@@ -81,6 +106,10 @@ class _ShareHarnessDialogState extends State<ShareHarnessDialog> {? error.detail!: 'Could not reach this harness. Check the connection and try again.';void _accept(Map<String, dynamic> response) {+ final recipientId =+ _row == _ShareRow.people && _choice >= 2 && _choice - 2 < _shares.length+ ? _shares[_choice - 2]['id']+ : null;_collaboration = response['collaboration'] == true;_link = response['link'] is Map? Map<String, dynamic>.from(response['link'] as Map)@@ -89,6 +118,11 @@ class _ShareHarnessDialogState extends State<ShareHarnessDialog> {for (final row in response['shares'] as List? ?? const [])Map<String, dynamic>.from(row as Map),];+ if (recipientId != null) {+ final index = _shares.indexWhere((share) => share['id'] == recipientId);+ _choice = index < 0 ? 0 : index + 2;+ if (_picking && index < 0) _focusPane();+ }}Future<void> _load({bool quiet = false}) async {@@ -158,7 +192,10 @@ class _ShareHarnessDialogState extends State<ShareHarnessDialog> {} catch (error) {if (mounted) setState(() => _error = _message(error));} finally {- if (mounted) setState(() => _busy = false);+ if (mounted) {+ setState(() => _busy = false);+ if (_picking && _row == _ShareRow.people) _focusPane();+ }}}@@ -181,7 +218,10 @@ class _ShareHarnessDialogState extends State<ShareHarnessDialog> {} catch (error) {if (mounted) setState(() => _error = _message(error));} finally {- if (mounted) setState(() => _busy = false);+ if (mounted) {+ setState(() => _busy = false);+ if (_picking && _row == _ShareRow.people) _focusPane();+ }}}@@ -228,296 +268,716 @@ class _ShareHarnessDialogState extends State<ShareHarnessDialog> {}}+ bool get _disabled => _busy || _loading;+ bool get _isPublic => _link?['visibility'] == 'public';+ bool get _linkActive => _link != null && _link?['visibility'] != 'off';+ bool get _composing =>+ _emails.value.composing.isValid && !_emails.value.composing.isCollapsed;+ bool get _hasChoices =>+ _row == _ShareRow.access ||+ _row == _ShareRow.people ||+ _row == _ShareRow.expiry ||+ _row == _ShareRow.comments;+ List<_ShareRow> get _rows => [+ if (_collaboration) _ShareRow.access,+ if (!_isPublic) _ShareRow.people,+ _ShareRow.options,+ if (_options) ...[+ if (!_isPublic) _ShareRow.expiry,+ if (_collaboration) _ShareRow.comments,+ if (_linkActive) _ShareRow.stop,+ ],+ _ShareRow.copy,+ if (_error != null) _ShareRow.retry,+ ];++ String _label(_ShareRow row) => switch (row) {+ _ShareRow.access => 'Access',+ _ShareRow.people => 'People',+ _ShareRow.options => 'Options',+ _ShareRow.expiry => 'Invite for',+ _ShareRow.comments => 'Comments',+ _ShareRow.stop => 'Stop sharing',+ _ShareRow.copy => _busy ? 'Saving…' : 'Copy link',+ _ShareRow.retry => 'Retry',+ };+ String? _value(_ShareRow row) => switch (row) {+ _ShareRow.access => _isPublic ? 'Public' : 'Private',+ _ShareRow.people =>+ _shares.isEmpty+ ? 'Only you'+ : '${_shares.length} ${_shares.length == 1 ? 'person' : 'people'}',+ _ShareRow.options => _options ? '[-]' : '[+]',+ _ShareRow.expiry => '$_days days',+ _ShareRow.comments => 'Open discussion',+ _ => null,+ };+ bool _enabled(_ShareRow row) =>+ !_disabled && (row != _ShareRow.copy || _collaboration);++ void _select(_ShareRow row, {bool enter = false}) {+ if (!_enabled(row)) return;+ setState(() {+ _row = row;+ _picking = enter && _hasChoices;+ _hideChoices = false;+ _choice = switch (row) {+ _ShareRow.access => _isPublic ? 1 : 0,+ _ShareRow.expiry => const [7, 30, 90].indexOf(_days),+ _ => 0,+ };+ });+ _focusPane();+ }++ void _focusPane() {+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted) return;+ if (_picking && _row == _ShareRow.people && _choice == 0) {+ _emailFocus.requestFocus();+ } else if (_picking && _row == _ShareRow.comments) {+ _commentsFocus.requestFocus();+ } else {+ _focus.requestFocus();+ }+ final target =+ (_picking ? _choiceKeys[_choice] : _rowKeys[_row])?.currentContext;+ if (target != null) Scrollable.ensureVisible(target, alignment: .5);+ });+ }++ void _backToForm({bool selectCopy = false}) {+ setState(() {+ _picking = false;+ _hideChoices = true;+ if (selectCopy) _row = _ShareRow.copy;+ });+ _focusPane();+ }++ void _cancel() {+ if (_picking || (_hasChoices && !_hideChoices)) {+ _backToForm();+ } else {+ Navigator.of(context).pop();+ }+ }++ void _switchPane() {+ if (_disabled || !_hasChoices) return;+ if (_picking) {+ _backToForm();+ } else {+ setState(() {+ _picking = true;+ _hideChoices = false;+ });+ _focusPane();+ }+ }++ void _step(int delta) {+ if (_disabled) return;+ if (_picking) {+ final count = switch (_row) {+ _ShareRow.access => 2,+ _ShareRow.expiry => 3,+ _ShareRow.people => _shares.length + 2,+ _ => 0,+ };+ if (count == 0) return;+ setState(() => _choice = (_choice + delta) % count);+ _focusPane();+ } else {+ final rows = _rows.where(_enabled).toList();+ if (rows.isNotEmpty) {+ _select(rows[(rows.indexOf(_row) + delta) % rows.length]);+ }+ }+ }++ Future<void> _chooseVisibility(int index) async {+ final visibility = index == 0 ? 'private' : 'public';+ if (_linkActive && _link?['visibility'] == visibility) {+ _backToForm(selectCopy: true);+ return;+ }+ await _linkAction(visibility);+ if (mounted && _error == null) _backToForm(selectCopy: true);+ }++ void _activate() {+ if (_disabled) return;+ if (!_picking) {+ if (!_enabled(_row)) return;+ switch (_row) {+ case _ShareRow.options:+ _toggleOptions();+ case _ShareRow.copy:+ unawaited(_linkAction('private', copy: true));+ case _ShareRow.stop:+ unawaited(_stopSharing());+ case _ShareRow.retry:+ unawaited(_load());+ default:+ _switchPane();+ }+ } else {+ switch (_row) {+ case _ShareRow.access:+ unawaited(_chooseVisibility(_choice));+ case _ShareRow.expiry:+ setState(() => _days = const [7, 30, 90][_choice]);+ _backToForm(selectCopy: true);+ case _ShareRow.people:+ if (_choice < 2) {+ if (_emails.text.trim().isNotEmpty) unawaited(_invite());+ } else if (_choice - 2 < _shares.length) {+ unawaited(_remove(_shares[_choice - 2]['id'] as String));+ }+ default:+ break;+ }+ }+ }++ Future<void> _stopSharing() async {+ await _linkAction('off');+ if (mounted && _error == null) _backToForm(selectCopy: true);+ }++ void _toggleOptions() {+ if (_disabled) return;+ setState(() {+ _options = !_options;+ if (!_rows.contains(_row)) {+ _row = _ShareRow.options;+ _picking = false;+ _hideChoices = true;+ }+ });+ _focusPane();+ }++ KeyEventResult _key(FocusNode node, KeyEvent event) {+ if (event is! KeyDownEvent && event is! KeyRepeatEvent) {+ return KeyEventResult.ignored;+ }+ if (_composing) return KeyEventResult.skipRemainingHandlers;+ if (_picking && _row == _ShareRow.comments) return KeyEventResult.ignored;+ final stroke = keyStrokeForEvent(event);+ final map =+ KeymapTheme.of(context, listen: false)?.current ?? harnessDefaultKeymap;+ final command = stroke == null+ ? null+ : map.match(KeymapContext.picker, [stroke]).command;+ final action = _keyActions[command];+ // Left/right retain caret behavior while an email address is being edited.+ if (_emailFocus.hasFocus &&+ (event.logicalKey == LogicalKeyboardKey.arrowLeft ||+ event.logicalKey == LogicalKeyboardKey.arrowRight)) {+ return KeyEventResult.ignored;+ }+ if (action != null) {+ if (event is! KeyRepeatEvent ||+ command == 'picker.next' ||+ command == 'picker.previous') {+ action();+ }+ return KeyEventResult.handled;+ }+ if (event.logicalKey == LogicalKeyboardKey.enter ||+ event.logicalKey == LogicalKeyboardKey.numpadEnter) {+ return KeyEventResult.handled;+ }+ if (_emailFocus.hasFocus) return KeyEventResult.ignored;+ if (event.logicalKey == LogicalKeyboardKey.space &&+ _row == _ShareRow.options) {+ if (event is KeyDownEvent) _activate();+ return KeyEventResult.handled;+ }+ // Like Cmd-N, typing on People enters its editor with that first character.+ final character = event.character;+ if (_row == _ShareRow.people &&+ !_disabled &&+ !HardwareKeyboard.instance.isMetaPressed &&+ !HardwareKeyboard.instance.isControlPressed &&+ character != null &&+ character.isNotEmpty &&+ character.codeUnitAt(0) >= 32) {+ _emails.text += character;+ _emails.selection = TextSelection.collapsed(offset: _emails.text.length);+ setState(() {+ _picking = true;+ _hideChoices = false;+ _choice = 0;+ });+ _focusPane();+ return KeyEventResult.handled;+ }+ return KeyEventResult.ignored;+ }++ Map<String, VoidCallback> get _keyActions => {+ 'picker.accept': _activate,+ 'picker.cancel': _cancel,+ 'picker.next': () => _step(1),+ 'picker.previous': () => _step(-1),+ 'picker.complete': _switchPane,+ 'picker.complete_back': _switchPane,+ 'picker.control_next': () {+ if (!_picking) _switchPane();+ },+ 'picker.control_previous': () {+ if (_picking) _backToForm();+ },+ 'picker.more_options': _toggleOptions,+ };+@overrideWidget build(BuildContext context) {grid.AppTheme.watch(context);+ TerminalFontScope.watch(context);return ListenableBuilder(listenable: Listenable.merge([terminalFontStore, terminalThemeStore]),builder: (context, _) {final cell = terminalCellSizeOf(context);+ _column = cell.width;+ _line = cell.height;final theme = terminalThemeFor(grid.AppTheme.palette.value,terminalThemeStore.value,);final style = terminalContentStyle(color: theme.foreground);- final muted = style.copyWith(- color: theme.foreground.withValues(alpha: .6),+ final muted = theme.foreground.withValues(alpha: .54);+ Widget surface(Key key, Widget child) => Material(+ key: key,+ color: theme.background,+ elevation: 0,+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(kTerminalCornerRadius),+ side: terminalPaneBorder(focused: true),+ ),+ clipBehavior: Clip.antiAlias,+ child: DefaultTextStyle(style: style, child: child),);- final isPublic = _link?['visibility'] == 'public';- final disabled = _busy || _loading;- final gap = SizedBox(height: cell.height);- Widget action(String label, VoidCallback? run) =>- TerminalTextAction(label: label, onPressed: run);- return TerminalPromptKeys(- cancel: () => Navigator.of(context).pop(),- child: Dialog(- backgroundColor: theme.background,- surfaceTintColor: Colors.transparent,- elevation: 0,- insetPadding: EdgeInsets.symmetric(- horizontal: cell.width * 2,- vertical: cell.height * 2,- ),- shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(kTerminalCornerRadius),- side: terminalPaneBorder(focused: true),+ return KeymapRegion(+ contextKind: KeymapContext.picker,+ composing: () => _composing,+ actions: _keyActions,+ child: Focus(+ focusNode: _focus,+ autofocus: true,+ onKeyEvent: _key,+ child: Padding(+ padding: EdgeInsets.symmetric(+ horizontal: _column * 2,+ vertical: _line,+ ),+ child: LayoutBuilder(+ builder: (context, constraints) {+ final columns = math.max(+ 1,+ (constraints.maxWidth / _column).floor(),+ );+ final formColumns = math.min(56, columns);+ final left = (columns - formColumns) ~/ 2;+ final available = columns - left - formColumns - 1;+ final beside = available >= 28;+ final showChoices = _hasChoices && !_hideChoices;+ final replaceForm = _picking && !beside;+ final formWidth = formColumns * _column;+ final rows = _rows;+ var formRows = 5 + rows.length + 3;+ if (rows.contains(_ShareRow.people)) formRows++;+ // Copy follows the fields with one blank row; notices get their own rows.+ for (final message in _messages) {+ final painter =+ TextPainter(+ text: TextSpan(text: message, style: style),+ textDirection: TextDirection.ltr,+ textScaler: MediaQuery.textScalerOf(context),+ )..layout(+ maxWidth: math.max(_column, formWidth - _column * 4),+ );+ formRows += 1 + (painter.height / _line).ceil();+ painter.dispose();+ }+ final formHeight = math.min(+ constraints.maxHeight,+ formRows * _line,+ );+ final sideHeight = math.min(+ constraints.maxHeight,+ ((_row == _ShareRow.access+ ? 12+ : _row == _ShareRow.expiry+ ? 11+ : _row == _ShareRow.people+ ? math.min(20, 12 + _shares.length * 4)+ : 20) ++ (replaceForm ? 2 : 0)) *+ _line,+ );+ final top = math.max(+ 0.0,+ ((constraints.maxHeight - formHeight) / (2 * _line))+ .floor() *+ _line,+ );+ final sideTop = math.min(+ top,+ constraints.maxHeight - sideHeight,+ );+ return Stack(+ children: [+ Positioned(+ left: left * _column,+ top: replaceForm ? sideTop : top,+ width: formWidth,+ height: replaceForm ? sideHeight : formHeight,+ child: surface(+ const ValueKey('share-form-surface'),+ replaceForm+ ? _sidePane(+ theme.foreground,+ muted,+ theme.selection,+ narrow: true,+ )+ : _formPane(+ theme.foreground,+ muted,+ theme.selection,+ ),+ ),+ ),+ if (showChoices && beside)+ Positioned(+ left: (left + formColumns + 1) * _column,+ top: sideTop,+ width: math.min(40, available) * _column,+ height: sideHeight,+ child: surface(+ const ValueKey('share-choices-surface'),+ _sidePane(theme.foreground, muted, theme.selection),+ ),+ ),+ ],+ );+ },+ ),),- child: DefaultTextStyle(- style: style,- child: SizedBox(- width: cell.width * 68,- child: ConstrainedBox(- constraints: BoxConstraints(- maxHeight: MediaQuery.sizeOf(context).height * .8,+ ),+ );+ },+ );+ }++ List<String> get _messages => [+ if (_loading) 'Loading sharing…',+ if (!_loading && !_collaboration && _error == null)+ 'Update Harness on this machine to share browser links and comments.',+ ?_error,+ ?_notice,+ if (_link?['error'] != null && _link?['error'] != _error)+ '${_link!['error']}',+ if (_manualCopy && _link?['url'] is String) _link!['url'] as String,+ ];++ Widget _plainRow({+ required String label,+ String? value,+ required bool selected,+ required bool enabled,+ required Color foreground,+ required Color muted,+ required Color selection,+ required VoidCallback onTap,+ Key? key,+ Key? rowKey,+ }) => Semantics(+ key: key,+ label: value == null ? label : '$label, $value',+ button: true,+ selected: selected,+ enabled: enabled,+ onTap: enabled ? onTap : null,+ excludeSemantics: true,+ child: MouseRegion(+ cursor: enabled ? SystemMouseCursors.click : SystemMouseCursors.basic,+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: enabled ? onTap : null,+ child: Container(+ key: rowKey,+ height: _line,+ color: selected && enabled ? selection : Colors.transparent,+ padding: EdgeInsets.symmetric(horizontal: _column),+ alignment: Alignment.centerLeft,+ child: value == null+ ? Text(+ label,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: terminalContentStyle(+ color: enabled ? foreground : muted,),- child: Padding(- padding: EdgeInsets.symmetric(- horizontal: cell.width * 2,- vertical: cell.height,+ )+ : Row(+ children: [+ SizedBox(+ width: _column * 11,+ child: Text(+ label,+ style: terminalContentStyle(color: muted),+ ),),- child: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- Row(- children: [- Expanded(- child: Text(- 'Share ${widget.name}',- overflow: TextOverflow.ellipsis,- style: style.copyWith(- fontWeight: FontWeight.bold,- ),- ),- ),- if (_collaboration)- action(- _comments ? 'Access' : 'Comments',- () => setState(() => _comments = !_comments),- ),- action('Done', () => Navigator.of(context).pop()),- ],+ Expanded(+ child: Text(+ value,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: terminalContentStyle(+ color: enabled ? foreground : muted,),- gap,- if (_comments)- Flexible(- child: SizedBox(- height: cell.height * 25,- child: HarnessComments(manage: widget.manage),- ),- )- else- Flexible(- child: SingleChildScrollView(- child: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- if (_loading) const Text('Loading sharing…'),- if (!_loading && !_collaboration)- const Text(- 'Update Harness on this machine to share browser links and comments.',- ),- if (_collaboration) ...[- Wrap(- children: [- action(- '${!isPublic ? 'x' : ' '} Private',- disabled- ? null- : () => _linkAction('private'),- ),- action(- '${isPublic ? 'x' : ' '} Public',- disabled- ? null- : () => _linkAction('public'),- ),- ],- ),- Text(- isPublic- ? 'Anyone with the link can view live output and comments.'- : 'Only the emails you add can view and comment.',- style: muted,- ),- gap,- Wrap(- children: [- action(- _busy ? 'Saving…' : 'Copy link',- disabled- ? null- : () => _linkAction(- 'private',- copy: true,- ),- ),- if (_link != null &&- _link?['visibility'] != 'off')- action(- 'Stop sharing',- disabled- ? null- : () => _linkAction('off'),- ),- ],- ),- if (_manualCopy && _link?['url'] is String)- Padding(- padding: EdgeInsets.only(- top: cell.height,- ),- child: SelectableText(- _link!['url'] as String,- style: muted,- ),- ),- if (_link?['error'] != null)- Text('${_link!['error']}'),- gap,- ],- if (!isPublic) ...[- const Text('Add people by email'),- TextField(- controller: _emails,- autofocus: true,- enabled: !disabled,- keyboardType: TextInputType.emailAddress,- maxLines: 2,- minLines: 1,- style: style,- cursorColor: theme.cursor,- decoration: InputDecoration(- hintText: '[email protected], [email protected]',- hintStyle: muted,- filled: false,- border: InputBorder.none,- enabledBorder: InputBorder.none,- focusedBorder: InputBorder.none,- contentPadding: EdgeInsets.symmetric(- vertical: cell.height / 2,- ),- ),- onSubmitted: (_) => _invite(),- onChanged: (_) => setState(() {}),- ),- Wrap(- crossAxisAlignment:- WrapCrossAlignment.center,- children: [- const Text('Expires in '),- for (final days in [7, 30, 90])- action(- '${_days == days ? 'x ' : ''}$days days',- disabled- ? null- : () => setState(- () => _days = days,- ),- ),- action(- 'Add people',- disabled ||- _emails.text.trim().isEmpty- ? null- : _invite,- ),- ],- ),- ],- if (_error != null)- Padding(- padding: EdgeInsets.only(- top: cell.height,- ),- child: Semantics(- liveRegion: true,- child: Text(- _error!,- style: style.copyWith(- color: theme.red,- ),- ),- ),- ),- if (_notice != null)- Padding(- padding: EdgeInsets.only(- top: cell.height,- ),- child: Semantics(- liveRegion: true,- child: Text(_notice!),- ),- ),- gap,- if (!_loading && !isPublic && _shares.isEmpty)- Text(- 'No invited people yet.',- style: muted,- ),- for (final share- in isPublic- ? <Map<String, dynamic>>[]- : _shares)- Padding(- padding: EdgeInsets.only(- bottom: cell.height,- ),- child: Column(- crossAxisAlignment:- CrossAxisAlignment.stretch,- children: [- Row(- children: [- Expanded(- child: Text(- '${share['email']}',- overflow:- TextOverflow.ellipsis,- ),- ),- action(- 'Remove',- _busy- ? null- : () => _remove(- share['id'] as String,- ),- ),- ],- ),- Text(- _recipientStatus(share),- style: muted,- ),- ],- ),- ),- Text(- 'Keep your machine online while people watch. Viewers can comment; they cannot control your agent.',- style: muted,- ),- if (_error != null && !_busy)- Align(- alignment: Alignment.centerLeft,- child: action('Retry', () => _load()),- ),- ],- ),- ),- ),- ],+ ),),- ),+ ],),+ ),+ ),+ ),+ );++ Widget _formPane(Color foreground, Color muted, Color selection) =>+ SingleChildScrollView(+ controller: _formScroll,+ padding: EdgeInsets.symmetric(horizontal: _column, vertical: _line),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Padding(+ padding: EdgeInsets.symmetric(horizontal: _column),+ child: Text(+ 'Share ${widget.name}',+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: terminalContentStyle(color: foreground)+ .copyWith(fontWeight: FontWeight.bold),),),- ),- );+ SizedBox(height: _line),+ for (final row in _rows) ...[+ if (row == _ShareRow.people ||+ row == _ShareRow.options ||+ row == _ShareRow.copy)+ SizedBox(height: _line),+ _plainRow(+ key: ValueKey('share-field-${row.name}'),+ rowKey: _rowKeys[row],+ label: _label(row),+ value: _value(row),+ selected: _row == row && !_picking,+ enabled: _enabled(row),+ foreground: foreground,+ muted: muted,+ selection: selection,+ onTap: () {+ _select(row);+ _activate();+ },+ ),+ ],+ if (!_picking) ..._messageWidgets(foreground),+ SizedBox(height: _line),+ Padding(+ padding: EdgeInsets.symmetric(horizontal: _column),+ child: Text(+ 'Keep your machine online.',+ style: terminalContentStyle(color: muted),+ ),+ ),+ ],+ ),+ );++ List<Widget> _messageWidgets(Color foreground) => [+ for (final message in _messages) ...[+ SizedBox(height: _line),+ Padding(+ padding: EdgeInsets.symmetric(horizontal: _column),+ child: Semantics(+ liveRegion: true,+ child: _manualCopy && message == _link?['url']+ ? SelectableText(+ message,+ style: terminalContentStyle(color: foreground),+ )+ : Text(message, style: terminalContentStyle(color: foreground)),+ ),+ ),+ ],+ ];++ Widget _sidePane(+ Color foreground,+ Color muted,+ Color selection, {+ bool narrow = false,+ }) {+ Widget choice(+ String label,+ int index,+ VoidCallback activate, {+ bool enabled = true,+ String? value,+ }) => _plainRow(+ key: ValueKey('share-choice-$index'),+ rowKey: _choiceKeys.putIfAbsent(index, GlobalKey.new),+ label: label,+ value: value,+ selected: _picking && _choice == index,+ enabled: enabled && !_disabled,+ foreground: foreground,+ muted: muted,+ selection: selection,+ onTap: () {+ setState(() {+ _picking = true;+ _choice = index;+ });+ activate();},);+ Widget note(String text) => Padding(+ padding: EdgeInsets.symmetric(horizontal: _column),+ child: Text(text, style: terminalContentStyle(color: muted)),+ );+ if (_row == _ShareRow.comments && _picking) {+ return TerminalPromptKeys(+ focusNode: _commentsFocus,+ cancel: _backToForm,+ child: Padding(+ padding: EdgeInsets.all(_column * 2),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Align(+ alignment: Alignment.centerLeft,+ child: TerminalTextAction(+ label: 'Back',+ onPressed: _backToForm,+ ),+ ),+ SizedBox(height: _line),+ Expanded(+ child: HarnessComments(+ key: _commentsKey,+ manage: widget.manage,+ ),+ ),+ ],+ ),+ ),+ );+ }+ return SingleChildScrollView(+ controller: _sideScroll,+ padding: EdgeInsets.symmetric(horizontal: _column, vertical: _line),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (narrow) ...[+ _plainRow(+ key: const ValueKey('share-back'),+ label: '< Back',+ selected: false,+ enabled: true,+ foreground: foreground,+ muted: muted,+ selection: selection,+ onTap: _backToForm,+ ),+ SizedBox(height: _line),+ ],+ if (_row == _ShareRow.access) ...[+ choice('Private', 0, () => unawaited(_chooseVisibility(0))),+ note('Only invited emails can view and comment.'),+ SizedBox(height: _line),+ choice('Public', 1, () => unawaited(_chooseVisibility(1))),+ note('Anyone with the link can view. Sign in to comment.'),+ SizedBox(height: _line),+ note('Viewers cannot control your agent.'),+ ],+ if (_row == _ShareRow.expiry) ...[+ for (var i = 0; i < 3; i++)+ choice('${const [7, 30, 90][i]} days', i, () {+ setState(() => _days = const [7, 30, 90][i]);+ _backToForm(selectCopy: true);+ }),+ SizedBox(height: _line),+ note(+ 'Applies to new invitations. Your link stays active until you stop sharing.',+ ),+ ],+ if (_row == _ShareRow.people) ...[+ Padding(+ padding: EdgeInsets.symmetric(horizontal: _column),+ child: TextField(+ key: _choiceKeys.putIfAbsent(0, GlobalKey.new),+ controller: _emails,+ focusNode: _emailFocus,+ enabled: !_disabled,+ keyboardType: TextInputType.emailAddress,+ style: terminalContentStyle(color: foreground),+ cursorWidth: 2,+ decoration: InputDecoration(+ hintText: 'Add emails',+ hintStyle: terminalContentStyle(color: muted),+ isDense: true,+ filled: false,+ border: InputBorder.none,+ enabledBorder: InputBorder.none,+ focusedBorder: InputBorder.none,+ contentPadding: EdgeInsets.zero,+ ),+ onTap: () => setState(() {+ _picking = true;+ _choice = 0;+ }),+ onChanged: (_) => setState(() {}),+ onSubmitted: (_) {+ if (!_composing && !_disabled) unawaited(_invite());+ },+ ),+ ),+ choice(+ 'Add people',+ 1,+ () => unawaited(_invite()),+ enabled: _emails.text.trim().isNotEmpty,+ ),+ note('Invited for $_days days. Copy and send them the link.'),+ SizedBox(height: _line),+ if (_shares.isEmpty) note('No invited people yet.'),+ for (final (index, share) in _shares.indexed) ...[+ note('${share['email']}'),+ note(_recipientStatus(share)),+ choice(+ 'Remove ${share['email']}',+ index + 2,+ () => unawaited(_remove(share['id'] as String)),+ ),+ SizedBox(height: _line),+ ],+ note('Viewers can comment; they cannot control your agent.'),+ ],+ if (_row == _ShareRow.comments) note('Enter to open the discussion.'),+ if (_picking) ..._messageWidgets(foreground),+ ],+ ),+ );}String _recipientStatus(Map<String, dynamic> share) {diff --git a/desktop/lib/shortcuts/app_shortcuts.dart b/desktop/lib/shortcuts/app_shortcuts.dartindex bd98d9b7d..59cc48aea 100644--- a/desktop/lib/shortcuts/app_shortcuts.dart+++ b/desktop/lib/shortcuts/app_shortcuts.dart@@ -71,6 +71,7 @@ enum ShortcutAction {/// conversation where the engine can — the pane, its folder and its settings/// all stay. Asks first, unlike [cloneAgent]: the running process ends.restartAgent,+ shareAgent,routeTask,orchestrate,reload,@@ -423,6 +424,17 @@ AppShortcut _platformShortcut(AppShortcut shortcut) => !kIsWeb/// Swarm bindings replace the old workspace navigation in the retained legacy/// screen. Live Swarm bindings, tooltips, and help all use this same catalog.const kSwarmShortcuts = [+ AppShortcut(+ action: ShortcutAction.shareAgent,+ activator: SingleActivator(+ LogicalKeyboardKey.keyS,+ meta: true,+ shift: true,+ includeRepeats: false,+ ),+ label: 'Share the focused agent',+ group: ShortcutGroup.actions,+ ),AppShortcut(action: ShortcutAction.addAgent,activator: SingleActivator(LogicalKeyboardKey.keyO, meta: true),diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dartindex 5905db34c..56e74b40e 100644--- a/desktop/lib/shortcuts/keymap_commands.dart+++ b/desktop/lib/shortcuts/keymap_commands.dart@@ -359,6 +359,8 @@ final harnessCommands = <HarnessCommand>['agent.share','Share Harness',ShortcutGroup.actions,+ action: ShortcutAction.shareAgent,+ keywords: ['link', 'public', 'private', 'invite', 'collaborate'],nativeAction: 'shareAgent',),const HarnessCommand(diff --git a/desktop/lib/widgets/workspace_share_button.dart b/desktop/lib/widgets/workspace_share_button.dartnew file mode 100644index 000000000..c885e0e3f--- /dev/null+++ b/desktop/lib/widgets/workspace_share_button.dart@@ -0,0 +1,58 @@+import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../shared/theme/workspace_bar_style.dart';+import 'workspace_bar_control.dart';++/// The primary workspace action, also rendered by the native macOS title bar.+class WorkspaceShareButton extends StatelessWidget {+ const WorkspaceShareButton({+ super.key,+ required this.label,+ required this.tooltip,+ this.onPressed,+ });++ final String label;+ final String tooltip;+ final VoidCallback? onPressed;++ static const text = '[ Share ]';++ static double widthOf(BuildContext context) =>+ workspaceBarTextSizeOf(context, text).width ++ workspaceBarCellSizeOf(context).width * 2;++ static Color backgroundFor(bool enabled) =>+ enabled ? grid.AppPalette.accent : grid.AppSurface.recess;++ static Color foregroundFor(bool enabled) =>+ enabled ? Colors.white : grid.AppPalette.textFaint;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final enabled = onPressed != null;+ return WorkspaceBarControl(+ label: label,+ tooltip: tooltip,+ onPressed: onPressed,+ builder: (context, emphasized) => ColoredBox(+ color: backgroundFor(enabled),+ child: SizedBox(+ width: widthOf(context),+ height: workspaceBarControlHeight(context),+ child: Center(+ child: Text(+ text,+ style: workspaceBarTextStyle(+ color: foregroundFor(enabled),+ emphasized: emphasized,+ ),+ ),+ ),+ ),+ ),+ );+ }+}diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swiftindex 2734d4361..56bd8fa74 100644--- a/desktop/macos/Runner/SwarmTitlebar.swift+++ b/desktop/macos/Runner/SwarmTitlebar.swift@@ -285,7 +285,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {add(file, "Clone Harness", "n", "cloneAgent", [.command, .shift])// ⌘⇧E: the pane's harness starts again where it is (Dart: `agent.restart`).add(file, "Restart Harness", "e", "restartAgent", [.command, .shift])- add(file, "Share Harness", "", "shareAgent")+ add(file, "Share Harness", "s", "shareAgent", [.command, .shift])file.addItem(.separator())add(file, "New Tab", "t", "new")add(file, "Rename Tab", "r", "renameActive", [.command, .shift])@@ -923,6 +923,31 @@ private final class SwarmStatusSymbolButton: SwarmIconButton {}}+/// Flat primary action; Dart supplies the same colors and text as Flutter.+private final class SwarmShareButton: SwarmIconButton {+ var background = NSColor.clear { didSet { needsDisplay = true } }+ var foreground = NSColor.white { didSet { needsDisplay = true } }+ var preferredWidth: CGFloat {+ let regularFont = font ?? NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)+ let cell = ("m" as NSString).size(withAttributes: [.font: regularFont]).width+ return ceil(workspaceBarTextWidth(title, font: regularFont) + cell * 2)+ }++ override func draw(_ dirtyRect: NSRect) {+ background.setFill()+ bounds.fill()+ let regularFont = font ?? NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)+ let emphasized = isEnabled && (hovered || hasKeyboardFocus || isHighlighted)+ let line = NSAttributedString(string: title, attributes: [+ .font: emphasized ? workspaceBarEmphasisFont(regularFont) : regularFont,+ .foregroundColor: foreground,+ ])+ let size = line.size()+ line.draw(in: NSRect(x: (bounds.width - size.width) / 2,+ y: (bounds.height - size.height) / 2, width: size.width, height: size.height))+ }+}+private final class SwarmStripScrollView: NSScrollView {override func scrollWheel(with event: NSEvent) {let dx = event.scrollingDeltaX, dy = event.scrollingDeltaY@@ -1227,6 +1252,8 @@ private final class SwarmTabStrip: NSView {fileprivate let focusedModelButton = SwarmContextButton()private var focusedModelTarget: [String: Any]?fileprivate let pullRequestButton = SwarmContextButton()+ fileprivate let shareButton = SwarmShareButton()+ private var shareTarget: [String: Any]?private var barFont = NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)private var terminalForeground = NSColor(white: 0.85, alpha: 1)private var tabs: [SwarmTabButton] = []@@ -1278,7 +1305,15 @@ private final class SwarmTabStrip: NSView {pullRequestButton.setAccessibilityLabel("Open pull request on GitHub")pullRequestButton.isHidden = trueaddSubview(pullRequestButton)- setAccessibilityChildren([scroll, newButton, focusedModelButton, contextButton, pullRequestButton])+ shareButton.isBordered = false+ shareButton.title = "[ Share ]"+ shareButton.target = self+ shareButton.action = #selector(shareFocusedAgent)+ shareButton.isEnabled = false+ shareButton.isHidden = true+ shareButton.setAccessibilityLabel("Share")+ addSubview(shareButton)+ setAccessibilityChildren([scroll, newButton, focusedModelButton, contextButton, pullRequestButton, shareButton])registerForDraggedTypes([swarmPasteboardType])}required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }@@ -1322,6 +1357,16 @@ private final class SwarmTabStrip: NSView {pullRequestButton.foreground = terminalForegroundpullRequestButton.update(state["pullRequest"] as? [String: Any], enabled: actionsEnabled)pullRequestButton.isHidden = state["pullRequest"] == nil+ shareTarget = state["shareAction"] as? [String: Any]+ shareButton.isHidden = shareTarget == nil+ shareButton.font = barFont+ shareButton.title = shareTarget?["text"] as? String ?? "[ Share ]"+ shareButton.isEnabled = actionsEnabled && shareTarget?["enabled"] as? Bool == true+ shareButton.background = statusColor(shareTarget?["background"], fallback: .clear)+ shareButton.foreground = statusColor(shareTarget?["foreground"], fallback: terminalForeground)+ shareButton.toolTip = shareTarget?["tooltip"] as? String+ shareButton.setAccessibilityLabel(shareTarget?["label"] as? String ?? "Share")+ shareButton.setAccessibilityHelp(shareButton.toolTip)let rows = state["tabs"] as? [[String: Any]] ?? []let nextActiveId = state["activeId"] as? String ?? ""revealActiveAfterLayout = revealActiveAfterLayout || nextActiveId != activeId@@ -1380,9 +1425,13 @@ private final class SwarmTabStrip: NSView {let cell = ceil(("m" as NSString).size(withAttributes: [.font: barFont]).width)let trailing = celllet toolHeight = workspaceBarControlHeight(barFont)- let statusRight = bounds.width - trailing+ let shareWidth = shareButton.isHidden ? 0 : shareButton.preferredWidth+ let shareSpace = shareWidth > 0 ? shareWidth + cell : 0+ shareButton.frame = NSRect(x: bounds.width - trailing - shareWidth,+ y: (bounds.height - toolHeight) / 2, width: shareWidth, height: toolHeight)+ let statusRight = bounds.width - trailing - shareSpace// Compact windows keep a scrolling tab list; context never overlaps it.- let available = max(0, bounds.width - cell * 7)+ let available = max(0, bounds.width - cell * 7 - shareSpace)let widths = tabs.map { min($0.preferredWidth, available * 0.45) }let total = widths.reduce(0, +)let occupied = min(total, available * 0.45)@@ -1458,6 +1507,13 @@ private final class SwarmTabStrip: NSView {emit?("focusedPullRequest", ["url": url])}}+ @objc private func shareFocusedAgent() {+ guard actionsEnabled, shareButton.isEnabled,+ let paneId = shareTarget?["paneId"] as? Int,+ let machineId = shareTarget?["machineId"] as? String,+ let agentId = shareTarget?["agentId"] as? String else { return }+ emit?("shareAgent", ["paneId": paneId, "machineId": machineId, "agentId": agentId])+ }@objc private func newSwarm() {if actionsEnabled && newButton.isEnabled { emit?("new", nil) }}diff --git a/desktop/test/share_harness_test.dart b/desktop/test/share_harness_test.dartindex f10fad8e7..482ef47c7 100644--- a/desktop/test/share_harness_test.dart+++ b/desktop/test/share_harness_test.dart@@ -3,6 +3,7 @@ import 'dart:io';import 'dart:ui' as ui;import 'package:flutter/material.dart';+import 'package:flutter/foundation.dart' show kIsWeb;import 'package:flutter/rendering.dart';import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';@@ -12,8 +13,13 @@ import 'package:harness/ws/ws_conn.dart';import 'package:harness/auth/auth_session.dart';import 'package:harness/core/config.dart';import 'package:harness/state/app_state.dart';+import 'package:harness/shortcuts/app_keymap.dart';+import 'package:harness/terminal/terminal_text.dart';+import 'package:harness/terminal/terminal_theme_store.dart';+import 'package:xterm/xterm.dart' show TerminalStyle;import 'support/real_fonts.dart';+import 'keymap_host_test.dart' show MemoryKeymap, key;class SharingApp extends AppNotifier {SharingApp()@@ -37,7 +43,20 @@ class SharingApp extends AppNotifier {void main() {setUpAll(() async {- await loadRealFonts();+ // Native captures use real fonts; Chrome exercises the same cell layout+ // with the test font and does not read the host filesystem.+ if (kIsWeb) return;+ if (Platform.isMacOS &&+ Platform.environment['HARNESS_SHARE_SCREENSHOT'] != null) {+ final mono = ByteData.sublistView(+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),+ );+ await (FontLoader(+ '.AppleSystemUIFontMonospaced',+ )..addFont(Future.value(mono))).load();+ } else {+ await loadRealFonts();+ }await (FontLoader('MaterialIcons',)..addFont(rootBundle.load('fonts/MaterialIcons-Regular.otf'))).load();@@ -46,6 +65,7 @@ void main() {WidgetTester tester,ShareAction manage, {Size size = const Size(900, 800),+ AppKeymap? keymap,}) async {tester.view.physicalSize = size;tester.view.devicePixelRatio = 1;@@ -53,6 +73,9 @@ void main() {await tester.pumpWidget(MaterialApp(theme: grid.buildAppTheme(brightness: Brightness.dark),+ builder: (context, child) => keymap == null+ ? child!+ : KeymapProvider(keymap: keymap, child: child!),home: RepaintBoundary(key: const Key('sharing-preview'),child: Scaffold(@@ -97,23 +120,268 @@ void main() {'expired': expired,'watching': watching,};- final submit = find.widgetWithText(TextButton, '[ Add people ]');+ final submit = find.byKey(const ValueKey('share-choice-1'));++ Future<void> field(WidgetTester tester, String name) async {+ if (find.byKey(ValueKey('share-field-$name')).evaluate().isEmpty) {+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pump();+ }+ await tester.tap(find.byKey(ValueKey('share-field-$name')));+ await tester.pump();+ }++ Future<void> close(WidgetTester tester) async {+ for (+ var i = 0;+ i < 3 && find.byType(ShareHarnessDialog).evaluate().isNotEmpty;+ i+++ ) {+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ }+ }Future<void> capture(WidgetTester tester, String state) async {+ if (kIsWeb) return;final output = Platform.environment['HARNESS_SHARE_SCREENSHOT'];if (output == null) return;await tester.pump(const Duration(milliseconds: 300));- final boundary = tester.renderObject<RenderRepaintBoundary>(- find.byKey(const Key('sharing-dialog-preview')),+ var region = tester.getRect(+ find.byKey(const ValueKey('share-form-surface')),);+ final choices = find.byKey(const ValueKey('share-choices-surface'));+ if (choices.evaluate().isNotEmpty) {+ region = region.expandToInclude(tester.getRect(choices));+ }+ final layer = tester.binding.renderViews.first.debugLayer! as OffsetLayer;await tester.runAsync(() async {- final image = await boundary.toImage();+ final image = await layer.toImage(region.inflate(12), pixelRatio: 2);final png = await image.toByteData(format: ui.ImageByteFormat.png);await File('$output.$state.png').writeAsBytes(png!.buffer.asUint8List());image.dispose();});}+ testWidgets(+ 'compact form uses one-row selection and chooser navigation never changes access',+ (tester) async {+ final changes = <String>[];+ String visibility = 'private';+ await show(tester, (action, payload) async {+ if (action == 'link') {+ visibility = payload['visibility'] as String;+ changes.add(visibility);+ }+ return {+ 'collaboration': true,+ 'shares': [],+ 'link': {'visibility': visibility},+ };+ }, size: const Size(1600, 900));+ final compact = tester.getRect(+ find.byKey(const ValueKey('share-form-surface')),+ );+ expect(find.byType(TextField), findsNothing);+ expect(find.text('Invite for'), findsNothing);+ expect(+ tester+ .widget<Semantics>(find.byKey(const ValueKey('share-field-copy')))+ .properties+ .selected,+ isTrue,+ );+ await capture(tester, 'compact');+ // Copy -> Options -> People -> Access. Moving fields reveals, but never commits, choices.+ for (var i = 0; i < 3; i++) {+ await key(tester, LogicalKeyboardKey.arrowUp);+ }+ expect(+ find.byKey(const ValueKey('share-choices-surface')),+ findsOneWidget,+ );+ expect(+ tester.getRect(find.byKey(const ValueKey('share-form-surface'))),+ compact,+ );+ expect(changes, isEmpty);+ await key(tester, LogicalKeyboardKey.tab);+ await key(tester, LogicalKeyboardKey.arrowDown);+ expect(+ tester+ .widget<Semantics>(find.byKey(const ValueKey('share-choice-1')))+ .properties+ .selected,+ isTrue,+ );+ final cell = terminalCellSizeOf(+ tester.element(find.byType(ShareHarnessDialog)),+ );+ expect(+ tester.getSize(find.byKey(const ValueKey('share-choice-1'))).height,+ closeTo(cell.height, .01),+ );+ await capture(tester, 'public-choice');+ await key(tester, LogicalKeyboardKey.tab, shift: true);+ expect(changes, isEmpty);+ expect(find.text('Private'), findsOneWidget);+ await key(tester, LogicalKeyboardKey.tab);+ await tester.sendKeyDownEvent(LogicalKeyboardKey.enter);+ await tester.pump();+ expect(changes, ['public']);+ expect(find.byKey(const ValueKey('share-choices-surface')), findsNothing);+ expect(+ tester+ .widget<Semantics>(find.byKey(const ValueKey('share-field-copy')))+ .properties+ .selected,+ isTrue,+ );+ await tester.sendKeyRepeatEvent(LogicalKeyboardKey.enter);+ await tester.sendKeyUpEvent(LogicalKeyboardKey.enter);+ await tester.pump();+ expect(changes, [+ 'public',+ ], reason: 'holding Enter cannot also copy or change another value');+ await tester.pumpWidget(const SizedBox());+ },+ );++ testWidgets(+ 'narrow form preserves email drafts across pane navigation, live font/theme changes and remaps',+ (tester) async {+ final map = MemoryKeymap()+ ..apply('''{"bindings":[+ {"keys":"enter","command":null,"when":"picker"},+ {"keys":"alt+enter","command":"picker.accept","when":"picker"}+ ]}''');+ addTearDown(map.dispose);+ final originalFont = terminalFontStore.value;+ final originalTheme = terminalThemeStore.value;+ addTearDown(() {+ terminalFontStore.value = originalFont;+ terminalThemeStore.value = originalTheme;+ });+ var invites = 0;+ await show(+ tester,+ (action, payload) async {+ if (action == 'invite') invites++;+ return {'collaboration': true, 'shares': []};+ },+ size: const Size(440, 760),+ keymap: map,+ );+ await field(tester, 'people');+ await tester.enterText(find.byType(TextField), '[email protected]');+ await tester.pump();+ await key(tester, LogicalKeyboardKey.enter);+ expect(+ invites,+ 0,+ reason: 'unbound Enter stays unbound in an email editor',+ );+ terminalFontStore.value = TerminalStyle(+ fontSize: 22,+ fontFamily: originalFont.fontFamily,+ fontFamilyFallback: originalFont.fontFamilyFallback,+ );+ terminalThemeStore.value = TerminalThemeChoice.tango;+ await tester.pump();+ expect(+ tester.widget<TextField>(find.byType(TextField)).controller!.text,+ '[email protected]',+ );+ expect(tester.takeException(), isNull);+ await capture(tester, 'narrow-tango');+ await tester.tap(find.byKey(const ValueKey('share-back')));+ await tester.pump();+ expect(find.text('Copy link'), findsOneWidget);+ await field(tester, 'people');+ final editor = tester.widget<TextField>(find.byType(TextField));+ expect(editor.controller!.text, '[email protected]');+ editor.controller!.value = editor.controller!.value.copyWith(+ composing: const TextRange(start: 0, end: 3),+ );+ await key(tester, LogicalKeyboardKey.enter, alt: true);+ expect(+ invites,+ 0,+ reason: 'an input-method candidate cannot send an invitation',+ );+ editor.controller!.value = editor.controller!.value.copyWith(+ composing: TextRange.empty,+ );+ await key(tester, LogicalKeyboardKey.enter, alt: true);+ await tester.pump();+ expect(invites, 1);+ await tester.pumpWidget(const SizedBox());+ },+ );++ testWidgets(+ 'live people updates preserve the selected recipient and email draft',+ (tester) async {+ var recipients = [person('[email protected]'), person('[email protected]')];+ final removed = <String>[];+ await show(tester, (action, payload) async {+ if (action == 'remove') {+ removed.add(payload['id'] as String);+ recipients.removeWhere((person) => person['id'] == payload['id']);+ }+ return {'collaboration': true, 'shares': recipients};+ }, size: const Size(1600, 900));+ await field(tester, 'people');+ await tester.enterText(find.byType(TextField), '[email protected]');+ await key(tester, LogicalKeyboardKey.arrowDown);+ await key(tester, LogicalKeyboardKey.arrowDown);+ recipients = recipients.reversed.toList();+ await tester.pump(const Duration(seconds: 5));+ await key(tester, LogicalKeyboardKey.enter);+ expect(removed, ['[email protected]']);+ final editor = tester.widget<TextField>(find.byType(TextField));+ expect(editor.controller!.text, '[email protected]');+ expect(editor.focusNode!.hasFocus, isTrue);+ expect(find.text('[email protected]'), findsOneWidget);+ await tester.pumpWidget(const SizedBox());+ },+ );++ testWidgets('Options opens comments and returns to the same form', (+ tester,+ ) async {+ final calls = <String>[];+ await show(tester, (action, payload) async {+ calls.add(action);+ return {+ 'collaboration': true,+ 'shares': [],+ 'comments': [],+ 'canComment': true,+ };+ }, size: const Size(1600, 900));+ await field(tester, 'options');+ await field(tester, 'comments');+ await tester.pumpAndSettle();+ expect(find.text('Start the conversation.'), findsOneWidget);+ expect(calls, ['list', 'comments']);+ await tester.enterText(find.byType(TextField), 'Please review this step.');+ tester.view.physicalSize = const Size(900, 800);+ await tester.pump();+ expect(+ tester.widget<TextField>(find.byType(TextField)).controller!.text,+ 'Please review this step.',+ reason: 'moving the discussion into the narrow pane keeps its draft',+ );+ expect(calls, ['list', 'comments']);+ await key(tester, LogicalKeyboardKey.escape);+ expect(find.text('Copy link'), findsOneWidget);+ expect(find.text('[-]'), findsOneWidget);+ expect(find.text('Private'), findsOneWidget);+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox());+ });+testWidgets('one stable browser link can be copied, made public/private and stopped',(tester) async {@@ -147,31 +415,33 @@ void main() {}return {'collaboration': true, 'link': link, 'shares': []};});- expect(- find.text('Only the emails you add can view and comment.'),- findsOneWidget,- );- await tester.tap(find.text('[ Copy link ]'));+ expect(find.text('Private'), findsOneWidget);+ expect(find.text('Only you'), findsOneWidget);+ await tester.tap(find.text('Copy link'));await tester.pump();expect(changes, ['private']);expect(clipboard, 'https://harness.example/s/fixture#key=pinned');expect(find.text('Link copied.'), findsOneWidget);await capture(tester, 'private');- await tester.tap(find.textContaining('Public').first);+ await field(tester, 'access');+ await capture(tester, 'access-choices');+ await tester.tap(find.byKey(const ValueKey('share-choice-1')));await tester.pump();expect(changes.last, 'public');- expect(find.textContaining('Anyone with the link'), findsOneWidget);+ expect(find.text('Public'), findsOneWidget);await capture(tester, 'public');- await tester.tap(find.text('[ Copy link ]'));+ await tester.tap(find.text('Copy link'));await tester.pump();expect(changes, ['private','public',], reason: 'copying never silently changes visibility');- await tester.tap(find.textContaining('Private').first);+ await field(tester, 'access');+ await tester.tap(find.byKey(const ValueKey('share-choice-0')));await tester.pump();expect(changes.last, 'private');- await tester.tap(find.text('[ Stop sharing ]'));+ await field(tester, 'options');+ await tester.tap(find.text('Stop sharing'));await tester.pump();expect(changes.last, 'off');expect(find.text('Sharing stopped.'), findsOneWidget);@@ -198,7 +468,7 @@ void main() {},},);- await tester.tap(find.text('[ Copy link ]'));+ await tester.tap(find.text('Copy link'));await tester.pump();expect(find.textContaining('Waiting for the connection'), findsOneWidget);expect(find.text('Link copied.'), findsNothing);@@ -233,7 +503,7 @@ void main() {await tester.pumpAndSettle();expect(app.calls, [('machine', 'agent', 'list')]);expect(find.text('Share Climate dashboard'), findsOneWidget);- await tester.tap(find.text('[ Done ]'));+ await close(tester);await tester.pumpAndSettle();app.dispose();});@@ -260,8 +530,11 @@ void main() {'shares': [person('[email protected]')],};});- await tester.tap(find.text('[ 7 days ]'));+ await field(tester, 'options');+ await field(tester, 'expiry');+ await tester.tap(find.text('7 days'));await tester.pumpAndSettle();+ await field(tester, 'people');await tester.enterText(find.byType(TextField), '[email protected]');tester.widget<TextField>(find.byType(TextField))@@ -270,7 +543,7 @@ void main() {await tester.pump();expect(invites.single['days'], 7);expect(find.text('This harness cannot be shared yet.'), findsOneWidget);- await tester.tap(find.widgetWithText(TextButton, '[ Remove ]'));+ await tester.tap(find.text('Remove [email protected]'));await tester.pump();expect(removing, isTrue);expect(find.textContaining('Check the connection'), findsOneWidget);@@ -297,6 +570,7 @@ void main() {}return {'shares': shares};});+ await field(tester, 'people');expect(find.text('No invited people yet.'), findsOneWidget);expect(find.textContaining('cannot control your agent'), findsOneWidget);await tester.enterText(@@ -313,10 +587,12 @@ void main() {});expect(find.text('2 people now have view-only access.'), findsOneWidget);expect(find.text('Watching now · Can view'), findsOneWidget);- expect(find.textContaining('Keep your machine online'), findsOneWidget);+ // The People pane owns focus while the invitation is edited.expect(tester.takeException(), isNull);// Optional artifact for visual review; no golden files or production filesystem writes.- final output = Platform.environment['HARNESS_SHARE_SCREENSHOT'];+ final output = kIsWeb+ ? null+ : Platform.environment['HARNESS_SHARE_SCREENSHOT'];if (output != null) {final boundary = tester.renderObject<RenderRepaintBoundary>(find.byKey(const Key('sharing-dialog-preview')),@@ -329,7 +605,7 @@ void main() {image.dispose();});}- await tester.tap(find.widgetWithText(TextButton, '[ Remove ]').first);+ await tester.tap(find.text('Remove [email protected]'));await tester.pump();expect(calls.last.$1, 'remove');expect(calls.last.$2, {'id': '[email protected]'});@@ -337,7 +613,7 @@ void main() {expect(find.text('Access removed.'), findsOneWidget);await tester.pump(const Duration(seconds: 5));expect(calls.last.$1, 'list');- await tester.tap(find.text('[ Done ]'));+ await close(tester);await tester.pumpAndSettle();expect(find.text('Share harness'), findsNothing);},@@ -355,7 +631,8 @@ void main() {}return {'shares': []};});- expect(tester.widget<TextButton>(submit).onPressed, isNull);+ await field(tester, 'people');+ expect(tester.widget<Semantics>(submit).properties.enabled, isFalse);for (final invalid in ['bad',List.generate(21, (i) => '[email protected]').join(','),@@ -372,7 +649,7 @@ void main() {await tester.tap(submit);await tester.pump();expect(tester.widget<TextField>(find.byType(TextField)).enabled, isFalse);- expect(tester.widget<TextButton>(submit).onPressed, isNull);+ expect(tester.widget<Semantics>(submit).properties.enabled, isFalse);await tester.pump(const Duration(seconds: 5));expect(invites, 1);pending.complete({@@ -400,6 +677,7 @@ void main() {},size: const Size(440, 680),);+ await field(tester, 'people');expect(find.text('Waiting for connection'), findsOneWidget);expect(find.text('Expired · add again to renew'), findsOneWidget);expect(find.text('You already own this harness.'), findsOneWidget);@@ -426,14 +704,14 @@ void main() {findsOneWidget,);fails = false;- await tester.tap(find.text('[ Retry ]'));+ await tester.tap(find.text('Retry'));await tester.pump();- expect(find.text('No invited people yet.'), findsOneWidget);- expect(find.text('[ Retry ]'), findsNothing);+ expect(find.text('Only you'), findsOneWidget);+ expect(find.text('Retry'), findsNothing);await tester.pumpWidget(const SizedBox());final pending = Completer<Map<String, dynamic>>();await show(tester, (_, _) => pending.future);- await tester.tap(find.text('[ Done ]'));+ await close(tester);await tester.pumpAndSettle();pending.complete({'shares': []});await tester.pump();@@ -453,6 +731,7 @@ void main() {};});await tester.pump(const Duration(seconds: 5));+ await field(tester, 'people');await tester.enterText(find.byType(TextField), '[email protected]');await tester.pump();await tester.tap(submit);diff --git a/desktop/test/share_toolbar_test.dart b/desktop/test/share_toolbar_test.dartnew file mode 100644index 000000000..c6c341a51--- /dev/null+++ b/desktop/test/share_toolbar_test.dart@@ -0,0 +1,303 @@+import 'dart:async';++import 'package:flutter/foundation.dart';+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';+import 'package:harness/core/models.dart';+import 'package:harness/screens/swarm_screen.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/sharing/share_harness_dialog.dart';+import 'package:harness/shortcuts/app_keymap.dart';+import 'package:harness/shortcuts/app_shortcuts.dart';+import 'package:harness/shortcuts/keymap.dart';+import 'package:harness/shortcuts/keymap_commands.dart';+import 'package:harness/shortcuts/keymap_native.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/state/terminal_pane.dart';+import 'package:harness/terminal/terminal_binary.dart';+import 'package:harness/widgets/workspace_share_button.dart';+import 'package:harness/ws/ws_conn.dart';++import 'keymap_host_test.dart' show MemoryKeymap, key;+import 'swarm_screen_test.dart' show terminal;+import 'swarm_state_test.dart' show createApp;++class _SharingConnection extends WsConn {+ _SharingConnection()+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: 'm',+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );+ final shares = <(String, String)>[];+ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async {+ if (!type.startsWith('harness_share_')) return {};+ shares.add((type, payload['agentId'] as String));+ return {'collaboration': true, 'shares': []};+ }+}++void main() {+ final button = find.byKey(const ValueKey('workspace-share-button'));+ late AppNotifier app;+ late MemoryKeymap keymap;+ late _SharingConnection connection;+ final input = <TerminalBinaryFrame>[];++ // Initialize the icon library before the deep viewer build stack in Chrome.+ setUpAll(() => expect(LucideIcons.refreshCw.codePoint, greaterThan(0)));++ setUp(() {+ connection = _SharingConnection();+ app = createApp(connectionForTest: (_) => connection);+ app.stateOf('m')!.nodeOnline = true;+ keymap = MemoryKeymap();+ input.clear();+ });+ tearDown(() {+ app.dispose();+ keymap.dispose();+ });++ Future<void> mount(+ WidgetTester tester, {+ bool native = false,+ Size size = const Size(1280, 800),+ }) async {+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = size;+ addTearDown(tester.view.reset);+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: KeymapProvider(+ keymap: keymap,+ child: SwarmScreen(notifier: app, nativeTabs: native),+ ),+ ),+ );+ await tester.pumpAndSettle();+ }++ Future<void> shareKey(WidgetTester tester) => key(+ tester,+ LogicalKeyboardKey.keyS,+ cmd: !kIsWeb,+ alt: kIsWeb,+ shift: true,+ );++ testWidgets(+ 'button and shortcut share only the focused agent and return terminal focus',+ (tester) async {+ final firstSession = terminal('a0', input);+ final first = app.adoptSessionForTest(firstSession);+ final second = app.adoptSessionForTest(terminal('a1', input));+ await mount(tester);+ app.focusPane(first.id);+ await tester.pump();+ expect(+ tester.widget<WorkspaceShareButton>(button).tooltip,+ 'Share Agent 0 · ${keymap.hint('agent.share')}',+ );+ await tester.tap(button);+ await tester.pumpAndSettle();+ expect(find.text('Share Agent 0'), findsOneWidget);+ expect(connection.shares, [('harness_share_list', 'a0')]);+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ expect(first.session, same(firstSession));+ app.focusPane(second.id);+ await tester.pump();+ await shareKey(tester);+ await tester.pumpAndSettle();+ expect(find.text('Share Agent 1'), findsOneWidget);+ await shareKey(tester);+ await tester.pump();+ expect(find.byType(ShareHarnessDialog), findsOneWidget);+ expect(connection.shares, [+ ('harness_share_list', 'a0'),+ ('harness_share_list', 'a1'),+ ]);+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ expect(+ input,+ isEmpty,+ reason: 'opening and dismissing Share never types into an agent',+ );+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);+ await tester.pump(const Duration(milliseconds: 100));+ expect(+ input,+ isNotEmpty,+ reason: 'normal typing returns to the terminal',+ );+ await tester.pumpWidget(const SizedBox());+ },+ );++ testWidgets('empty and view-only panes keep an inactive Share button', (+ tester,+ ) async {+ await mount(tester);+ expect(tester.widget<WorkspaceShareButton>(button).onPressed, isNull);+ await shareKey(tester);+ expect(connection.shares, isEmpty);+ const shared = Machine(+ machineId: 'm',+ authMode: MachineAuthMode.remote,+ isShared: true,+ );+ app.machineStates['m'] = MachineState(shared)+ ..agents = const [Agent(id: 'a0', name: 'Shared agent')];+ app.adoptSessionForTest(terminal('a0', input));+ await tester.pump();+ expect(tester.widget<WorkspaceShareButton>(button).onPressed, isNull);+ await tester.tap(button);+ await shareKey(tester);+ await tester.pump();+ expect(connection.shares, isEmpty);+ expect(find.byType(ShareHarnessDialog), findsNothing);+ await tester.pumpWidget(const SizedBox());+ });++ testWidgets('a dependent viewer shares its owning agent', (tester) async {+ app.adoptSessionForTest(terminal('a0', input));+ final viewer = TerminalPane(+ id: 99,+ machineId: 'm',+ kind: PaneKind.web,+ ownerAgentId: 'a0',+ );+ app.panes.add(viewer);+ app.focusedPaneId = viewer.id;+ await mount(tester);+ await tester.tap(button);+ await tester.pumpAndSettle();+ expect(connection.shares.single, ('harness_share_list', 'a0'));+ expect(find.text('Share Agent 0'), findsOneWidget);+ await tester.pumpWidget(const SizedBox());+ });++ testWidgets(+ 'Share keeps its corner at narrow widths and follows custom shortcuts',+ (tester) async {+ app.adoptSessionForTest(terminal('a0', input));+ await mount(tester, size: const Size(520, 800));+ final bar = tester.getRect(+ find.byKey(const ValueKey('workspace-status-bar')),+ );+ expect(tester.getRect(button).right, lessThanOrEqualTo(bar.right));+ expect(+ tester.getRect(button).left,+ greaterThan(+ tester+ .getRect(find.byKey(const ValueKey('swarm-new-tab-button')))+ .right,+ ),+ );+ expect(tester.takeException(), isNull);+ keymap.apply(+ '{"bindings":[{"keys":"${platformWorkspaceBinding("cmd+shift+s")}","command":null},{"keys":"f8","command":"agent.share"}]}',+ );+ await tester.pump();+ expect(+ tester.widget<WorkspaceShareButton>(button).tooltip,+ 'Share Agent 0 · F8',+ );+ await shareKey(tester);+ expect(connection.shares, isEmpty);+ await key(tester, LogicalKeyboardKey.f8);+ await tester.pumpAndSettle();+ expect(find.text('Share Agent 0'), findsOneWidget);+ await tester.pumpWidget(const SizedBox());+ },+ );++ testWidgets(+ 'native titlebar receives current target, colors and remapped hint and rejects stale clicks',+ (tester) async {+ const channel = MethodChannel('harness/swarm_tabs');+ const codec = StandardMethodCodec();+ final updates = <Map>[];+ final messenger = tester.binding.defaultBinaryMessenger;+ messenger.setMockMethodCallHandler(channel, (call) async {+ if (call.method == 'update') updates.add(call.arguments as Map);+ return true;+ });+ addTearDown(() => messenger.setMockMethodCallHandler(channel, null));+ final first = app.adoptSessionForTest(terminal('a0', input));+ final second = app.adoptSessionForTest(terminal('a1', input));+ app.focusPane(first.id);+ await mount(tester, native: true);+ final old = updates.last['shareAction'] as Map;+ expect(old['label'], 'Share Agent 0');+ expect(old['enabled'], true);+ expect(+ old['background'],+ WorkspaceShareButton.backgroundFor(true).toARGB32(),+ );+ keymap.apply(+ '{"bindings":[{"keys":"${platformWorkspaceBinding("cmd+shift+s")}","command":null},{"keys":"f8","command":"agent.share"}]}',+ );+ await tester.pump();+ expect(+ (updates.last['shareAction'] as Map)['tooltip'],+ 'Share Agent 0 · F8',+ );+ app.focusPane(second.id);+ await tester.pump();+ Future<void> click(Map target) async {+ final done = Completer<void>();+ messenger.handlePlatformMessage(+ channel.name,+ codec.encodeMethodCall(MethodCall('shareAgent', target)),+ (_) => done.complete(),+ );+ for (var i = 0; i < 8 && !done.isCompleted; i++) {+ await tester.pump();+ }+ expect(done.isCompleted, isTrue);+ await done.future;+ await tester.pumpAndSettle();+ }++ await click(old);+ expect(connection.shares, isEmpty);+ await click(updates.last['shareAction'] as Map);+ expect(connection.shares.single, ('harness_share_list', 'a1'));+ expect((updates.last['shareAction'] as Map)['enabled'], false);+ await tester.pumpWidget(const SizedBox());+ },+ );++ test(+ 'Share has one documented platform binding and a remappable native command',+ () {+ final binding = platformWorkspaceBinding('cmd+shift+s');+ expect(+ harnessDefaultKeymap.match(KeymapContext.terminal, [+ KeyStroke.parse(binding),+ ]).command,+ 'agent.share',+ );+ expect(+ shortcutRows().where((row) => row.label == 'Share the focused agent'),+ hasLength(1),+ );+ expect(nativeKeymapSnapshot(keymap).toString(), contains('shareAgent'));+ },+ );+}diff --git a/desktop/tool/check_swarm_titlebar.sh b/desktop/tool/check_swarm_titlebar.shindex 32fe6c861..ac83022b1 100644--- a/desktop/tool/check_swarm_titlebar.sh+++ b/desktop/tool/check_swarm_titlebar.sh@@ -30,9 +30,11 @@ fiif [[ "${2:-}" == "--status-preview" ]]; thencheck_source="$desktop_dir/tool/status_theme_preview.swift"fi-cat "$desktop_dir/macos/Runner/HarnessKeymap.swift" \- "$desktop_dir/macos/Runner/SwarmTitlebar.swift" \- "$check_source" > "$check_dir/main.swift"+cat "$desktop_dir/macos/Runner/HarnessKeymap.swift" > "$check_dir/main.swift"+# The title bar shares menu ordering with the window. Include that production+# helper without booting the Flutter window or its account/runtime services.+sed -n '/^enum HarnessAppMenu {/,$p' "$desktop_dir/macos/Runner/MainFlutterWindow.swift" >> "$check_dir/main.swift"+cat "$desktop_dir/macos/Runner/SwarmTitlebar.swift" "$check_source" >> "$check_dir/main.swift"xcrun swiftc -swift-version 5 "${optimization[@]}" -module-cache-path "$check_dir/module-cache" \-F "$framework_dir" -framework FlutterMacOS \-Xlinker -rpath -Xlinker "$framework_dir" \diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swiftindex acf84d370..e2c8d7db3 100644--- a/desktop/tool/swarm_titlebar_checks.swift+++ b/desktop/tool/swarm_titlebar_checks.swift@@ -218,6 +218,54 @@ private extension SwarmTabButton {}private extension SwarmTabStrip {+ func checkShareAction() throws {+ let target: [String: Any] = ["text": "[ Share ]", "label": "Share Website launch",+ "tooltip": "Share Website launch · ⇧⌘S", "enabled": true,+ "paneId": 7, "machineId": "office", "agentId": "website",+ "foreground": Int64(0xffffffff), "background": Int64(0xff2f5bea)]+ var state: [String: Any] = ["enabled": true, "shareAction": target,+ "tabs": [["id": "work", "name": "Work"]], "activeId": "work",+ "focusedContext": ["text": "Office project", "segments": [["text": "Office project"]]]]+ var calls: [(String, [String: Any])] = []+ emit = { method, args in calls.append((method, args as? [String: Any] ?? [:])) }+ for width in [CGFloat(360), CGFloat(520), CGFloat(1280)] {+ setFrameSize(NSSize(width: width, height: 40))+ update(state)+ try checkTitlebar(!shareButton.isHidden && shareButton.isEnabled &&+ shareButton.frame.width == shareButton.preferredWidth &&+ shareButton.frame.maxX <= bounds.width &&+ contextButton.frame.maxX < shareButton.frame.minX &&+ newButton.frame.maxX < shareButton.frame.minX,+ "Share stays prominent at the right edge without overlapping tabs or context at width \(width)")+ }+ try checkTitlebar(shareButton.accessibilityLabel() == "Share Website launch" &&+ shareButton.toolTip == "Share Website launch · ⇧⌘S",+ "Share identifies the selected agent and its live shortcut")+ let pixel = shareButton.renderedBitmap().colorAt(x: 1, y: 1)!.usingColorSpace(.sRGB)!+ try checkTitlebar(abs(pixel.blueComponent - 234.0 / 255.0) < 0.02,+ "The primary Share action paints the color supplied by Flutter")+ shareButton.performClick(nil)+ try checkTitlebar(calls.last?.0 == "shareAgent" && calls.last?.1["paneId"] as? Int == 7 &&+ calls.last?.1["machineId"] as? String == "office" && calls.last?.1["agentId"] as? String == "website",+ "The native Share button sends the exact displayed agent identity")+ let count = calls.count+ state["enabled"] = false+ update(state)+ shareButton.performClick(nil)+ try checkTitlebar(!shareButton.isEnabled && calls.count == count,+ "Share is disabled behind a modal and cannot dispatch")+ state["enabled"] = true+ var disabled = target+ disabled["enabled"] = false+ state["shareAction"] = disabled+ update(state)+ shareButton.performClick(nil)+ try checkTitlebar(!shareButton.isHidden && !shareButton.isEnabled && calls.count == count,+ "An empty or view-only pane keeps Share visible and inactive")+ update([:])+ try checkTitlebar(shareButton.isHidden, "Workspace teardown clears the Share control")+ }+func checkAgentIdentity() throws {func show(_ count: Int, engine: String? = nil) {var row: [String: Any] = ["id": "agent-tab", "name": "Login flow", "agentCount": count]@@ -444,8 +492,8 @@ private extension SwarmTabStrip {newButton.frame.maxX < contextButton.frame.minX, "Tabs are left of the right-aligned focused context")try checkTitlebar(tabs[0].frame.width < 120 && tabs[0].displayLabel == "1:code","Short numbered labels use text-sized widths")- try checkTitlebar(subviews.count == 5 && pullRequestButton.isHidden && focusedModelButton.isHidden,- "Context links fill the bar; standalone search and management controls are absent")+ try checkTitlebar(subviews.count == 6 && pullRequestButton.isHidden && focusedModelButton.isHidden && shareButton.isHidden,+ "Context links fill the bar; absent context and Share state clear their controls")let controls = [newButton]for (control, symbol) in zip(controls, ["+"]) {try checkTitlebar(control.image == nil && control.title == symbol && !control.isBordered,@@ -1293,6 +1341,7 @@ do {try strip.runChecks()try strip.checkAgentIdentity()try strip.checkSharedTypography()+ try strip.checkShareAction()try SwarmTabButton(id: "hover-fixture").checkHoverStyleAndTooltips()try checkTitlebar(titlebarCheckApp.windows.isEmpty, "Checks never open an application window")if CommandLine.arguments.contains("--window-layout") {diff --git a/docs/plans/2026-09-28-011-share-button-and-form.md b/docs/plans/2026-09-28-011-share-button-and-form.mdnew file mode 100644index 000000000..d7e0a86be--- /dev/null+++ b/docs/plans/2026-09-28-011-share-button-and-form.md@@ -0,0 +1,50 @@+# Share button and Cmd-N form++Branch: `harness-share-toolbar`. Implementation and local review builds are+complete. This receipt records validation before merge; deployment is separate.++Sharing was hidden behind menus, and its dialog presented access modes,+invitations, expiry, comments, and link controls at once. Desktop and web now+have a persistent Share action at the top-right and a compact form based on+Cmd-N.++## Interaction++- Share opens for the focused agent. A dependent viewer uses its owning agent.+ Empty tabs and agents shared with the user keep the button disabled.+- Cmd-Shift-S on desktop and Alt-Shift-S on web open the same form. Menu entries,+ help, tooltips, and custom keymaps use the existing `agent.share` command.+- Access and People are aligned fields. Private/Public and email management+ open beside the form. Options reveals invitation expiry, Comments, and Stop+ sharing. Copy link is the selected primary row.+- Up/Down navigate, Tab switches panes, Enter accepts, and Escape goes back.+ Browsing access choices does not change permissions. Narrow windows replace+ the form with the selected pane and provide a Back action.+- Email drafts survive navigation, font changes, and theme changes. Comment+ drafts survive responsive pane changes. Recipient refreshes preserve the+ selected person's identity; stale native button clicks cannot target a new+ focused agent.++The shared Flutter form reuses the existing share and comment operations.+The macOS title bar receives the same button labels, colors, target identity,+and availability as the Flutter toolbar. Backend access enforcement and URL+formats are unchanged.++## Verification++- Focused native widget/shortcut/workspace regression suite: 77 tests passed+ after rebasing on current main. Final form suite: 13 tests, including SF Mono+ captures and enlarged text in Tango.+- Chrome: 19 form and toolbar tests passed with `HARNESS_TEST=true`; the final+ responsive comment-draft check also passed in the 13-test browser form suite.+- AppKit title-bar checks: 271 passed, without opening a window.+- Flutter analysis: no errors, warnings, or new diagnostics; 12 existing info+ diagnostics in vendored xterm remain.+- Production web build and macOS debug app build succeeded.+- No live accounts, agents, invitations, or comments were changed by the tests.++Review images are generated from production widgets with fixture data:+[compact form](../../desktop/design/images/share-form-compact.png),+[access choices](../../desktop/design/images/share-form-access.png),+[narrow form](../../desktop/design/images/share-form-narrow.png), and+[toolbar](../../desktop/design/images/workspace-share-button.png).