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
Show animated activity beside desktop tab and pane names (#436)
Dee54666ae20871
diff --git a/desktop/design/images/workspace-activity.png b/desktop/design/images/workspace-activity.pngnew file mode 100644index 000000000..b42e9eb29Binary files /dev/null and b/desktop/design/images/workspace-activity.png differdiff --git a/desktop/design/workspace-status-bar.md b/desktop/design/workspace-status-bar.mdindex 1a01e31bd..17e479059 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) [ Share ]+1:api ? 2:web ⠹ 3:blender ✓ + M2 autonomous-harness (main) [ Share ]```## Tabs on the left@@ -54,6 +54,60 @@ The new-tab `+` uses a plain-text control: no restingbox, with bold text on hover or keyboardfocus. Keep its New Tab tooltip and shortcut hint.+### Harness activity++Use hn's activity states in two existing places: after the tab name+(`2:web ⠹`), and after the title in a pane header (`[engine] Session name ⠹`).+Idle has no visible mark. Viewer headers show their owner's state. Shells, unknown agents, and+utility tabs have no harness activity mark. Keep the existing engine icon.+The mark replaces the native tab's old orange attention indicator; it adds no+new bar, counter, badge, or permanent legend. Hover and accessibility descriptions+explain each symbol.++++| Mark | Meaning | Terminal color |+| --- | --- | --- |+| `?` | Needs your input | Yellow |+| `✗` | Last turn or launch failed | Red |+| `✓` | Finished and unread | Green |+| `⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏` | Working, one frame per 100 ms | Cyan |+| `◌` | Starting | Yellow |+| None | Idle | — |+| `\|\|` | Paused | Muted foreground |+| `⊘` | Offline | Muted foreground |++A tab shows its most urgent member in the order above, counting a harness and+its viewers once. For an individual harness, offline/paused/launch state takes+precedence; a current question takes precedence over working. A new turn masks+old results. Seeing a completion clears its unread check, but viewing a failed+turn does not clear the failure. A pane hidden by zoom or an inactive/utility+tab is not seen. Existing unread storage remains an in-memory, bounded list;+these marks are not a durable event history.++Reserve one measured cell for the mark and one for the gap, including when idle+is blank, so state changes never move the names or adjacent tabs. Paused uses+two ASCII pipes at 65% font size with quarter-cell negative letter spacing:+short, thin strokes centered in the same cell. Keep native and Flutter metrics+in sync. The question mark stays plain yellow. Animate only the+mark, never the label, width, terminal, or method-channel payload. Long tabs+shorten their names and scroll; preserve room for the number and mark. SF Mono+does not contain Braille, so Flutter explicitly falls back to the platform's+symbol font inside that fixed cell. Native text uses CoreText fallback.++Flutter shares one clock; AppKit has one local clock. Both derive the same frame+from Unix time. No visible working mark means no timer. Hidden panes and+offscreen tabs do not animate; background/inactive apps and Reduce Motion stop+the clock. Reduce Motion keeps the first Braille frame with its Working label.+Colors follow the terminal palette and the Color preference.++State rules live in `lib/state/harness_activity.dart`, with the Flutter mark in+`lib/widgets/harness_activity_mark.dart`. `harness_activity_test.dart`,+`workspace_activity_test.dart`, and the native titlebar checks cover state,+acknowledgement, fixed geometry, visibility, and animation. Set+`HARNESS_ACTIVITY_CAPTURE_DIR` when running the workspace activity test to+capture synthetic Flutter screenshots and the native tab payload.+Tab labels, status text, pane titles, and model selectors use **13 pt SF Mono,regular weight at rest** on macOS. Linux uses its platform monospace stack at the samesize. Use `workspaceBarTextStyle()` and `workspaceBarCellSizeOf(context)` fromdiff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 7e584bece..0e084d6f9 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -39,6 +39,7 @@ import '../shortcuts/keymap_native.dart';import '../shortcuts/keymap_settings.dart';import '../state/app_state.dart';import '../state/harness_sessions.dart';+import '../state/harness_activity.dart';import '../state/harness_placement.dart';import '../state/new_harness.dart';import '../state/device_form.dart';@@ -61,6 +62,7 @@ import '../widgets/add_phone_dialog.dart';import '../widgets/layout_palette.dart';import '../widgets/move_pane_palette.dart';import '../widgets/engine_identity.dart';+import '../widgets/harness_activity_mark.dart';import '../widgets/status_line.dart';import '../widgets/workspace_status_line.dart';import '../widgets/workspace_bar_control.dart';@@ -564,7 +566,9 @@ class _SwarmScreenState extends State<SwarmScreen> {super.didChangeDependencies();// Only the one flag: depending on all of MediaQuery rebuilt the workspace// on every resize.- _reduceMotion = MediaQuery.maybeDisableAnimationsOf(context) ?? false;+ final reduceMotion = MediaQuery.maybeDisableAnimationsOf(context) ?? false;+ final motionChanged = reduceMotion != _reduceMotion;+ _reduceMotion = reduceMotion;_daemonEnvironmentChanged();final keymap = KeymapTheme.of(context);if (keymap != _providedKeymap) {@@ -574,7 +578,10 @@ class _SwarmScreenState extends State<SwarmScreen> {}_syncKeymap();final current = ModalRoute.isCurrentOf(context) ?? true;- if (_routeIsCurrent == current) return;+ if (_routeIsCurrent == current) {+ if (motionChanged && _native) _syncNative();+ return;+ }_routeIsCurrent = current;if (!current &&(_search != null ||@@ -1539,6 +1546,7 @@ class _SwarmScreenState extends State<SwarmScreen> {final barStyle = workspaceBarTextStyle();final payload = {'enabled': _routeIsCurrent && !_dialogOpen && !_spokenPaletteOpen,+ 'reduceMotion': _reduceMotion,'activeId': app.activeSwarmId,// The selected tab is drawn with keyboard focus: ⏎ goes into it.'tabsFocused': app.tabStripFocused && _tabStripFocus.hasPrimaryFocus,@@ -1712,6 +1720,17 @@ class _SwarmScreenState extends State<SwarmScreen> {app.questionFor(p.machineId, p.agentId!) != null,).length,+ if (tabActivity(app, swarm) case final activity?)+ 'activity': {+ 'mark': activity.mark,+ 'label': activity.label,+ 'working': activity == HarnessActivity.working,+ 'color': activityColor(+ activity,+ terminalTheme,+ color: prefs.color,+ ).toARGB32(),+ },},],};@@ -6238,6 +6257,7 @@ class _SwarmScreenState extends State<SwarmScreen> {terminalThemeStore.value,);final names = workspaceTabNames(app);+ final activities = [for (final tab in app.swarms) tabActivity(app, tab)];final labels = [for (var index = 0; index < app.swarms.length; index++)'${index + 1}:${names[app.swarms[index].id]}',@@ -6265,10 +6285,19 @@ class _SwarmScreenState extends State<SwarmScreen> {);final tabBudget = contentWidth * .45;_tabWidths = [- for (final label in labels)- math.min(- math.min(label.characters.length + 2, 24) * cell.width,- tabBudget,+ for (var i = 0; i < labels.length; i++)+ math.max(+ activities[i] == null ? 0 : ('${i + 1}:'.length + 4) * cell.width,+ math.min(+ math.min(+ labels[i].characters.length ++ 2 ++ (activities[i] == null ? 0 : 2),+ 24,+ ) *+ cell.width,+ tabBudget,+ ),),];final total = _tabWidths.fold(0.0, (sum, width) => sum + width);@@ -6387,6 +6416,19 @@ class _SwarmScreenState extends State<SwarmScreen> {itemBuilder: (context, index) {final swarm = app.swarms[index];final selected = app.activeSwarmId == swarm.id;+ final activity = activities[index];+ final nameHint = workspaceTabTooltip(+ labels[index],+ swarm.name,+ clipped:+ workspaceBarTextSizeOf(context, labels[index]).width ++ (activity == null ? 0 : cell.width * 2) >+ _tabWidths[index] - cell.width * 2,+ );+ final tabHint = [+ ?nameHint,+ if (activity != null) activity.label,+ ].join('\n');return ReorderableDragStartListener(key: ValueKey(swarm.id),index: index,@@ -6407,17 +6449,9 @@ class _SwarmScreenState extends State<SwarmScreen> {onDoubleTap: () => _rename(swarm.id),child: Center(child: WorkspaceBarControl(- label: '${labels[index]}: ${swarm.name}',- tooltip: workspaceTabTooltip(- labels[index],- swarm.name,- clipped:- workspaceBarTextSizeOf(- context,- labels[index],- ).width >- _tabWidths[index] - cell.width * 2,- ),+ label:+ '${labels[index]}: ${swarm.name}${activity == null ? '' : ', ${activity.label}'}',+ tooltip: tabHint.isEmpty ? null : tabHint,selectedBackground: grid.AppPalette.swarmWelcome,selected: selected,highlighted:@@ -6434,16 +6468,76 @@ class _SwarmScreenState extends State<SwarmScreen> {horizontal: cell.width,),child: Center(- child: Text(- labels[index],- maxLines: 1,- overflow: TextOverflow.ellipsis,- textAlign: TextAlign.center,- style: workspaceBarTextStyle(- color: theme.foreground,- emphasized: emphasized,- ),- ),+ child: activity == null+ ? Text(+ labels[index],+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ textAlign: TextAlign.center,+ style: workspaceBarTextStyle(+ color: theme.foreground,+ emphasized: emphasized,+ ),+ )+ : Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(+ '${index + 1}:',+ style: workspaceBarTextStyle(+ color: theme.foreground,+ emphasized: emphasized,+ ),+ ),+ Flexible(+ child: Text(+ names[swarm.id]!,+ maxLines: 1,+ overflow:+ TextOverflow.ellipsis,+ style: workspaceBarTextStyle(+ color: theme.foreground,+ emphasized: emphasized,+ ),+ ),+ ),+ SizedBox(width: cell.width),+ ListenableBuilder(+ listenable: _tabScroll,+ builder: (context, _) {+ final left = _tabWidths+ .take(index)+ .fold(+ 0.0,+ (a, b) => a + b,+ );+ final offset =+ _tabScroll.hasClients+ ? _tabScroll.offset+ : 0.0;+ return ActivityMark(+ key: ValueKey(+ 'tab-activity:${swarm.id}',+ ),+ activity: activity,+ color: activityColor(+ activity,+ theme,+ color: prefs.color,+ ),+ emphasized: emphasized,+ tooltip: false,+ visible:+ left <+ offset ++ tabsWidth &&+ left + _tabWidths[index] >+ offset,+ );+ },+ ),+ ],+ ),),),),diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 4699dd01a..159b644d8 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -360,7 +360,7 @@ class MachineState {/// failed, so the daemon can say who (and not about the pane in front).final recentTurnEnds = <({String agentId, bool failed})>[];- /// Open harnesses whose last turn failed, until their next turn starts or+ /// Known harnesses whose last turn failed, until their next turn starts or/// ends well: the daemon's `fail` face while it lasts.final failedTurnAgents = <String>{};@@ -7212,10 +7212,12 @@ class AppNotifier extends ChangeNotifier {Iterable<({String machineId, String agentId})> _visibleOnTab() {if (lifecycle() != AppLifecycleState.resumed) return const [];+ if (activeSwarm.isStore || activeSwarm.isOrchestrator) return const [];return [for (final pane in activeSwarm.panes)- if (pane.agentId case final agentId?)- (machineId: pane.machineId, agentId: agentId),+ if (zoomedPaneId == null || pane.id == zoomedPaneId)+ if (pane.agentId case final agentId?)+ (machineId: pane.machineId, agentId: agentId),];}@@ -12878,6 +12880,15 @@ class AppNotifier extends ChangeNotifier {pane.session != null,);final failed = event['error'] != null || payload['error'] != null;+ // Activity belongs to the harness, even if its pane is currently+ // detached. The zoo counters below still count only our own work.+ if (agent != null && !isTerminalEngine(agent.engine)) {+ if (failed) {+ machine.failedTurnAgents.add(agentId);+ } else {+ machine.failedTurnAgents.remove(agentId);+ }+ }if (ownWork && !failed) {machine.completedHarnessUses.add((harness: agent.dsh == null@@ -12886,10 +12897,8 @@ class AppNotifier extends ChangeNotifier {model: agent.gridModel,));machine.completedHarnessTurns++;- machine.failedTurnAgents.remove(agentId);} else if (ownWork) {machine.failedHarnessTurns++;- machine.failedTurnAgents.add(agentId);}if (ownWork) {machine.recentTurnEnds.add((agentId: agentId, failed: failed));diff --git a/desktop/lib/state/harness_activity.dart b/desktop/lib/state/harness_activity.dartnew file mode 100644index 000000000..ebcc3e394--- /dev/null+++ b/desktop/lib/state/harness_activity.dart@@ -0,0 +1,93 @@+import '../core/models.dart';+import '../notify/alert_sounds.dart';+import '../widgets/engine_identity.dart' show isTerminalEngine;+import 'app_state.dart';+import 'swarm.dart';++/// The TUI's states, ordered by a tab's most urgent member. Activity is+/// separate from unread results: a new turn always looks busy, not finished.+enum HarnessActivity {+ needsInput('?', 'Needs your input'),+ failed('✗', 'Failed'),+ done('✓', 'Finished · unread'),+ working('⠋', 'Working'),+ starting('◌', 'Starting'),+ idle('', 'Idle'),+ paused('||', 'Paused'),+ offline('⊘', 'Offline');++ const HarnessActivity(this.mark, this.label);+ final String mark;+ final String label;+}++const activitySpinnerFrames = [+ '⠋',+ '⠙',+ '⠹',+ '⠸',+ '⠼',+ '⠴',+ '⠦',+ '⠧',+ '⠇',+ '⠏',+];+const activityFrameInterval = Duration(milliseconds: 100);++int activityFrameAt(DateTime time) =>+ (time.millisecondsSinceEpoch ~/ activityFrameInterval.inMilliseconds) %+ activitySpinnerFrames.length;++HarnessActivity? harnessActivity(+ AppNotifier app,+ String machineId,+ String agentId,+) {+ final machine = app.stateOf(machineId);+ final agent = machine?.agents.where((a) => a.id == agentId).firstOrNull;+ // A shell or an unknown roster entry has no agent activity to report.+ if (machine == null || agent == null || isTerminalEngine(agent.engine)) {+ return null;+ }+ if (machine.isOffline ||+ machine.needsLink ||+ (!machine.machine.isShared &&+ machine.connectionStatus != ConnectionStatus.connected)) {+ return HarnessActivity.offline;+ }+ if (agent.isStopped) return HarnessActivity.paused;+ if (agent.launchState == 'starting') return HarnessActivity.starting;+ if (agent.launchState == 'failed') {+ return agent.launchError == 'RESUME_UNCONFIRMED'+ ? HarnessActivity.needsInput+ : HarnessActivity.failed;+ }+ if (machine.blockedAgents.containsKey(agentId)) {+ return HarnessActivity.needsInput;+ }+ if (machine.processingAgentIds.contains(agentId)) {+ return HarnessActivity.working;+ }+ if (machine.failedTurnAgents.contains(agentId)) return HarnessActivity.failed;+ if (app.agentUnread.kindFor(machineId, agentId) == AlertKind.done) {+ return HarnessActivity.done;+ }+ return HarnessActivity.idle;+}++/// A viewer refers to its owner; showing the same harness twice adds no vote.+HarnessActivity? tabActivity(AppNotifier app, Swarm tab) {+ if (tab.isStore || tab.isOrchestrator) return null;+ HarnessActivity? result;+ final seen = <(String, String)>{};+ for (final pane in tab.panes) {+ final id = pane.isWeb ? pane.ownerAgentId : pane.agentId;+ if (id == null || !seen.add((pane.machineId, id))) continue;+ final state = harnessActivity(app, pane.machineId, id);+ if (state != null && (result == null || state.index < result.index)) {+ result = state;+ }+ }+ return result;+}diff --git a/desktop/lib/widgets/harness_activity_mark.dart b/desktop/lib/widgets/harness_activity_mark.dartnew file mode 100644index 000000000..9e0a6dc8d--- /dev/null+++ b/desktop/lib/widgets/harness_activity_mark.dart@@ -0,0 +1,268 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:xterm/xterm.dart' show TerminalTheme;++import '../shared/theme/app_theme.dart' as grid;+import '../shared/theme/appearance_prefs_store.dart';+import '../shared/theme/workspace_bar_style.dart';+import '../state/app_state.dart';+import '../state/harness_activity.dart';+import '../terminal/terminal_theme.dart';+import '../terminal/terminal_theme_store.dart';++Color activityColor(+ HarnessActivity state,+ TerminalTheme theme, {+ bool color = true,+}) {+ if (!color) return theme.foreground;+ return switch (state) {+ HarnessActivity.needsInput || HarnessActivity.starting => theme.yellow,+ HarnessActivity.failed => theme.red,+ HarnessActivity.done => theme.green,+ HarnessActivity.working => theme.cyan,+ _ => theme.foreground.withValues(alpha: .55),+ };+}++/// One clock for visible Flutter marks, aligned with hn and AppKit's Unix-time+/// frames. No listeners means no timer; background apps do not keep ticking.+class ActivityClock extends ChangeNotifier with WidgetsBindingObserver {+ ActivityClock({DateTime Function()? now}) : now = now ?? DateTime.now;+ final DateTime Function() now;+ Timer? _timer;+ int? _lastFrame;+ bool _observing = false;+ int get frame => activityFrameAt(now());+ bool get running => _timer != null;++ @override+ void addListener(VoidCallback listener) {+ super.addListener(listener);+ if (!_observing) {+ WidgetsBinding.instance.addObserver(this);+ _observing = true;+ }+ _schedule();+ }++ @override+ void removeListener(VoidCallback listener) {+ super.removeListener(listener);+ if (!hasListeners) {+ _timer?.cancel();+ _timer = null;+ _lastFrame = null;+ WidgetsBinding.instance.removeObserver(this);+ _observing = false;+ }+ }++ void _schedule() {+ final lifecycle = WidgetsBinding.instance.lifecycleState;+ if (!hasListeners ||+ (lifecycle != null && lifecycle != AppLifecycleState.resumed)) {+ _timer?.cancel();+ _timer = null;+ return;+ }+ if (_timer != null) return;+ _lastFrame ??= frame;+ final interval = activityFrameInterval.inMilliseconds;+ _timer = Timer(+ Duration(+ milliseconds: interval - now().millisecondsSinceEpoch % interval,+ ),+ () {+ _timer = null;+ final next = frame;+ if (next != _lastFrame) {+ _lastFrame = next;+ notifyListeners();+ }+ _schedule();+ },+ );+ }++ @override+ void didChangeAppLifecycleState(AppLifecycleState state) => _schedule();++ @override+ void dispose() {+ _timer?.cancel();+ _timer = null;+ if (_observing) WidgetsBinding.instance.removeObserver(this);+ super.dispose();+ }+}++final _activityClock = ActivityClock();++/// One status cell, with a stable semantic label outside the animated subtree.+/// Only this repaint boundary changes on a tick, never the terminal or tab.+class ActivityMark extends StatefulWidget {+ const ActivityMark({+ super.key,+ required this.activity,+ required this.color,+ this.visible = true,+ this.emphasized = false,+ this.tooltip = true,+ this.clock,+ });+ final HarnessActivity activity;+ final Color color;+ final bool visible, emphasized, tooltip;+ final ActivityClock? clock;++ @override+ State<ActivityMark> createState() => _ActivityMarkState();+}++class _ActivityMarkState extends State<ActivityMark> {+ ActivityClock get clock => widget.clock ?? _activityClock;+ bool _listening = false;++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ _sync();+ }++ @override+ void didUpdateWidget(ActivityMark oldWidget) {+ super.didUpdateWidget(oldWidget);+ if (oldWidget.clock != widget.clock && _listening) {+ (oldWidget.clock ?? _activityClock).removeListener(_tick);+ _listening = false;+ }+ _sync();+ }++ void _sync() {+ final listen =+ widget.activity == HarnessActivity.working &&+ widget.visible &&+ TickerMode.valuesOf(context).enabled &&+ !MediaQuery.disableAnimationsOf(context);+ if (listen == _listening) return;+ _listening = listen;+ if (listen) {+ clock.addListener(_tick);+ } else {+ clock.removeListener(_tick);+ }+ }++ void _tick() {+ if (mounted) setState(() {});+ }++ @override+ void dispose() {+ if (_listening) clock.removeListener(_tick);+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ final mark = _listening+ ? activitySpinnerFrames[clock.frame]+ : widget.activity.mark;+ final cell = workspaceBarCellSizeOf(context);+ var style =+ workspaceBarTextStyle(+ color: widget.color,+ emphasized: widget.emphasized,+ ).copyWith(+ fontFamilyFallback: [+ ...?workspaceBarTextStyle().fontFamilyFallback,+ // SF Mono and Menlo lack Braille; the fixed cell still uses+ // workspace metrics while the OS symbol font supplies dots.+ 'Apple Symbols',+ 'DejaVu Sans',+ ],+ );+ if (widget.activity == HarnessActivity.paused) {+ // Two short ASCII pipes, tightened into the same cell as every other+ // mark. Keep these metrics in sync with SwarmTabButton's native drawing.+ style = style.copyWith(+ fontSize: workspaceBarFontSize * .65,+ letterSpacing: -cell.width * .25,+ );+ }+ final child = Semantics(+ label: widget.activity.label,+ child: ExcludeSemantics(+ child: RepaintBoundary(+ child: SizedBox(+ width: cell.width,+ child: Text(+ mark,+ textAlign: TextAlign.center,+ maxLines: 1,+ overflow: TextOverflow.clip,+ style: style,+ ),+ ),+ ),+ ),+ );+ return widget.tooltip+ ? Tooltip(message: widget.activity.label, child: child)+ : child;+ }+}++/// Pane headers listen to activity and acknowledgement independently of their+/// cached title/controls, so a turn or unread change never rebuilds a terminal.+class HarnessActivityMark extends StatelessWidget {+ const HarnessActivityMark({+ super.key,+ required this.app,+ required this.machineId,+ required this.agentId,+ this.visible = true,+ });+ final AppNotifier app;+ final String machineId, agentId;+ final bool visible;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ return ListenableBuilder(+ listenable: Listenable.merge([+ app,+ app.agentUnread,+ terminalThemeStore,+ appearancePrefsStore,+ ]),+ builder: (context, _) {+ final state = harnessActivity(app, machineId, agentId);+ if (state == null) return const SizedBox.shrink();+ final theme = terminalThemeFor(+ grid.AppTheme.palette.value,+ terminalThemeStore.value,+ );+ return Padding(+ padding: EdgeInsets.only(left: workspaceBarCellSizeOf(context).width),+ child: ActivityMark(+ activity: state,+ color: activityColor(+ state,+ theme,+ color: appearancePrefsStore.value.prompt.color,+ ),+ visible:+ visible &&+ !app.activeSwarm.isStore &&+ !app.activeSwarm.isOrchestrator,+ ),+ );+ },+ );+ }+}diff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dartindex 1fa233124..ddaaddbe5 100644--- a/desktop/lib/widgets/pane_grid.dart+++ b/desktop/lib/widgets/pane_grid.dart@@ -32,6 +32,7 @@ import 'new_agent_dialog.dart';import 'delete_agent_dialog.dart';import 'restart_agent_action.dart';import 'terminal_panel.dart';+import 'harness_activity_mark.dart';import 'web_pane_panel.dart';import 'pane_resize_handle.dart';import 'box_chrome.dart';@@ -1320,6 +1321,7 @@ class _PaneContent extends StatelessWidget {notifier: notifier,pane: pane,title: viewerPaneName(owner, machine?.dsh.entries ?? const []),+ visible: visible,ownerName: owner?.name ?? pane.ownerAgentId ?? 'Viewer',ownerEngine: owner?.identityEngine,ownerDisplayName: owner?.identityDisplayName,@@ -1340,6 +1342,14 @@ class _PaneContent extends StatelessWidget {}final session = pane.session;final wantedAgentId = pane.agentId;+ final activityMark = wantedAgentId == null+ ? null+ : HarnessActivityMark(+ app: notifier,+ machineId: pane.machineId,+ agentId: wantedAgentId,+ visible: visible,+ );final agent = machine?.agents.where((agent) => agent.id == wantedAgentId).firstOrNull;@@ -1508,6 +1518,7 @@ class _PaneContent extends StatelessWidget {final waiting = !listFailed && !notifier.machineInventoryLoaded;final stale = notifier.machinesAreStale;return _PaneStatus(+ activity: activityMark,title: wantedAgentId == null ? 'Machine' : kUntitledPane,icon: listFailed || stale ? Icons.cloud_off : Icons.link_off,message: listFailed@@ -1525,6 +1536,7 @@ class _PaneContent extends StatelessWidget {}if (needsLink) {return _PaneStatus(+ activity: activityMark,title: agentName ?? machine.machine.displayName,icon: Icons.link_off,message:@@ -1545,6 +1557,7 @@ class _PaneContent extends StatelessWidget {}if (offline) {return _Guide(+ activity: activityMark,single: single && !swarmMode,onClose: close,title: agentName ?? machine.machine.displayName,@@ -1561,6 +1574,7 @@ class _PaneContent extends StatelessWidget {}if (wantedAgentId == null) {return _PaneStatus(+ activity: activityMark,title: machine.machine.displayName,icon: Icons.check_circle_outline,message: 'This machine is ready. Drag an agent here to open it.',@@ -1569,6 +1583,7 @@ class _PaneContent extends StatelessWidget {}if (agentName == null) {return _PaneStatus(+ activity: activityMark,title: wantedAgentId,icon: Icons.help_outline,message: 'This agent is no longer on ${machine.machine.displayName}.',@@ -1577,6 +1592,7 @@ class _PaneContent extends StatelessWidget {}if (agent != null && !agent.terminalAvailable) {return _PaneStatus(+ activity: activityMark,title: agentName,icon: Icons.terminal,message:@@ -1591,6 +1607,7 @@ class _PaneContent extends StatelessWidget {// would promise something that is never coming.if (!machine.terminalNoTakeoverAvailable) {return _PaneStatus(+ activity: activityMark,title: agentName,icon: Icons.terminal,message:@@ -1605,6 +1622,7 @@ class _PaneContent extends StatelessWidget {);}return _PaneStatus(+ activity: activityMark,title: agentName,icon: Icons.hourglass_empty,message: 'Attaching…',@@ -1953,6 +1971,7 @@ class _Guide extends StatelessWidget {required this.single,required this.onClose,required this.title,+ this.activity,required this.compactMessage,required this.compactIcon,required this.full,@@ -1961,6 +1980,7 @@ class _Guide extends StatelessWidget {final bool single;final VoidCallback onClose;final String title;+ final Widget? activity;final String compactMessage;final IconData compactIcon;final Widget full;@@ -1977,12 +1997,13 @@ class _Guide extends StatelessWidget {if (single) return full;return Column(children: [- _PaneHeader(title: title, onClose: onClose),+ _PaneHeader(title: title, onClose: onClose, activity: activity),Expanded(child: full),],);}return _PaneStatus(+ activity: activity,title: title,icon: compactIcon,message: compactMessage,@@ -1996,9 +2017,10 @@ class _Guide extends StatelessWidget {/// The same 46pt strip TerminalPanel draws, for the tiles that have no terminal/// to draw one — so the close button never moves between states.class _PaneHeader extends StatelessWidget {- const _PaneHeader({required this.title, this.onClose});+ const _PaneHeader({required this.title, this.onClose, this.activity});final String title;+ final Widget? activity;final VoidCallback? onClose;@override@@ -2015,13 +2037,20 @@ class _PaneHeader extends StatelessWidget {child: Row(children: [Expanded(- child: Text(- title,- overflow: TextOverflow.ellipsis,- style: grid.AppType.monoLabel(- color: AppColors.text,- fontWeight: FontWeight.w600,- ),+ child: Row(+ children: [+ Flexible(+ child: Text(+ title,+ overflow: TextOverflow.ellipsis,+ style: grid.AppType.monoLabel(+ color: AppColors.text,+ fontWeight: FontWeight.w600,+ ),+ ),+ ),+ ?activity,+ ],),),if (onClose != null) PaneCloseButton(onPressed: onClose!),@@ -2037,6 +2066,7 @@ class _PaneHeader extends StatelessWidget {class _PaneStatus extends StatelessWidget {const _PaneStatus({required this.title,+ this.activity,required this.icon,required this.message,this.onClose,@@ -2046,6 +2076,7 @@ class _PaneStatus extends StatelessWidget {});final String title;+ final Widget? activity;final IconData icon;final String message;final VoidCallback? onClose;@@ -2061,7 +2092,7 @@ class _PaneStatus extends StatelessWidget {grid.AppTheme.watch(context);return Column(children: [- _PaneHeader(title: title, onClose: onClose),+ _PaneHeader(title: title, onClose: onClose, activity: activity),Divider(height: 1, color: AppColors.border),Expanded(child: Center(diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dartindex 83a74c146..926317898 100644--- a/desktop/lib/widgets/terminal_panel.dart+++ b/desktop/lib/widgets/terminal_panel.dart@@ -41,6 +41,7 @@ import '../shared/theme/app_theme.dart' as grid;import '../shared/theme/workspace_bar_style.dart';import '../theme/app_theme.dart';import 'engine_identity.dart';+import 'harness_activity_mark.dart';import 'grid_model_picker.dart';import 'pane_header_actions.dart';import 'pane_model_status.dart';@@ -2366,7 +2367,7 @@ class _TerminalPanelState extends State<TerminalPanel>pickerController: _pickerController,);}- return _header!;+ return TickerMode(enabled: widget.visible, child: _header!);}}@@ -2673,6 +2674,11 @@ class _TerminalHeader extends StatelessWidget {),),),+ HarnessActivityMark(+ app: notifier,+ machineId: session.machineId,+ agentId: session.agentId,+ ),if (status != null || starting != null || !compact)const SizedBox(width: 8),if (status != null && narrow)diff --git a/desktop/lib/widgets/web_pane_panel.dart b/desktop/lib/widgets/web_pane_panel.dartindex e169eddb8..69c30c1b0 100644--- a/desktop/lib/widgets/web_pane_panel.dart+++ b/desktop/lib/widgets/web_pane_panel.dart@@ -14,6 +14,7 @@ import '../state/terminal_pane.dart';import '../theme/app_theme.dart';import '../viewer/interactive_viewer.dart';import 'engine_identity.dart';+import 'harness_activity_mark.dart';import '../terminal/terminal_text.dart';import 'verdict_marks.dart';@@ -45,9 +46,11 @@ class WebPanePanel extends StatefulWidget {this.onToggleZoom,this.zoomed = false,this.compactHeader = false,+ this.visible = true,});final AppNotifier notifier;+ final bool visible;final TerminalPane pane;/// What the pane is called in its header ("3D Viewer"); see viewerPaneName.@@ -286,6 +289,13 @@ class _WebPanePanelState extends State<WebPanePanel> {style: workspaceBarTextStyle(color: AppColors.text),),),+ if (widget.pane.ownerAgentId case final ownerId?)+ HarnessActivityMark(+ app: widget.notifier,+ machineId: widget.pane.machineId,+ agentId: ownerId,+ visible: widget.visible,+ ),if (widget.verdict case final verdict?) ...[Text(' · ',diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swiftindex 635d326f3..93ad17d99 100644--- a/desktop/macos/Runner/SwarmTitlebar.swift+++ b/desktop/macos/Runner/SwarmTitlebar.swift@@ -1406,6 +1406,29 @@ private final class SwarmVoiceLabel: NSView {}}+/// Mirrors hn and Dart's ten-frame, 100ms Braille clock. The channel sends only+/// activity changes; animation never pushes workspace snapshots through Flutter.+private let harnessActivityFrames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]+private func harnessActivityFrame(at date: Date = Date()) -> Int {+ Int(date.timeIntervalSince1970 * 1000) / 100 % harnessActivityFrames.count+}++private struct SwarmTabActivity: Equatable {+ let mark: String+ let label: String+ let working: Bool+ let color: NSColor++ init?(_ payload: [String: Any]?) {+ guard let payload, let mark = payload["mark"] as? String,+ let label = payload["label"] as? String else { return nil }+ self.mark = mark+ self.label = label+ working = payload["working"] as? Bool == true+ color = statusColor(payload["color"], fallback: .labelColor)+ }+}+private final class SwarmTabStrip: NSView {private(set) var palette = SwarmNativePalette()var emit: ((String, Any?) -> Void)?@@ -1431,6 +1454,10 @@ private final class SwarmTabStrip: NSView {private var revealActiveAfterLayout = falseprivate var tabOrderChanged = falseprivate var actionsEnabled = false+ private var reduceMotion = false+ private var activityTimer: Timer?+ private var activityObservers: [NSObjectProtocol] = []+ private var motionObserver: NSObjectProtocol?private var lastBackgroundClick: (time: TimeInterval, point: NSPoint)?// Dragging is explicit below. AppKit must not also start a titlebar gesture.override var mouseDownCanMoveWindow: Bool { false }@@ -1503,9 +1530,59 @@ private final class SwarmTabStrip: NSView {addSubview(shareButton)setAccessibilityChildren([scroll, newButton, focusedModelButton, contextButton, pullRequestButton, voiceLabel, daemonButton, shareButton])registerForDraggedTypes([swarmPasteboardType])+ scroll.contentView.postsBoundsChangedNotifications = true+ for name in [NSApplication.didBecomeActiveNotification, NSApplication.didResignActiveNotification,+ NSWindow.didChangeOcclusionStateNotification, NSView.boundsDidChangeNotification] {+ let object: AnyObject? = name == NSView.boundsDidChangeNotification ? scroll.contentView : nil+ activityObservers.append(NotificationCenter.default.addObserver(forName: name, object: object, queue: .main) {+ [weak self] _ in self?.syncActivityAnimation()+ })+ }+ motionObserver = NSWorkspace.shared.notificationCenter.addObserver(+ forName: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification, object: nil, queue: .main) {+ [weak self] _ in self?.syncActivityAnimation()+ }}required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }+ deinit {+ activityTimer?.invalidate()+ daemonRevealTimer?.invalidate()+ activityObservers.forEach(NotificationCenter.default.removeObserver)+ if let motionObserver { NSWorkspace.shared.notificationCenter.removeObserver(motionObserver) }+ }++ override func viewDidMoveToWindow() {+ super.viewDidMoveToWindow()+ syncActivityAnimation()+ }++ private var visibleWorkingTabs: [SwarmTabButton] {+ tabs.filter { $0.activity?.working == true && scroll.documentVisibleRect.intersects($0.frame) }+ }++ private func syncActivityAnimation() {+ let moving = actionsEnabled && !reduceMotion &&+ !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion && NSApp.isActive &&+ window?.occlusionState.contains(.visible) == true && !isHiddenOrHasHiddenAncestor &&+ !visibleWorkingTabs.isEmpty+ guard moving else {+ activityTimer?.invalidate()+ activityTimer = nil+ for tab in tabs { tab.activityFrame = 0 }+ return+ }+ for tab in visibleWorkingTabs { tab.activityFrame = harnessActivityFrame() }+ guard activityTimer == nil else { return }+ let next = (floor(Date().timeIntervalSince1970 * 10) + 1) / 10+ let timer = Timer(fire: Date(timeIntervalSince1970: next), interval: 0.1, repeats: true) { [weak self] _ in+ guard let self else { return }+ for tab in self.visibleWorkingTabs { tab.activityFrame = harnessActivityFrame() }+ }+ activityTimer = timer+ RunLoop.main.add(timer, forMode: .common)+ }+func updatePalette(_ values: [String: Any]) {let nextPalette = SwarmNativePalette(values)guard nextPalette != palette else { return }@@ -1520,6 +1597,7 @@ private final class SwarmTabStrip: NSView {// Workspace teardown clears its controls without changing appearance.if let palette = state["palette"] as? [String: Any] { updatePalette(palette) }actionsEnabled = state["enabled"] as? Bool == true+ reduceMotion = state["reduceMotion"] as? Bool == trueif let style = state["barStyle"] as? [String: Any] {let size = CGFloat(min(36, max(8, (style["size"] as? NSNumber)?.doubleValue ?? 13)))let families = [style["family"] as? String].compactMap { $0 } + (style["fallback"] as? [String] ?? [])@@ -1584,6 +1662,7 @@ private final class SwarmTabStrip: NSView {tab.keyboardFocus = tabsFocused && id == activeIdtab.actionsEnabled = actionsEnabledtab.attention = (row["attention"] as? Int ?? 0) > 0+ tab.activity = SwarmTabActivity(row["activity"] as? [String: Any])tab.emit = { [weak self, weak tab] method, args inguard let self, let tab, self.actionsEnabled,self.tabs.contains(where: { $0 === tab }) else { return }@@ -1601,6 +1680,7 @@ private final class SwarmTabStrip: NSView {needsDisplay = trueneedsLayout = truelayoutSubtreeIfNeeded()+ syncActivityAnimation()if ids != previousOrder {NSAccessibility.post(element: document, notification: .layoutChanged)}@@ -1725,7 +1805,7 @@ private final class SwarmTabStrip: NSView {y: (bounds.height - toolHeight) / 2, width: daemonWidth, height: toolHeight)// Compact windows keep a scrolling tab list; context never overlaps it.let available = max(0, bounds.width - cell * 7 - shareSpace - daemonWidth)- let widths = tabs.map { min($0.preferredWidth, available * 0.45) }+ let widths = tabs.map { max($0.minimumWidth, min($0.preferredWidth, available * 0.45)) }let total = widths.reduce(0, +)let occupied = min(total, available * 0.45)let scrollX = cell@@ -1763,6 +1843,7 @@ private final class SwarmTabStrip: NSView {}revealActiveAfterLayout = falsetabOrderChanged = false+ syncActivityAnimation()}override func draw(_ dirtyRect: NSRect) {// A fine rule joins the flat tabs to the workspace.@@ -1843,9 +1924,42 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidativar displayLabel = "New Tab" { didSet { if displayLabel != oldValue { invalidateLabel() } } }var foreground = NSColor(white: 0.85, alpha: 1) { didSet { if foreground != oldValue { invalidateLabel() } } }private var cellWidth: CGFloat { ceil(("m" as NSString).size(withAttributes: [.font: labelFont]).width) }+ var minimumWidth: CGFloat {+ activityLabel == nil ? 0 : (labelPrefix as NSString).size(withAttributes: [.font: labelFont]).width + cellWidth * 4+ }var preferredWidth: CGFloat { min(cellWidth * 24, ceil(max(label.size().width, emphasizedLabel.size().width) / cellWidth) * cellWidth + cellWidth * 2) }var selected = false { didSet { if selected != oldValue { invalidateLabel(); updateAccessibility() } } }- var attention = false { didSet { if attention != oldValue { needsDisplay = true; updateAccessibility() } } }+ var attention = false { didSet { if attention != oldValue { invalidateLabel(); updateAccessibility() } } }+ var activity: SwarmTabActivity? {+ didSet { if activity != oldValue { invalidateLabel(); updateAccessibility() } }+ }+ var activityFrame = 0 {+ didSet { if activityFrame != oldValue, activity?.working == true { setNeedsDisplay(activityRect) } }+ }+ // Keep the old question payload useful for an older Flutter fixture/runner.+ private var activityLabel: String? { activity?.label ?? (attention ? "Needs your input" : nil) }+ private var activityMark: String? {+ if let activity { return activity.working ? harnessActivityFrames[activityFrame] : activity.mark }+ return attention ? "?" : nil+ }+ private var labelPrefix: String {+ guard let colon = displayLabel.firstIndex(of: ":") else { return "" }+ return String(displayLabel[...colon])+ }+ private var labelText: String {+ guard activityLabel != nil else { return displayLabel }+ // Keep the trailing gap and status cell even when idle has no glyph.+ return displayLabel + " "+ }+ private var activityRect: NSRect {+ if bounds.width < minimumWidth {+ return NSRect(x: bounds.midX - cellWidth / 2, y: 0, width: cellWidth, height: bounds.height)+ }+ let available = max(0, bounds.width - cellWidth * 2)+ let textWidth = min(available, label.size().width)+ return NSRect(x: cellWidth + (available - textWidth) / 2 + textWidth - cellWidth,+ y: 0, width: cellWidth, height: bounds.height)+ }/// The strip holds the keyboard on this, the selected tab — drawn like a/// focused control, though the keys themselves stay in Flutter.var keyboardFocus = false { didSet { if keyboardFocus != oldValue { needsDisplay = true; updateAccessibility() } } }@@ -1905,6 +2019,7 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidativar hints: [String] = []if max(label.size().width, emphasizedLabel.size().width) > max(0, bounds.width - cellWidth * 2) { hints.append(displayLabel) }if !fullName.isEmpty && fullName != visibleName && fullName != displayLabel { hints.append(name) }+ if let activityLabel { hints.append(activityLabel) }toolTip = hints.isEmpty ? nil : hints.joined(separator: "\n")}override func updateTrackingAreas() {@@ -1934,7 +2049,7 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidatilet paragraph = NSMutableParagraphStyle()paragraph.lineBreakMode = .byTruncatingTailparagraph.alignment = .center- let label = NSAttributedString(string: displayLabel,+ let label = NSAttributedString(string: labelText,attributes: [.font: labelFont,.foregroundColor: foreground, .paragraphStyle: paragraph])cachedLabel = label@@ -1956,11 +2071,41 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidatipalette.workspace.setFill()bounds.fill()}- text.draw(in: NSRect(x: cellWidth, y: contentCenterY - text.size().height / 2,- width: max(0, bounds.width - cellWidth * 2), height: text.size().height))- if attention {- let marker = NSAttributedString(string: "!", attributes: [.font: labelFont, .foregroundColor: NSColor.systemOrange])- marker.draw(at: NSPoint(x: 0, y: contentCenterY - marker.size().height / 2))+ if bounds.width >= minimumWidth {+ let y = contentCenterY - text.size().height / 2+ if activity != nil || attention {+ // Keep the number and trailing activity cell; only the name truncates.+ let available = max(0, bounds.width - cellWidth * 2)+ let x = cellWidth + (available - min(available, label.size().width)) / 2+ let prefix = text.attributedSubstring(from: NSRange(location: 0, length: labelPrefix.utf16.count))+ prefix.draw(at: NSPoint(x: x, y: y))+ let start = labelPrefix.utf16.count+ let title = NSMutableAttributedString(attributedString:+ text.attributedSubstring(from: NSRange(location: start, length: text.length - start - 2)))+ let paragraph = NSMutableParagraphStyle()+ paragraph.lineBreakMode = .byTruncatingTail+ paragraph.alignment = .left+ title.addAttribute(.paragraphStyle, value: paragraph, range: NSRange(location: 0, length: title.length))+ let titleX = x + prefix.size().width+ title.draw(in: NSRect(x: titleX, y: y, width: max(0, activityRect.minX - cellWidth - titleX), height: text.size().height))+ } else {+ text.draw(in: NSRect(x: cellWidth, y: y,+ width: max(0, bounds.width - cellWidth * 2), height: text.size().height))+ }+ }+ if let activityMark {+ let font = active ? workspaceBarEmphasisFont(labelFont) : labelFont+ let paused = activityMark == "||"+ let marker = NSAttributedString(string: activityMark,+ attributes: [.font: paused ? NSFontManager.shared.convert(font, toSize: font.pointSize * 0.65) : font,+ .kern: paused ? -cellWidth * 0.25 : 0,+ .foregroundColor: activity?.color ?? NSColor.systemOrange])+ NSGraphicsContext.saveGraphicsState()+ let padding = bounds.width < minimumWidth ? 0 : cellWidth+ NSRect(x: padding, y: 0, width: max(0, bounds.width - padding * 2), height: bounds.height).clip()+ marker.draw(at: NSPoint(x: activityRect.midX - marker.size().width / 2,+ y: contentCenterY - marker.size().height / 2))+ NSGraphicsContext.restoreGraphicsState()}}// Overflowed tabs might not be drawn. Their names and selection still need@@ -1969,7 +2114,7 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidatisetAccessibilityLabel(name)selectButton.setAccessibilityLabel("Select \(name)")selectButton.setAccessibilityValue(selected ? "Selected" : "")- let help = [attention ? "Contains agents needing input" : nil,+ let help = [activityLabel,keyboardFocus ? "Keyboard is on the tabs. Press Return to type in this tab." : nil].compactMap { $0 }selectButton.setAccessibilityHelp(help.isEmpty ? nil : help.joined(separator: ". "))}diff --git a/desktop/test/fixtures/status_bar_before_daemons.json b/desktop/test/fixtures/status_bar_before_daemons.jsonindex 63cfbe68a..5b1ad7b21 100644--- a/desktop/test/fixtures/status_bar_before_daemons.json+++ b/desktop/test/fixtures/status_bar_before_daemons.json@@ -7,15 +7,15 @@40.0],[- -42.15,+ -67.3,0.0,- 104.0,+ 104.85,40.0],[- 61.85,+ 37.55,0.0,- 104.0,+ 104.85,40.0],[@@ -51,15 +51,15 @@40.0],[- -90.15,+ -16.4,0.0,- 104.0,+ 130.0,40.0],[- 13.85,+ 113.6,0.0,- 104.0,+ 130.0,40.0],[@@ -101,21 +101,15 @@40.0],[- -86.15,+ -34.15,0.0,- 104.0,+ 130.0,40.0],[- 17.85,+ 95.85,0.0,- 104.0,- 40.0- ],- [- 121.85,- 0.0,- 104.0,+ 130.0,40.0],[@@ -157,27 +151,21 @@40.0],[- -53.35,+ -27.35,0.0,- 104.0,+ 130.0,40.0],[- 50.65,+ 102.65,0.0,- 104.0,+ 130.0,40.0],[- 154.65,+ 232.65,0.0,- 104.0,- 40.0- ],- [- 258.65,- 0.0,- 104.0,+ 130.0,40.0],[@@ -221,35 +209,29 @@[-42.15,0.0,- 104.0,- 40.0- ],- [- 61.85,- 0.0,- 104.0,+ 130.0,40.0],[- 165.85,+ 87.85,0.0,- 104.0,+ 130.0,40.0],[- 269.85,+ 217.85,0.0,- 104.0,+ 130.0,40.0],[- 373.85,+ 347.85,0.0,- 104.0,+ 130.0,40.0],[- 533.0,+ 663.0,6.0,39.0,28.0diff --git a/desktop/test/harness_activity_test.dart b/desktop/test/harness_activity_test.dartnew file mode 100644index 000000000..dd6cd8094--- /dev/null+++ b/desktop/test/harness_activity_test.dart@@ -0,0 +1,293 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/notify/alert_sounds.dart';+import 'package:harness/state/harness_activity.dart';+import 'package:harness/state/pending_question.dart';+import 'package:harness/state/swarm.dart';+import 'package:harness/state/terminal_pane.dart';+import 'package:harness/widgets/harness_activity_mark.dart';+import 'package:harness/widgets/terminal_panel.dart';++import 'swarm_state_test.dart' show createApp;+import 'swarm_screen_test.dart' show terminal;++PendingQuestion activityQuestion(String id) => PendingQuestion(+ machineId: 'm',+ agentId: id,+ requestId: 'question-$id',+ answerKey: 'Continue?',+ prompt: 'Continue?',+ options: const ['Yes', 'No'],+ multi: false,+ since: DateTime(2026, 9, 28),+);++void main() {+ test('a blocked turn outranks working; a new turn hides an old result', () {+ final app = createApp(connected: true);+ addTearDown(app.dispose);+ final machine = app.stateOf('m')!;+ app.agentUnread.mark('m', 'a0', AlertKind.done);+ expect(harnessActivity(app, 'm', 'a0'), HarnessActivity.done);+ machine.processingAgentIds.add('a0');+ expect(harnessActivity(app, 'm', 'a0'), HarnessActivity.working);+ machine.blockedAgents['a0'] = activityQuestion('a0');+ expect(harnessActivity(app, 'm', 'a0'), HarnessActivity.needsInput);+ app.markAgentSeen('m', 'a0');+ expect(harnessActivity(app, 'm', 'a0'), HarnessActivity.needsInput);+ machine.blockedAgents.clear();+ machine.processingAgentIds.clear();+ expect(harnessActivity(app, 'm', 'a0'), HarnessActivity.idle);+ });++ test('disconnect and pause do not masquerade as work or failure', () {+ final app = createApp(connected: true);+ addTearDown(app.dispose);+ final machine = app.stateOf('m')!;+ machine.processingAgentIds.add('a0');+ machine.failedTurnAgents.add('a0');+ machine.connectionStatus = ConnectionStatus.reconnecting;+ expect(harnessActivity(app, 'm', 'a0'), HarnessActivity.offline);+ machine.connectionStatus = ConnectionStatus.connected;+ machine.agents = const [+ Agent(id: 'a0', name: 'Paused', engine: 'codex', status: 'stopped'),+ ];+ expect(harnessActivity(app, 'm', 'a0'), HarnessActivity.paused);+ machine.agents = const [+ Agent(+ id: 'a0',+ name: 'Starting',+ engine: 'codex',+ launchState: 'starting',+ ),+ ];+ expect(harnessActivity(app, 'm', 'a0'), HarnessActivity.starting);+ machine.agents = const [+ Agent(id: 'a0', name: 'Failed', engine: 'codex', launchState: 'failed'),+ ];+ expect(harnessActivity(app, 'm', 'a0'), HarnessActivity.failed);+ machine.agents = const [+ Agent(+ id: 'a0',+ name: 'Unconfirmed',+ engine: 'codex',+ launchState: 'failed',+ launchError: 'RESUME_UNCONFIRMED',+ ),+ ];+ expect(harnessActivity(app, 'm', 'a0'), HarnessActivity.needsInput);+ });++ test('tab urgency ignores focus, shells, and duplicate viewers', () {+ final app = createApp(connected: true);+ addTearDown(app.dispose);+ final machine = app.stateOf('m')!;+ final tab = Swarm(id: 'activity');+ for (var i = 0; i < 4; i++) {+ tab.panes.add(TerminalPane(id: i, machineId: 'm', agentId: 'a$i'));+ }+ tab.panes.add(+ TerminalPane(+ id: 10,+ machineId: 'm',+ kind: PaneKind.web,+ ownerAgentId: 'a3',+ ),+ );+ machine.processingAgentIds.add('a0');+ app.agentUnread.mark('m', 'a1', AlertKind.done);+ machine.failedTurnAgents.add('a2');+ machine.blockedAgents['a3'] = activityQuestion('a3');+ expect(tabActivity(app, tab), HarnessActivity.needsInput);+ machine.blockedAgents.clear();+ expect(tabActivity(app, tab), HarnessActivity.failed);+ machine.failedTurnAgents.clear();+ expect(tabActivity(app, tab), HarnessActivity.done);+ app.markAgentSeen('m', 'a1');+ expect(tabActivity(app, tab), HarnessActivity.working);+ machine.processingAgentIds.clear();+ expect(tabActivity(app, tab), HarnessActivity.idle);+ tab.kind = 'store';+ expect(tabActivity(app, tab), isNull);+ tab.kind = 'harness';+ machine.agents = const [Agent(id: 'a0', name: 'Shell', engine: 'terminal')];+ expect(tabActivity(app, tab), isNull);+ expect(tabActivity(app, Swarm(id: 'store', kind: 'store')), isNull);+ });++ test(+ 'failed turns remain failures when no terminal view is attached',+ () async {+ final app = createApp(connected: true);+ addTearDown(app.dispose);+ app.watchedAgents = () => [];+ await app.handleEventForTest('m', {+ 'type': 'turn_ended',+ 'agentId': 'a0',+ 'error': 'Test failure',+ });+ expect(harnessActivity(app, 'm', 'a0'), HarnessActivity.failed);+ app.markAgentSeen('m', 'a0');+ expect(+ harnessActivity(app, 'm', 'a0'),+ HarnessActivity.failed,+ reason: 'viewing a failed turn does not make it successful',+ );+ await app.handleEventForTest('m', {+ 'type': 'turn_started',+ 'agentId': 'a0',+ });+ expect(harnessActivity(app, 'm', 'a0'), HarnessActivity.working);+ await app.handleEventForTest('m', {+ 'type': 'turn_ended',+ 'agentId': 'a0',+ });+ expect(harnessActivity(app, 'm', 'a0'), HarnessActivity.done);+ app.markAgentSeen('m', 'a0');+ expect(harnessActivity(app, 'm', 'a0'), HarnessActivity.idle);+ },+ );++ test(+ 'a pane hidden by zoom stays unread until it is actually revealed',+ () async {+ final app = createApp(connected: true);+ addTearDown(app.dispose);+ app.lifecycle = () => AppLifecycleState.resumed;+ final first = app.adoptSessionForTest(terminal('a0', []));+ final second = app.adoptSessionForTest(terminal('a1', []));+ app.zoomedPaneId = first.id;+ expect(app.visibleOnTabForTest().map((p) => p.agentId), ['a0']);+ await app.handleEventForTest('m', {+ 'type': 'turn_ended',+ 'agentId': 'a1',+ });+ expect(harnessActivity(app, 'm', 'a1'), HarnessActivity.done);+ app.seeWatchedAgents();+ expect(harnessActivity(app, 'm', 'a1'), HarnessActivity.done);+ app.zoomedPaneId = second.id;+ app.seeWatchedAgents();+ expect(harnessActivity(app, 'm', 'a1'), HarnessActivity.idle);+ },+ );++ testWidgets(+ 'one synchronized clock stops for hidden, reduced-motion, and inactive marks',+ (tester) async {+ final clock = ActivityClock(now: tester.binding.clock.now);+ addTearDown(clock.dispose);+ Future<void> show({+ bool visible = true,+ bool reduce = false,+ bool ticking = true,+ }) async {+ await tester.pumpWidget(+ MaterialApp(+ home: MediaQuery(+ data: MediaQueryData(disableAnimations: reduce),+ child: TickerMode(+ enabled: ticking,+ child: Row(+ children: [+ for (var i = 0; i < 2; i++)+ ActivityMark(+ activity: HarnessActivity.working,+ color: Colors.cyan,+ visible: visible,+ clock: clock,+ ),+ ],+ ),+ ),+ ),+ ),+ );+ }++ await show();+ expect(clock.running, isTrue);+ final size = tester.getSize(find.byType(ActivityMark).first);+ for (var i = 0; i < 10; i++) {+ expect(find.text(activitySpinnerFrames[clock.frame]), findsNWidgets(2));+ expect(+ tester.getSize(find.byType(ActivityMark).first).width,+ size.width,+ );+ await tester.pump(activityFrameInterval);+ }+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);+ expect(clock.running, isFalse);+ await tester.pump(const Duration(seconds: 2));+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);+ expect(clock.running, isTrue);+ await show(visible: false);+ expect(clock.running, isFalse);+ await show(reduce: true);+ expect(clock.running, isFalse);+ expect(find.text('⠋'), findsNWidgets(2));+ await show(ticking: false);+ expect(clock.running, isFalse);+ await show();+ expect(clock.running, isTrue);+ await tester.pumpWidget(const SizedBox());+ expect(clock.running, isFalse);+ },+ );++ testWidgets(+ 'cached pane headers update without recreating the terminal or shifting its title',+ (tester) async {+ final app = createApp(connected: true);+ final session = terminal('a0', []);+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: TerminalPanel(+ notifier: app,+ session: session,+ focused: true,+ compactHeader: true,+ ),+ ),+ ),+ );+ await tester.pump();+ final panel = tester.state(find.byType(TerminalPanel));+ final titleRect = tester.getRect(+ find.byKey(const ValueKey('terminal-pane-title')),+ );+ expect(find.text('·'), findsNothing);+ expect(+ tester.getRect(find.byType(ActivityMark)).left,+ greaterThan(titleRect.right),+ );+ await app.handleEventForTest('m', {+ 'type': 'turn_started',+ 'agentId': 'a0',+ });+ await tester.pump();+ expect(+ tester.widget<ActivityMark>(find.byType(ActivityMark)).activity,+ HarnessActivity.working,+ );+ await tester.pump(const Duration(milliseconds: 300));+ await app.handleEventForTest('m', {+ 'type': 'turn_ended',+ 'agentId': 'a0',+ 'error': 'Failed',+ });+ await tester.pump();+ expect(find.text('✗'), findsOneWidget);+ expect(+ tester.getRect(find.byKey(const ValueKey('terminal-pane-title'))),+ titleRect,+ );+ expect(tester.state(find.byType(TerminalPanel)), same(panel));+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ session.dispose();+ },+ );+}diff --git a/desktop/test/pane_model_status_test.dart b/desktop/test/pane_model_status_test.dartindex 383ad68ff..5b859ac95 100644--- a/desktop/test/pane_model_status_test.dart+++ b/desktop/test/pane_model_status_test.dart@@ -102,11 +102,11 @@ void main() {tester,) async {await pane(tester, {'model': 'Qwen3.5-4B', 'webSearch': 'on'});- // The header as it was drawn before this ticket, nothing added — its order is main's since- // #329, which put the model after the machine.- expect(textsUnder(tester), ['Desktop', 'Test host', 'Qwen3.5-4B']);+ // An ordinary model adds no startup label. The trailing activity mark is+ // offline because this fixture's machine is not connected.+ expect(textsUnder(tester), ['Desktop', '⊘', 'Test host', 'Qwen3.5-4B']);await event(tester, 'turn_started', payload: {'userMessage': 'hi'});- expect(textsUnder(tester), ['Desktop', 'Test host', 'Qwen3.5-4B']);+ expect(textsUnder(tester), ['Desktop', '⊘', 'Test host', 'Qwen3.5-4B']);await settle(tester);});diff --git a/desktop/test/support/status_bar_layout.dart b/desktop/test/support/status_bar_layout.dartindex dac6dc315..85c06c870 100644--- a/desktop/test/support/status_bar_layout.dart+++ b/desktop/test/support/status_bar_layout.dart@@ -1,10 +1,13 @@// The Flutter status bar's geometry, for comparing the bar with daemons off-// against the current main bar without daemons (0e4724cd, including Share)+// against the bar without daemons (including Share and harness activity marks)// (test/fixtures/status_bar_before_daemons.json).//// Only what both versions have is read, so the same code measures either:// every control in the bar (tabs, the new-tab button, the model picker) and// the focused pane's context, in the default test font.+import 'dart:convert';+import 'dart:io';+import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/core/models.dart';@@ -53,5 +56,13 @@ Future<Map<String, List<List<double>>>> measureStatusBar(box(tester.getRect(find.byKey(const ValueKey('workspace-pane-context')))),];}+ // Explicit regeneration for intentional bar layout changes; normal test runs+ // only compare the checked-in fixture.+ final capture = Platform.environment['HARNESS_STATUS_BAR_CAPTURE_PATH'];+ if (capture != null) {+ File(+ capture,+ ).writeAsStringSync('${const JsonEncoder.withIndent(' ').convert(out)}\n');+ }return out;}diff --git a/desktop/test/swarm_arrange_keyboard_test.dart b/desktop/test/swarm_arrange_keyboard_test.dartindex a9daa85a6..36f369ec8 100644--- a/desktop/test/swarm_arrange_keyboard_test.dart+++ b/desktop/test/swarm_arrange_keyboard_test.dart@@ -36,9 +36,7 @@ void main() {await tester.pump();final label = find.descendant(of: strip,- matching: find.text(- '${app.swarms.indexOf(app.activeSwarm) + 1}:${app.activeSwarm.name}',- ),+ matching: find.byKey(ValueKey(app.activeSwarmId)),);expect(label, findsOneWidget);final viewport = tester.getRect(strip);diff --git a/desktop/test/swarm_interactions_test.dart b/desktop/test/swarm_interactions_test.dartindex 8034c8844..e84079a25 100644--- a/desktop/test/swarm_interactions_test.dart+++ b/desktop/test/swarm_interactions_test.dart@@ -228,7 +228,7 @@ void main() {expect(tab['id'], office.id);expect(tab['label'], '1:office');} else {- expect(find.text('1:office'), findsOneWidget);+ expect(find.text('office'), findsOneWidget);}expect(tester.takeException(), isNull);await tester.pumpWidget(const SizedBox());diff --git a/desktop/test/swarm_screen_test.dart b/desktop/test/swarm_screen_test.dartindex 01cb5caca..dfe52ca26 100644--- a/desktop/test/swarm_screen_test.dart+++ b/desktop/test/swarm_screen_test.dart@@ -276,7 +276,13 @@ void main() {);expect(row['iconAsset'], 'assets/engine-icons/marp.png');} else {- expect(find.text('1:Quarterly deck'), findsOneWidget);+ expect(+ find.descendant(+ of: find.byKey(ValueKey(tab.id)),+ matching: find.text('Quarterly deck'),+ ),+ findsOneWidget,+ );}// An agent the machine no longer lists is drawn as its session's engine,@@ -408,7 +414,7 @@ void main() {expect(row['engine'], 'codex');expect(row['iconAsset'], 'assets/engine-icons/codex.png');} else {- expect(find.text('1:code'), findsOneWidget);+ expect(find.text('code'), findsOneWidget);}// A harness's viewer beside its agent is the same agent: still its mark, not a group.@@ -428,7 +434,7 @@ void main() {expect(row['agentCount'], 1);expect(row['engine'], 'codex');} else {- expect(find.text('1:New Tab'), findsOneWidget);+ expect(find.text('New Tab'), findsOneWidget);expect(find.byKey(ValueKey('tab-group:${tab.id}')), findsNothing);}tab.panes.removeWhere((pane) => pane.id == 900);@@ -440,7 +446,7 @@ void main() {expect(row['agentCount'], 2);expect(row['engine'], isNull);} else {- expect(find.text('1:New Tab'), findsOneWidget);+ expect(find.text('New Tab'), findsOneWidget);}await app.closePane(app.panes.last.id);@@ -451,7 +457,7 @@ void main() {'codex',);} else {- expect(find.text('1:New Tab'), findsOneWidget);+ expect(find.text('New Tab'), findsOneWidget);expect(find.byKey(ValueKey('tab-group:${tab.id}')), findsNothing);}expect(app.activeSwarm, same(tab));diff --git a/desktop/test/terminal_ui_typography_test.dart b/desktop/test/terminal_ui_typography_test.dartindex b0a60b968..e904f9c0f 100644--- a/desktop/test/terminal_ui_typography_test.dart+++ b/desktop/test/terminal_ui_typography_test.dart@@ -12,6 +12,7 @@ import 'package:harness/state/new_harness.dart';import 'package:harness/state/swarm_catalog.dart';import 'package:harness/terminal/terminal_text.dart';import 'package:harness/widgets/delete_agent_dialog.dart';+import 'package:harness/widgets/harness_activity_mark.dart';import 'package:harness/widgets/new_harness_form.dart';import 'package:harness/widgets/pane_header_actions.dart';import 'package:harness/widgets/swarm_dialogs.dart';@@ -136,6 +137,7 @@ void main() {widget.key == const ValueKey('workspace-status-bar') ||widget.key == const ValueKey('terminal-pane-title') ||widget.key == const ValueKey('viewer-pane-title') ||+ widget is ActivityMark ||widget is PaneHeaderActions,),matching: find.byWidget(element.widget),diff --git a/desktop/test/workspace_activity_test.dart b/desktop/test/workspace_activity_test.dartnew file mode 100644index 000000000..79fe621f1--- /dev/null+++ b/desktop/test/workspace_activity_test.dart@@ -0,0 +1,191 @@+import 'dart:convert';+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/state/harness_activity.dart';+import 'package:harness/terminal/terminal_theme_store.dart';+import 'package:harness/widgets/harness_activity_mark.dart';++import 'harness_activity_test.dart' show activityQuestion;+import 'swarm_state_test.dart' show createApp;+import 'swarm_screen_test.dart' show mount, terminal;+import 'support/real_fonts.dart';++Future<void> captureWorkspace(WidgetTester tester, String path) =>+ tester.runAsync(() async {+ final view = tester.binding.renderViews.first;+ final image = await (view.debugLayer! as OffsetLayer).toImage(+ Offset.zero & view.size,+ pixelRatio: 2,+ );+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);+ await File(path).writeAsBytes(bytes!.buffer.asUint8List());+ image.dispose();+ });++void main() {+ final capture = Platform.environment['HARNESS_ACTIVITY_CAPTURE_DIR'];+ setUpAll(() async {+ if (capture != null && Platform.isMacOS) {+ for (final (family, path) in [+ ('SF Mono', '/System/Library/Fonts/SFNSMono.ttf'),+ ('.AppleSystemUIFontMonospaced', '/System/Library/Fonts/SFNSMono.ttf'),+ ('Menlo', '/System/Library/Fonts/Menlo.ttc'),+ ('Apple Symbols', '/System/Library/Fonts/Apple Symbols.ttf'),+ ('.AppleSystemUIFont', '/System/Library/Fonts/SFNS.ttf'),+ ('Roboto', '/System/Library/Fonts/Supplemental/Arial.ttf'),+ ]) {+ final bytes = ByteData.sublistView(await File(path).readAsBytes());+ await (FontLoader(family)..addFont(Future.value(bytes))).load();+ }+ } else {+ await loadRealFonts();+ }+ });++ for (final native in [false, true]) {+ testWidgets(+ 'pane and tab states agree and native receives changes, not animation frames (native=$native)',+ (tester) async {+ final updates = <Map>[];+ const channel = MethodChannel('harness/swarm_tabs');+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(+ channel,+ (call) async {+ if (call.method == 'update') updates.add(call.arguments as Map);+ return true;+ },+ );+ addTearDown(+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(+ channel,+ null,+ ),+ );+ final app = createApp(connected: true);+ final machine = app.stateOf('m')!;+ app.renameSwarm(app.activeSwarmId, 'desktop');+ final first = app.activeSwarm;+ app.adoptSessionForTest(+ terminal('a0', [])..agentName = 'Review pull requests',+ );+ app.adoptSessionForTest(+ terminal('a1', [])..agentName = 'Fix reconnect',+ );+ app.newSwarm(name: 'daemons');+ final second = app.activeSwarm;+ app.adoptSessionForTest(terminal('a2', [])..agentName = 'Daemon tests');+ app.selectSwarm(first.id);+ machine.processingAgentIds.addAll(['a0', 'a1', 'a2']);+ machine.blockedAgents['a0'] = activityQuestion('a0');+ await mount(tester, app, nativeTabs: native);+ await tester.pump(const Duration(milliseconds: 100));++ HarnessActivity? flutterState(String tab) => tester+ .widget<ActivityMark>(find.byKey(ValueKey('tab-activity:$tab')))+ .activity;+ Map nativeActivity(String tab) =>+ ((updates.last['tabs'] as List).cast<Map>().singleWhere(+ (row) => row['id'] == tab,+ )['activity']+ as Map);+ if (native) {+ expect(nativeActivity(first.id)['mark'], '?');+ expect(nativeActivity(second.id)['working'], isTrue);+ final count = updates.length;+ await tester.pump(const Duration(milliseconds: 500));+ expect(updates.length, count, reason: 'native animates locally');+ expect(updates.last['reduceMotion'], isFalse);+ tester.platformDispatcher.accessibilityFeaturesTestValue =+ FakeAccessibilityFeatures(disableAnimations: true);+ await tester.pump();+ expect(updates.last['reduceMotion'], isTrue);+ tester.platformDispatcher.clearAccessibilityFeaturesTestValue();+ await tester.pump();+ } else {+ expect(flutterState(first.id), HarnessActivity.needsInput);+ expect(flutterState(second.id), HarnessActivity.working);+ expect(+ tester+ .getRect(find.byKey(ValueKey('tab-activity:${first.id}')))+ .left,+ greaterThan(tester.getRect(find.text('desktop')).right),+ );+ // Two visible panes and the second tab: the hidden daemon pane is+ // retained but contributes no extra animation or terminal rebuilds.+ expect(find.byType(HarnessActivityMark), findsNWidgets(2));+ }++ if (capture != null) {+ await tester.runAsync(() async {+ final dir = Directory(capture);+ await dir.create(recursive: true);+ if (native) {+ await File('$capture/native-activity.json')+ .writeAsString(jsonEncode(updates.last));+ }+ });+ if (!native) {+ await captureWorkspace(tester, '$capture/workspace-activity.png');+ terminalThemeStore.value = TerminalThemeChoice.tango;+ await tester.pump();+ await captureWorkspace(+ tester,+ '$capture/workspace-activity-tango.png',+ );+ terminalThemeStore.value = TerminalThemeChoice.matchApp;+ await tester.pump();+ }+ }++ machine.blockedAgents.clear();+ await app.handleEventForTest('m', {+ 'type': 'turn_ended',+ 'agentId': 'a0',+ 'error': 'Test failure',+ });+ await tester.pump(const Duration(milliseconds: 100));+ if (native) {+ expect(nativeActivity(first.id)['mark'], '✗');+ } else {+ expect(flutterState(first.id), HarnessActivity.failed);+ }+ await app.handleEventForTest('m', {+ 'type': 'turn_ended',+ 'agentId': 'a2',+ });+ await tester.pump(const Duration(milliseconds: 100));+ if (native) {+ expect(nativeActivity(second.id)['mark'], '✓');+ } else {+ expect(flutterState(second.id), HarnessActivity.done);+ }+ app.markAgentSeen('m', 'a2');+ await tester.pump();+ if (native) {+ expect(nativeActivity(second.id)['mark'], isEmpty);+ } else {+ expect(flutterState(second.id), HarnessActivity.idle);+ }+ // Narrow windows keep the symbol, shorten the name, and retain controls.+ tester.view.physicalSize = const Size(640, 600);+ await tester.pump(const Duration(milliseconds: 150));+ expect(tester.takeException(), isNull);+ if (capture != null && !native) {+ await captureWorkspace(+ tester,+ '$capture/workspace-activity-narrow.png',+ );+ }+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ grid.AppTheme.brightness.value = Brightness.dark;+ },+ );+ }+}diff --git a/desktop/test/workspace_start_guide_test.dart b/desktop/test/workspace_start_guide_test.dartindex 1e5efec43..8d43e30f1 100644--- a/desktop/test/workspace_start_guide_test.dart+++ b/desktop/test/workspace_start_guide_test.dart@@ -238,8 +238,15 @@ void main() {await tester.pumpAndSettle();expect(find.byType(WorkspaceWelcome), findsOneWidget);expect(find.text('Harness like a boss.'), findsOneWidget);- expect(find.text('✓'), findsNothing);- expect(find.text('○'), findsNothing);+ for (final mark in ['✓', '○']) {+ expect(+ find.descendant(+ of: find.byType(WorkspaceWelcome),+ matching: find.text(mark),+ ),+ findsNothing,+ );+ }expect(app.launches, hasLength(1));expect(tester.takeException(), isNull);await tester.pumpWidget(const SizedBox());diff --git a/desktop/test/workspace_status_test.dart b/desktop/test/workspace_status_test.dartindex 07c4212ca..38fb72f92 100644--- a/desktop/test/workspace_status_test.dart+++ b/desktop/test/workspace_status_test.dart@@ -521,7 +521,7 @@ void main() {'1:Release',);} else {- expect(find.text('1:Release'), findsOneWidget);+ expect(find.text('Release'), findsOneWidget);}app.newSwarm();await tester.pump();@@ -665,7 +665,9 @@ void main() {expect(workspaceTabNames(restored)[office.id], expected);expect(restored.swarms.any((tab) => tab.id == term.id), isFalse);expect(- restored.swarms.singleWhere((tab) => tab.id == office.id).nameIsCustom,+ restored.swarms+ .singleWhere((tab) => tab.id == office.id)+ .nameIsCustom,custom,);},@@ -924,12 +926,15 @@ void main() {app.newSwarm();app.adoptSessionForTest(terminal('a1', []));await mount(tester, app);- expect(find.text('1:code'), findsOneWidget);- expect(find.text('2:code'), findsOneWidget);+ expect(find.text('code'), findsNWidgets(2));+ expect(find.text('1:'), findsOneWidget);+ expect(find.text('2:'), findsOneWidget);final context = find.byKey(const ValueKey('workspace-pane-context'));expect(tester.getRect(context).left,- greaterThan(tester.getRect(find.text('2:code')).right),+ greaterThan(+ tester.getRect(find.byKey(ValueKey(app.activeSwarmId))).right,+ ),);final secondTab = find.byKey(ValueKey(app.activeSwarmId));final barControls = find.byType(WorkspaceBarControl);@@ -966,7 +971,7 @@ void main() {),findsNothing,);- await tester.tap(find.text('1:code'));+ await tester.tap(find.byKey(ValueKey(first.id)));await tester.pump(const Duration(milliseconds: 350));expect(app.activeSwarm, same(first));final originalFont = terminalFontStore.value;diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swiftindex eb342b4d5..c79443bb3 100644--- a/desktop/tool/swarm_titlebar_checks.swift+++ b/desktop/tool/swarm_titlebar_checks.swift@@ -36,6 +36,84 @@ private extension NSView {}}+private extension SwarmTabStrip {+ func checkActivityMarks() throws {+ func payload(_ mark: String, _ label: String, working: Bool = false) -> [String: Any] {+ ["mark": mark, "label": label, "working": working, "color": Int64(0xff64d2ff)]+ }+ let states: [(String, String)] = [("⠋", "Working"), ("?", "Needs your input"),+ ("✗", "Failed"), ("✓", "Finished · unread"), ("", "Idle"),+ ("◌", "Starting"), ("||", "Paused"), ("⊘", "Offline")]+ update(["enabled": true, "activeId": "activity", "tabs": [+ ["id": "activity", "name": "desktop", "label": "1:desktop", "activity": payload("⠋", "Working", working: true)]+ ]])+ let tab = tabs[0]+ try checkTitlebar(activityTimer == nil, "A hidden native strip runs no animation timer")+ try tab.checkActivityDrawing(states: states)+ update(["enabled": true, "reduceMotion": true, "activeId": "activity", "tabs": [+ ["id": "activity", "name": "desktop", "label": "1:desktop", "activity": payload("⠋", "Working", working: true)]+ ]])+ try checkTitlebar(activityTimer == nil && tab.activityFrame == 0, "Reduce Motion parks the native spinner")+ update(["enabled": true, "tabs": []])+ try checkTitlebar(activityTimer == nil, "Removing the last working tab leaves no timer")+ }+}++private extension SwarmTabButton {+ func checkActivityDrawing(states: [(String, String)]) throws {+ func payload(_ mark: String, _ label: String) -> [String: Any] {+ ["mark": mark, "label": label, "color": Int64(0xff64d2ff)]+ }+ let width = preferredWidth+ let rect = activityRect+ try checkTitlebar(labelText == "1:desktop ", "Activity reserves its cell after the tab name")+ try checkTitlebar(rect.minX > ("1:desktop" as NSString).size(withAttributes: [.font: labelFont]).width,+ "The native activity follows the complete tab name")+ var pictures = Set<Data>()+ for frame in 0..<10 {+ // Sample inside each interval: Date's reference-epoch conversion can put+ // an exact decimal boundary a fraction of a microsecond before it.+ try checkTitlebar(harnessActivityFrame(at: Date(timeIntervalSince1970: Double(frame) / 10 + 0.05)) == frame,+ "The native spinner uses hn's exact 100ms frame \(frame)")+ activityFrame = frame+ pictures.insert(renderedPixels())+ try checkTitlebar(preferredWidth == width && activityRect == rect,+ "A spinner frame never moves native tab text")+ }+ try checkTitlebar(pictures.count == 10, "All ten Braille frames render distinctly")+ for (mark, label) in states {+ activity = SwarmTabActivity(payload(mark, label))+ layoutSubtreeIfNeeded()+ try checkTitlebar(preferredWidth == width && activityRect == rect,+ "\(label) occupies the same reserved cell")+ try checkTitlebar(toolTip == label && selectButton.accessibilityHelp() == label,+ "\(label) has readable hover and accessibility descriptions")+ for narrow in [CGFloat(28), CGFloat(56), width] {+ frame.size.width = narrow+ let bitmap = renderedBitmap()+ if let capture = ProcessInfo.processInfo.environment["HARNESS_ACTIVITY_CAPTURE_DIR"] {+ try bitmap.representation(using: .png, properties: [:])!.write(to:+ URL(fileURLWithPath: capture).appendingPathComponent("native-\(label)-\(Int(narrow)).png"))+ }+ let colored = (0..<bitmap.pixelsWide).contains { x in+ (0..<bitmap.pixelsHigh).contains { y in+ guard let pixel = bitmap.colorAt(x: x, y: y)?.usingColorSpace(.sRGB),+ pixel.alphaComponent > 0.2 else { return false }+ // Antialiased dots need not contain a fully opaque ink pixel.+ // Only the mark has cyan chroma; the title and background are gray.+ return pixel.blueComponent - pixel.redComponent > 0.15 &&+ pixel.greenComponent - pixel.redComponent > 0.10 &&+ pixel.blueComponent - pixel.greenComponent > 0.04+ }+ }+ try checkTitlebar(colored == !mark.isEmpty,+ "\(label) \(mark.isEmpty ? "stays unmarked" : "remains visible") at tab width \(narrow)")+ }+ frame.size.width = width+ }+ }+}+private extension SwarmContextButton {func checkThemeSymbolsAndCaps() throws {font = NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)@@ -958,7 +1036,7 @@ private extension SwarmTabStrip {try checkTitlebar(messenger.calls.count == before + 1, "Each native tab activation sends one action")}tab.attention = true- try checkTitlebar(buttons[0].accessibilityHelp()?.contains("needing input") == true,+ try checkTitlebar(buttons[0].accessibilityHelp()?.contains("Needs your input") == true,"The attention dot has an accessible description")tab.attention = falsetry checkTitlebar(buttons[0].accessibilityHelp() == nil, "Resolved attention clears its accessible description")@@ -1748,6 +1826,7 @@ do {try strip.checkAgentIdentity()try strip.checkSharedTypography()try strip.checkShareAction()+ try strip.checkActivityMarks()try SwarmTabButton(id: "hover-fixture").checkHoverStyleAndTooltips()try strip.checkDaemon()try strip.checkDaemonOff()diff --git a/docs/research/2026-09-28-tui-desktop-interaction-study.md b/docs/research/2026-09-28-tui-desktop-interaction-study.mdnew file mode 100644index 000000000..3d825ec00--- /dev/null+++ b/docs/research/2026-09-28-tui-desktop-interaction-study.md@@ -0,0 +1,149 @@+# TUI interactions worth borrowing for desktop++Source audit: 2026-09-28, repository baseline `dafb0cab`, plus the desktop activity+marks on `feat/desktop-activity-marks`. Read the implementation behind the user's+screenshots and the repository's rendered TUI fixtures, then compared it with+the current desktop. This is a design study, not a claim that every interaction+was exercised against a live fleet. No real daemon or tmux session was changed.++The useful pattern is small, repeated cues with predictable behavior: a symbol+says what happened, one action takes you there, and the surrounding interface+stays put. Copy the behavior together with the visual detail.++## Built in this change++The same eight activity states now occupy existing desktop pane headers and+tabs. Desktop review refined their presentation: marks follow names, Idle is+blank, Paused uses two short ASCII pipes, and Offline uses a slashed circle.+Only Working animates, with hn's ten Braille frames at 100 ms. The tab+shows its most urgent member. Fixed cells, local clocks, visibility gating,+Reduce Motion, accessible labels, and native/Flutter parity are part of the+implementation. No additional toolbar, counter, or permanent legend.++```text+1:desktop ? 2:daemons ⠹ 3:tests ✓ +++[engine] Review pull requests ? x+[engine] Fix reconnect ⠹ x+```++See the [desktop activity contract](../../desktop/design/workspace-status-bar.md#harness-activity)+and [hn's state vocabulary](../../tui/src/theme.rs#L1120).++The desktop currently uses its existing unread storage: eight agents, in memory.+`✓` means an unseen completion. `✗` describes a failed launch or last turn, and+viewing it does not clear that failure. hn also has explicit read acknowledgements+for turn failures and locally persisted seen/error records. Shared vocabulary+does not yet imply identical acknowledgement or restart behavior.++## Build next: one command to review what needs attention++hn's `next-harness` goes through questions, failures, and unread completions,+oldest within each urgency group. It visits each once per pass, reveals an+existing pane when possible, and otherwise reuses the review pane. Reviewing a+large fleet does not produce a trail of new windows.++Desktop already has **Show agents needing input**, which opens the existing+filtered picker. It does not provide the same combined question/failure/result+walk. Add **Next needing attention** and **Previous needing attention** to the+existing command palette and configurable keyboard shortcuts. Reuse the+existing tab/pane when one is open. Decide acknowledgement for failures before+adding the command; otherwise a persistent failure can keep returning forever.++```text+Cmd-P > Next needing attention+ |+ v+existing tab selected → relevant pane revealed → keyboard focus there+```++This is the strongest next step because it makes the new marks actionable+without adding a permanent control. A question stays pending until answered;+looking at its pane must never count as answering it.++Evidence: [queue and pane reuse](../../tui/src/input.rs#L1121),+[urgency/age ranking](../../tui/src/fleet.rs#L477),+[current desktop attention action](../../desktop/lib/screens/swarm_screen.dart#L5225).++## Other findings, with desktop placement and parity++| Interaction | What makes the execution useful | Desktop fit and recommendation |+| --- | --- | --- |+| Return-from-away recap | Appears only after a meaningful absence and only if there is news; gives one action to review it. | A temporary message in the existing status-message area, connected to the review command. The creature already records away activity, but a general recap must also work when the creature is off. Third priority, after defining reliable unread/away accounting. |+| A row says what the agent is doing | Working rows can say `Running npm test` or `Editing app.dart`; completed rows show the recap; blocked rows show the actual question. | Improve the existing Cmd-P row detail and preview. Desktop already shows recent conversation text and questions. The new opportunity is the observed current action, not another generic Working label. Second priority. |+| A preview changes with the situation | The question or failure gets priority; a working turn can expose its plan; finished work shows the actual final response. | Add supported plan/current-action information inside the existing preview. Keep missing information absent. Preserve the matched excerpt when the user searched for conversation content. |+| Answer without navigating away | `M-1…9` or a typed answer resolves the selected question from the picker. | Consider answer controls in the existing question preview. Desktop currently treats navigation and answering as separate operations; do not silently make Enter approve a question. |+| A newly changed question cannot receive a stray key | hn binds an answer to its request ID and requires 600 ms of exposure; a row that changed under the cursor is temporarily unanswerable. | Essential companion to any future inline answers. Revalidate the same request on dispatch and retain explicit button/keyboard intent. This is part of the interaction, not optional polish. |+| Live lists stand still while choosing | hn keeps the open list's order while state/age text refreshes; new rows append. Its cursor follows an item identity. | Desktop already preserves selection and some result orders. Audit the recently-active and attention paths specifically before claiming full parity; strengthen those behaviors in the existing picker. |+| Volatile text does not destabilize search | Changing ages and current-action text are excluded from ordinary row matching so a running agent does not blink in and out of the results. | Apply when adding current-action rows. Desktop already separates preview refreshes and preserves selection; avoid making every tool call reorder Cmd-P. |+| Narrow layouts protect the actionable words | A question or failure keeps its text while machine/project columns give way; the preview moves below the list at narrow widths. | Preserve this priority in the existing desktop search. It already has compact-window attention tests; audit metadata truncation rather than adding a new compact UI. |+| Hints appear after hesitation | Holding the TUI prefix for 600 ms reveals actual configured next keys, capped to a third of the screen. | Desktop already has key hints, menus, shortcut search, and Practice. Explore delayed contextual hints inside an existing picker or menu. A bare Command key is not a tmux prefix; choose desktop semantics before implementing a hold gesture. |+| A new tab accepts the first keystroke | Typing on hn home creates a shell on the previous pane's machine/folder and buffers the initial keys until it is ready. | A possible opt-in “type to start a terminal” behavior on the existing welcome page. Numbered recents already exist. Preserve its 1–9/arrow navigation and make the typing behavior discoverable first. |+| Splits inherit the live working directory | hn prefers the shell's current OSC 7 path over the original launch directory. | Desktop already creates terminals on the focused machine and project. A useful smaller improvement is preferring an observed live shell directory when available. No new controls. |+| Opening an existing session reveals it | The preview tells you which window/session contains the harness; Enter goes there, while alternate commands explicitly place it beside/below/here. | Desktop already resolves destinations and reuses sessions. Improve location text or action hints only where the existing preview leaves placement ambiguous. |+| Project opening adds what is missing | The TUI project action reuses its named session and adds harness windows that are not already there. | Audit the existing project/workspace opening behavior. Preserve tab names and layouts. This is not a reason to recreate the recently simplified PR/Branches UI. |+| Rate limits are quiet until relevant | hn's status line shows the worst account window only when usage reaches 80%; healthy accounts consume no space. | Consider a contextual notice or the focused model's existing popover. Reuse real usage-window data; do not introduce a permanent fleet counter or infer money from token counts. |+| Slow-link typing feels immediate | Predictive echo activates only on measured slow links, waits for an echoed character in the current input epoch, and draws predictions underlined until confirmed. | A later terminal experiment, separate from status UI. There is no equivalent predictive overlay in the desktop terminal code audited here. Validate password/no-echo modes, wide characters, cursor moves, and takeover before adopting it. |+| Disconnection leaves useful context | hn dims the last terminal screen and puts the reconnect explanation in one row instead of replacing everything with a loader. | Desktop already retains terminal state across reconnects. Borrow the clarity of the explanation where needed. Do not copy queued-input replay blindly; desktop's stale-input protections are valuable. |+| Read-only ownership is explicit | A watched pane says who has the keyboard. | Desktop already has Watching/takeover state. Keep the new activity mark separate: a harness may be working while this particular view is read-only. |+| Reading and copying preserve place | Copy mode can retain scroll position; previews initially show the useful end of a conversation and then respect navigation. | Desktop already retains scroll/selection and uses conversation previews. Preserve these invariants while enriching previews rather than treating them as a new feature. |+| Attention survives restarting a client | hn saves seen times, failures, and announced questions, and rereads another local client's acknowledgements. | Desktop's unread map is bounded and in memory. Define a persistent acknowledgement model before promising complete return recaps. hn's local file is not evidence of account-wide cross-device sync. |+| Confirmation depends on interruption cost | A picker action that interrupts a working harness asks for the same action again on that same harness within three seconds; an idle harness does not get the same friction. | Consider only in the relevant action surface. Desktop already separates Close View from Stop Harness and confirms Stop. Keep that distinction; the status animation does not change process lifetime. |++## Source notes that change the recommendation++- **Recap accounting is approximate in hn.** `welcome_back()` takes positive+ differences between current pending-state counts and the counts on focus loss,+ after three minutes, and shows the message for eight seconds. It is not a+ chronological event log: one finished agent replacing another can leave the+ count unchanged. `back_again()` instead reports current pending counts after+ a restart. Borrow the brief presentation; define honest counting for desktop.+ [Implementation](../../tui/src/app.rs#L1017).+- **Normal search and attention ranking differ.** `agent_rows()` starts with+ recent activity; the open picker holds that order. `next_attention()` uses+ the separate urgency-ranked fleet. Some README prose describes all lists as+ urgency-ranked. The code is the source for this study.+ [Rows](../../tui/src/modal.rs#L215), [held order](../../tui/src/input.rs#L569).+- **Several attractive ideas already shipped on desktop.** Numbered/stable+ recents, cross-machine conversation search, previews, configurable hints,+ keyboard practice, retained terminal views, and close-without-stop are+ foundations to extend. The PR/Branches redesign from #433 stays intact.+ [Welcome](../../desktop/lib/widgets/workspace_welcome.dart),+ [recents](../../desktop/lib/state/welcome_sessions.dart),+ [search](../../desktop/lib/state/swarm_search.dart),+ [preview](../../desktop/lib/widgets/swarm_search_preview.dart),+ [attention tests](../../desktop/test/swarm_attention_picker_test.dart).+- **The creature's existing return behavior is deliberately quiet.** After a+ 15-minute absence it waves; the brief/panel carries the facts, with no takeover+ of the status line. A general return message would be a new product decision,+ not simply enabling an existing hidden banner.+ [Current behavior](../../desktop/lib/daemons/daemon_face.dart#L1006).++Additional implementation references:+[tool descriptions](../../tui/src/fleet.rs#L324),+[state-aware previews](../../tui/src/preview.rs#L36),+[answer guard](../../tui/src/input.rs#L538),+[volatile/narrow rows](../../tui/src/picker.rs#L15),+[delayed hints](../../tui/src/ui.rs#L178),+[new-tab typing](../../tui/src/input.rs#L490),+[live-directory inheritance](../../tui/src/input.rs#L1164),+[project session reuse](../../tui/src/input.rs#L1106),+[usage threshold](../../tui/src/format.rs#L1233),+[predictive echo](../../tui/src/pane.rs#L690),+[disconnect rendering](../../tui/src/ui.rs#L2459),+[persistent acknowledgements](../../tui/src/app.rs#L3750),+[target-bound confirmation](../../tui/src/input.rs#L2437).++## Proposed order++1. **Next needing attention:** command palette and configurable shortcut;+ existing tabs/panes. Define failure acknowledgement and preserve questions.+2. **More useful Cmd-P previews:** observed action and plan where supported;+ existing preview. No new sidebar or expanded pane header.+3. **Return recap:** temporary existing status-message area plus Review;+ first define reliable accounting and what persists across app restarts.++Inline answers, delayed contextual hints, live-directory inheritance, and+typing-to-start can be considered independently after those. Predictive echo+deserves its own latency and terminal-correctness work. None of these follow-up+ideas is implemented by the status-mark change.