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 workspace dialogs, tabs, and pane controls feel like a terminal (#315)
Dee430b49842098
diff --git a/desktop/AGENTS.md b/desktop/AGENTS.mdnew file mode 100644index 000000000..d9ad8c067--- /dev/null+++ b/desktop/AGENTS.md@@ -0,0 +1,9 @@+# Desktop development++Use [CLAUDE.md](CLAUDE.md) for desktop architecture, build commands, and testing+conventions.++Before adding or changing a terminal-workspace dialog, picker, form, or preview,+read and follow the [terminal dialog design system](design/terminal-dialogs.md).+Its core rule is **fixed cells, plain text, one-line selection**. It supersedes+older visual handoff notes for these surfaces.diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.mdindex 6b786f110..1d224a8cf 100644--- a/desktop/CLAUDE.md+++ b/desktop/CLAUDE.md@@ -192,9 +192,12 @@ from `node_status` pushes — distinct from our own socket status, pending offli### Command dock+For dialog presentation, follow the [terminal dialog design system](design/terminal-dialogs.md):+fixed cells, plain text, one-line selection. Cmd-N and Cmd-O are the reference implementations.+`SwarmSearchController` owns search and selection; `SwarmSearchResults` keeps a bounded cache ofvisible/recent row controls. Query-dependent match text listens separately, so typing does not-rebuild unchanged `ListTile` controls and arrows rebuild only changed highlights. The cache still+rebuild unchanged row controls and arrows rebuild only changed highlights. The cache stillinvalidates for row metadata, availability, action, geometry, theme, and font changes. Keep focus,semantics, and traversal on the row; do not replace them with paint-only search results.Creation and draft precedence are documented in `design/new-harness-entry-rules.md` and exercised@@ -242,6 +245,13 @@ its headless debug timings do not establish native display or network latency.`grid.AppTheme.brightness`, which `_GridTokenScope` in `main.dart` sets from `Theme.of(context)`.Chrome widgets call `grid.AppTheme.watch(context)` at the top of `build` so `const` subtrees stillrepaint on a theme flip.+- The [workspace status bar](design/workspace-status-bar.md) places compact numbered tabs on the left+ and focused-pane context on the right. Automatic names use the strongest shared harness type,+ project, or machine, preferring traits that distinguish tabs and excluding dependent viewers.+ The context follows a viewer's owner and uses the compact project label, never a worktree path+ or marker. User-renamed tabs always retain their saved name. Customize Harness → Status+ selects shell-inspired text or Powerline themes; the focused PR label uses that same theme.+ The single focused PR reader is `state/workspace_pull_request.dart`.- `lib/theme/app_theme.dart` (`AppColors`, `AppTheme.terminalLight/terminalDark`) is a set ofadapters over those tokens. Nothing here is `const` on purpose — freezing a colour is how light modesilently breaks. Do not add a parallel palette.@@ -249,9 +259,11 @@ its headless debug timings do not establish native display or network latency.heading 15, label/mono 13, monoLabel 12, caption/monoMeta 11) across two faces. The terminal'sface leads — headings, labels, buttons, rows, fields, tabs, shortcuts and anything copied aremono — and the system sans is kept for prose alone (`body`, `caption`), which is what stops a- screen reading as a wall of mono. Sizes are fixed: `terminalTextStyle` (the terminal's own size,- ⌘+/⌘−) is only for the grid, its composer and find field, and the empty tab's welcome page (it- stands where a terminal will), and `terminalTextScaleOf` only for their geometry — UI boxes use `appTextScaleOf`. Native tabs get the terminal face at+ screen reading as a wall of mono. Ordinary UI stays on the `AppType` scale and uses+ `appTextScaleOf` for geometry. The terminal grid, composer, find field, empty tab's welcome+ page, and terminal-workspace dialogs follow the selected terminal size (⌘+/⌘−). Dialogs use+ `terminalContentStyle()` and `terminalCellSizeOf(context)` for the exact font and character grid;+ see [the dialog guide](design/terminal-dialogs.md). Native tabs get the terminal face at`AppType.chromeSize`; native menus keep the system menu font.- `ThemeModeStore` and `TerminalFontStore` are `ValueNotifier` singletons (they must resolve above theprovider scope and before sign-in).diff --git a/desktop/README.md b/desktop/README.mdindex 2048161ab..568a4b309 100644--- a/desktop/README.md+++ b/desktop/README.md@@ -7,6 +7,10 @@ planned and its runner is unexercised. Embedded harness viewers currently requir## Development+For workspace dialog work, follow the+[terminal dialog design system](design/terminal-dialogs.md): fixed cells, plain+text, and one-line selection, using Cmd-N and Cmd-O as references.+Install a compatible Flutter SDK, then run the project from this directory(`desktop/` in the monorepo):diff --git a/desktop/design/bios-setup-screen-handoff.md b/desktop/design/bios-setup-screen-handoff.mdindex c29e87d3c..78175614d 100644--- a/desktop/design/bios-setup-screen-handoff.md+++ b/desktop/design/bios-setup-screen-handoff.md@@ -1,5 +1,9 @@# New Harness setup and minimal Open Harness picker — handoff+For current dialog presentation, follow the+[terminal dialog design system](terminal-dialogs.md). The 2026-09-24 review+supersedes this handoff's older logo, selection, spacing, and color directions.+Branch: `feat/centered-new-harness-palette`. Updated 2026-09-23.## Latest review directiondiff --git a/desktop/design/images/terminal-open-harness.png b/desktop/design/images/terminal-open-harness.pngnew file mode 100644index 000000000..57d041c05Binary files /dev/null and b/desktop/design/images/terminal-open-harness.png differdiff --git a/desktop/design/new-harness-entry-rules.md b/desktop/design/new-harness-entry-rules.mdindex 7f57793c7..0dfcc5bb0 100644--- a/desktop/design/new-harness-entry-rules.md+++ b/desktop/design/new-harness-entry-rules.md@@ -1,5 +1,8 @@# New Harness entry rules+Presentation follows the [terminal dialog design system](terminal-dialogs.md).+Use that guide for current visuals; this document owns entry and launch behavior.+Startup and Cmd-T show the same quiet welcome page. Cmd-T creates a blank tab;Escape leaves that tab open. The command dock opens only after an explicitCmd-N, Cmd-O, or Cmd-P action. Start Harness submits the reviewed draft;diff --git a/desktop/design/super-terminal-interaction.md b/desktop/design/super-terminal-interaction.mdindex 8e6fe32f3..b423f286a 100644--- a/desktop/design/super-terminal-interaction.md+++ b/desktop/design/super-terminal-interaction.md@@ -1,5 +1,9 @@# Terminal prompts in OpenHarness+For current dialog presentation, follow the+[terminal dialog design system](terminal-dialogs.md). It supersedes the older+visual descriptions below, including dock placement and chrome.+The terminal is the workspace. Search and creation are temporary prompts overit, using the same monospace family, compact text rows, a thin border, and avisible cursor. No backdrop dims the running agents. No permanent status bardiff --git a/desktop/design/terminal-dialogs.md b/desktop/design/terminal-dialogs.mdnew file mode 100644index 000000000..c8c0cfa93--- /dev/null+++ b/desktop/design/terminal-dialogs.md@@ -0,0 +1,151 @@+# Terminal dialog design system++**Fixed cells. Plain text. One-line selection.**++Harness's terminal-workspace dialogs should feel like part of the terminal.+This is the agreed design direction from the Cmd-N and Cmd-O review on+2026-09-24. Apply it to new and revised workspace pickers, forms, confirmations,+and their previews. It is the current source of truth for their presentation,+including where older design handoffs describe different visuals.++Cmd-N (`NewHarnessForm`) and Cmd-O (`SwarmSearchResults` in its terminal setup+layout) are the implementation references. Full Settings pages and embedded+viewers keep their own component systems.++++The fixture above shows the terminal grid, plain-text rows, and one-line+selection. Live surfaces use the user's selected terminal font and palette.++## Lay out a character grid++Measure the selected terminal font through `terminalCellSizeOf(context)` in+[`terminal_text.dart`](../lib/terminal/terminal_text.dart). Its width is one+character column; its height is one text row. Use this shared measurement in+both layout and scrolling calculations.++- Express horizontal margins, gutters, column widths, and gaps in whole cells.+- Express vertical spacing in whole text rows. A title is one row; its context+ or description is the next row; separation is a blank row.+- Align the input text, result titles, and context lines to the same column.+ Align form labels and values in consistent columns.+- Keep single-line choices to one row. Truncate long labels within their+ column; preserve the full value for accessibility or inspection.+- On narrow windows, reduce columns or change the pane arrangement. Keep the+ measured font and row spacing rather than shrinking text to fit.++Do not approximate a cell as `fontSize * .6`, copy pixel padding from a+screenshot, or let Material control minimum heights determine the grid.++```dart+final cell = terminalCellSizeOf(context);+final gutter = cell.width * 2;+final lineHeight = cell.height;+```++## Highlight one line++The selection background spans the selected name/value line and is exactly one+terminal row tall. Descriptions, metadata, previews, and blank spacing remain+outside it. Only the list or field that owns keyboard navigation shows the+active highlight. Moving selection must not shift any text or columns.++Click targets may include a result's context line. Their size must not enlarge+the visible selection. Keep semantic selection, focus, and enabled state even+when using custom row widgets.++## Use text for the controls++- No provider logos, avatars, decorative emoji, image assets, or icon-font+ glyphs in dialog chrome. Write `Codex`, `Claude`, or the harness name.+- Use plain markers when useful: `>` for the search prompt, `@` for a machine,+ `/` for a project, and `git:` for a branch. Keep identity readable as text.+- Boolean controls use `[x]` and `[ ]`; Enter and Space toggle them.+- Actions use concise text, such as `[ New Harness ]`. Shortcut hints are text+ beside the action, resolved from the live keymap.+- Omit redundant heading rows such as “New Tab” or “New Pane.” Add a label or+ explanation only when it helps someone understand a choice or state.+- Preserve user content, including Unicode. The restriction on decorative+ graphics applies to our controls, not to the text someone supplied.++For example, a result is two text lines followed by one blank row:++```text+> Find a harness...++ Checkout retries 5m+ Codex @ M2 / storefront git: fix/retry++ Search experience 1h+ Claude @ M2 / storefront git: main+```++The highlight covers only the selected title line.++## Inherit the real terminal's appearance++Use `terminalContentStyle()` for all dialog text: input, labels, values,+metadata, timestamps, actions, and previews. This preserves the terminal's+font family, fallback fonts, size, line height, and zero added letter/word+spacing. Do not substitute the general app UI type scale or hardcode a font+and size in an individual dialog.++Resolve colors through `terminalThemeFor(AppTheme.palette.value,+terminalThemeStore.value)` from+[`terminal_theme.dart`](../lib/terminal/terminal_theme.dart). Use its background,+foreground, cursor, selection, and semantic colors. Derive muted text from its+foreground; hardcoded white fails on other terminal schemes.++Use the same thin frame as an active pane:+`terminalPaneBorder(focused: true)` and `kTerminalCornerRadius` from+[`box_chrome.dart`](../lib/widgets/box_chrome.dart). Keep the surface flat, with+no elevated cards, pill controls, or decorative shadows inside it.++Search is one unfilled, borderless text line with a block caret one measured+cell wide. Its prompt occupies the shared gutter. Previews use the same text+metrics and blank-row spacing; warnings are readable text in semantic colors.++Open dialogs must follow live terminal font and theme changes while preserving+the input controller, query, selection, focus, and scroll state. Wire the font,+palette, and terminal-theme dependencies as the reference dialogs do. Settings+come from Harness's own Terminal preferences, not Apple Terminal or iTerm.++## Keep the terminal interaction++Arrows navigate the active choices; Enter accepts the current choice; Escape+goes back or dismisses according to the existing workflow. An editor still+accepts ordinary text, including `j` and `k`. Preserve composition, paste,+readline editing, remapped shortcuts, and mouse access.++Opening, searching, previewing, and cancelling must not send input to an agent,+start a process, or resize/recreate the underlying terminal. Return focus to the+workspace on dismissal. Search navigation should keep typing focus in its+editor, and a stationary pointer must not steal the keyboard highlight.++Keep lists virtualized and retain cached row controls. Arrow movement updates+the old and new highlights; it should not rebuild the editor or whole catalog.+Calculate reveal and paging from the actual measured item extent.++## Review a dialog change++Check the result with the user's terminal font and colors, an alternate scheme,+enlarged text, and a narrow window. Look for a one-line highlight, aligned+columns, intact text, plain controls, and no layout jumps. Exercise typing,+selection, acceptance, dismissal, scrolling, and focus restoration. Check live+font/theme changes while the dialog is open.++Reuse the relevant existing checks:++- [`new_harness_grid_test.dart`](../test/new_harness_grid_test.dart): row and+ column alignment, selection ownership, and scaling.+- [`open_picker_rendering_test.dart`](../test/open_picker_rendering_test.dart):+ pane/dialog appearance, one-line selection, no logos, and virtualized traversal.+- [`swarm_search_render_test.dart`](../test/swarm_search_render_test.dart):+ cached rows, query updates, theme changes, and focus.+- [`swarm_search_preview_test.dart`](../test/swarm_search_preview_test.dart):+ preview navigation and narrow layouts.+- [`keymap_runtime_test.dart`](../test/keymap_runtime_test.dart): shortcut+ routing and focus ownership.++When checking a native build, restart into the rebuilt app before judging the+result. An existing process does not pick up a new build automatically.diff --git a/desktop/design/terminal-prompt-styling.md b/desktop/design/terminal-prompt-styling.mdindex 8ad6b779c..788c6a775 100644--- a/desktop/design/terminal-prompt-styling.md+++ b/desktop/design/terminal-prompt-styling.md@@ -1,5 +1,11 @@# Prompt themes and workspace styling+For the current top bar and Customize Harness → Status, follow+[Workspace status bar](workspace-status-bar.md). It replaces the pane-header+choices described below with Standard, Robbyrussell, Pure, and Starship text+formats. The notes below describe the older `PromptContextView` surfaces;+terminal dialogs follow [the terminal dialog design system](terminal-dialogs.md).+The user's reference is an Agnoster-style shell prompt. The goal is familiar,compact context and fast keyboard interaction, with appearance choices thatcan be previewed before returning to work.diff --git a/desktop/design/workspace-status-bar.md b/desktop/design/workspace-status-bar.mdnew file mode 100644index 000000000..88211f0b1--- /dev/null+++ b/desktop/design/workspace-status-bar.md@@ -0,0 +1,117 @@+# Workspace status bar++One shared status line, using the terminal font and measured character cells.+Follow the [terminal dialog design system](terminal-dialogs.md).++```text+1:api 2:web 3:blender + OpenAI M2:autonomous-harness (main)+```++## Tabs on the left++Each tab shows its number and a compact name. A user-entered name always wins:+once renamed, keep it across pane changes, closing/reopening, and saved layout+restores. Use automatic naming only when `nameIsCustom` is false. Custom-named+tabs do not vote in the automatic-name comparison. Count independent+harness panes once per agent; dependent viewers do not vote. Consider harness+type (`code`, `blender`, etc.), project name, and machine name. Choose the most+widely shared trait in that tab. Among equally shared traits, prefer the name+least repeated in other tabs; otherwise prefer type, then project, then machine.+Ties within one trait use pane order. Focus does not affect the name.++This keeps `blender` useful beside coding tabs, uses project names when all work+is code, and uses machine names for the same project on different computers.+Tabs with identical contents can still share a name; their numbers distinguish+them. Preserve the full name for inspection when its visible label is truncated.++Center the text with one cell of padding on each side. Cap long labels at 24+cells and scroll overflow, revealing the selected tab on keyboard navigation.+There is no close button or reserved close-button space. Cmd-W closes the active+tab; preserve remapped shortcuts, native menu access, and middle-click closing.+Preserve reorder, rename, keyboard focus, and terminal sessions.++Tab labels, status text, and pane titles use the selected terminal font, point+size, and regular weight. Pane titles must not use the smaller `monoLabel` UI+style. As in the terminal renderer, do not apply a second UI text-scale factor+to pane titles.++## Pane controls++Keep three muted ASCII controls at the right of a harness pane: `-` closes only+that view, `[]` toggles zoom, and `x` stops the harness after confirmation. Each+control occupies two character columns. Use the terminal font and palette,+plain text, and a subtle hover/focus fill. Retain descriptive tooltips and+keyboard/accessibility labels; never rely on the symbols alone.++Restart Harness and Share Harness belong in File. Fork remains available in+command search. Viewer and message-composer toggles belong in View and command+search. These actions apply to the focused pane; sharing and viewer visibility+follow a dependent viewer's owner.++## Focused context on the right++Show provider or selected model, `machine:project`, then `(branch)` when known.+Use the shared `AgentProject.label` rule: at a Git root, prefer the remote repo's+name, falling back to the local repo name; in a repo subfolder, use that folder's+name; outside Git, use the ordinary folder name. A worktree follows exactly the+same rule. Its generated path and `[worktree]` marker do not belong in the bar.+Keep the full actual path in the tooltip and accessibility detail.++A focused viewer shows its owning harness's context. Omit absent project or Git+metadata; detached commits say `detached:<commit>`. Clicking the context opens+the harness's existing model picker when supported. Clear it for an empty tab.++Customize Harness → Status offers five saved themes with a colored preview of+the same sample pane beneath each choice. Selection covers only the name row.+The selected theme also previews PR status. All choices inherit the terminal+font, cell size, and ANSI palette; controls keep the plain terminal design.++| Theme | Treatment |+| --- | --- |+| Standard (default) | Foreground provider, cyan `machine:project`, green `(branch)` |+| Robbyrussell | Green arrow, cyan project, blue `git:(` with red branch |+| Pure | Blue project, muted machine/branch, magenta prompt mark |+| Agnoster | Joined black context, blue project, and green branch segments |+| Powerlevel10k Rainbow | Separate light provider, yellow-on-black machine, blue project, and green branch segments |++These are one-line visual adaptations, not installed shell themes. Powerline+separators are drawn one-cell shapes and do not require patched fonts. Prompt+marks and segment colors are decorative; they never invent dirty, ahead/behind,+privilege, or exit-status readings. Standard keeps familiar host/directory+notation; Zsh's actual stock prompt is `%m%# ` (host and prompt character).++The rightmost PR label belongs to the focused harness, including when its viewer+has focus. Display `PR #298 · Merged` (or Draft/Open/Closed), with a separate link+to that PR. Plain themes leave one text cell before the label. Segmented themes+connect it directly to the preceding arrow, making one continuous bar while+retaining separate model-picker and PR click targets. The selected-theme preview+shows that same joined line. State colors come from the terminal palette:+muted for Draft, green for Open, magenta for Merged, and red for Closed. Turning+Color off applies a monochrome treatment to context and PR together.++Read PR status through the owning machine's existing `git_pull_request` RPC.+Refresh once per minute while focused, reuse recent results across focus+switches, and discard stale replies after a pane, branch, or project change.+Unknown, absent, or inaccessible PRs have no label. Never display a previous+pane's PR while waiting for the newly focused one. Compact pane headers do not+also poll or display PR status.++References: [Zsh prompt parameters](https://zsh.sourceforge.io/Doc/Release/Parameters.html),+[Oh My Zsh themes](https://github.com/ohmyzsh/ohmyzsh/wiki/Themes),+[Robbyrussell source](https://github.com/ohmyzsh/ohmyzsh/blob/master/themes/robbyrussell.zsh-theme),+[Pure](https://github.com/sindresorhus/pure),+[Agnoster](https://github.com/agnoster/agnoster-zsh-theme), and+[Powerlevel10k](https://github.com/romkatv/powerlevel10k).++Pane headers keep task identity and controls. Machines, Models, Harnesses, and+the Store remain reachable from native menus and commands. Leave a window drag+area between tabs and context and prevent overlap in narrow windows.++Data rules live in `lib/state/workspace_status.dart`; prompt formatting lives in+`lib/shared/theme/status_line_style.dart`. Flutter draws the fallback bar in+`SwarmScreen`; macOS draws `SwarmTabStrip` in `macos/Runner/SwarmTitlebar.swift`.+Both use the same names, formatted context, resolved text/color segments, and+preferences. `WorkspacePullRequest` owns focused PR state; the native and Flutter+bars receive the same validated label and URL. Checks live in+`workspace_status_test.dart`, `workspace_pull_request_test.dart`,+`status_line_test.dart`, and `tool/swarm_titlebar_checks.swift`.diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dartindex ab7d405ed..2430ee233 100644--- a/desktop/lib/core/models.dart+++ b/desktop/lib/core/models.dart@@ -940,14 +940,23 @@ class AgentProject {final bool branchPending;/// The folder as the person chose it: inside a Git checkout, a subfolder- /// shows as itself and the checkout's root as its repository ([name]), even+ /// shows as itself and the checkout's root as its remote repository name+ /// (falling back to [name]), even/// when the checkout is a temporary worktree. Outside Git it is [name], the/// folder itself. The branch beside it is the repository's.String get label {final checkout = root;if (checkout == null) return name;String trimmed(String path) => path.replaceFirst(RegExp(r'[/\\]+$'), '');- if (trimmed(checkout) == trimmed(cwd)) return name;+ if (trimmed(checkout) == trimmed(cwd)) {+ final repository = remote == null+ ? ''+ : trimmed(remote!)+ .split('/')+ .last+ .replaceFirst(RegExp(r'\.git$', caseSensitive: false), '');+ return repository.isEmpty ? name : repository;+ }return cwd.split(RegExp(r'[/\\]')).where((part) => part.isNotEmpty)diff --git a/desktop/lib/core/pull_request_status.dart b/desktop/lib/core/pull_request_status.dartnew file mode 100644index 000000000..f1dd74155--- /dev/null+++ b/desktop/lib/core/pull_request_status.dart@@ -0,0 +1,27 @@+/// A PR reported by the owning machine. Only validated GitHub PR URLs become+/// clickable; missing access or a repository without a PR has no badge.+class PullRequestStatus {+ const PullRequestStatus(this.number, this.state, this.url);+ final int number;+ final String state;+ final Uri url;+ String get label => 'PR #$number · $state';++ static PullRequestStatus? fromResult(Map<String, dynamic>? result) {+ final number = result?['number'];+ final state = result?['state'];+ final url = Uri.tryParse(result?['url'] is String ? result!['url'] : '');+ if (result?['status'] != 'found' ||+ number is! int ||+ number <= 0 ||+ state is! String ||+ !const ['Draft', 'Open', 'Merged', 'Closed'].contains(state) ||+ url?.scheme != 'https' ||+ url?.host != 'github.com' ||+ url!.userInfo.isNotEmpty ||+ !url.path.endsWith('/pull/$number')) {+ return null;+ }+ return PullRequestStatus(number, state, url);+ }+}diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex f4dab3069..165b7b9b4 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -8,6 +8,8 @@ import 'package:flutter/foundation.dart' show listEquals;import 'package:flutter/gestures.dart';import 'package:flutter/material.dart';import 'package:flutter/services.dart';+import 'package:url_launcher/url_launcher.dart';+import 'package:xterm/xterm.dart' show TerminalTheme;import '../analytics/analytics.dart';import '../core/desktop_window.dart';@@ -19,6 +21,9 @@ import '../models/models_panel.dart';import '../settings/settings_screen.dart';import '../settings/settings_section.dart';import '../shared/theme/app_theme.dart' as grid;+import '../sharing/share_harness_dialog.dart';+import '../shared/theme/appearance_prefs_store.dart';+import '../shared/theme/status_line_style.dart';import '../shortcuts/app_shortcuts.dart';import '../core/models.dart';import '../shortcuts/app_keymap.dart';@@ -41,16 +46,19 @@ import '../state/swarm_catalog.dart';import '../state/swarm_navigation.dart';import '../state/swarm_search.dart';import '../state/swarm.dart';+import '../state/workspace_status.dart';+import '../state/workspace_pull_request.dart';import '../state/terminal_pane.dart';import '../widgets/transient_menus.dart';import '../widgets/layout_palette.dart';import '../widgets/move_pane_palette.dart';import '../widgets/engine_identity.dart';+import '../widgets/grid_model_picker.dart';+import '../widgets/status_line.dart';import '../store/store_mark.dart';import '../store/store_screen.dart';import '../widgets/harness_start_page.dart';import '../widgets/machines_panel.dart';-import '../widgets/toolbar_icon.dart';import '../state/toolbar_notices.dart';import '../widgets/machine_actions.dart';import '../widgets/rename_agent_dialog.dart';@@ -72,7 +80,6 @@ import '../widgets/swarm_dialogs.dart';import '../widgets/swarm_search_input.dart';import '../widgets/swarm_switcher.dart';import '../widgets/swarm_wallpaper.dart';-import '../widgets/swarm_icon.dart';import '../widgets/task_palette.dart';import '../state/command_bar.dart';import '../state/command_bar_catalog.dart';@@ -149,7 +156,9 @@ class _SwarmScreenState extends State<SwarmScreen>StreamSubscription<SpokenTaskRequest>? _spokenTasks;StreamSubscription<void>? _modelsRequests;final _shellFocus = FocusNode(debugLabel: 'Swarm shell');- final _sessionsButton = GlobalKey();+ final _paneContextAnchor = GlobalKey();+ final _focusedModel = GridModelPickerController();+ late final WorkspacePullRequest _pullRequest;MachinesPanelHandle? _machinesPanel;final _toolbarNotices = ToolbarNotices();late final _onboarding =@@ -194,7 +203,8 @@ class _SwarmScreenState extends State<SwarmScreen>final _searchText = TextEditingController();final _searchFocus = FocusNode(debugLabel: 'Find a harness');final _tabScroll = ScrollController();- ({String activeId, List<String> order, double viewport})? _tabGeometry;+ ({String activeId, List<String> order, double viewport, List<double> widths})?+ _tabGeometry;bool _tabRevealScheduled = false;SwarmSearchController? _search;OverlayEntry? _searchOverlay;@@ -255,6 +265,7 @@ class _SwarmScreenState extends State<SwarmScreen>@overridevoid initState() {super.initState();+ _pullRequest = WorkspacePullRequest(app)..addListener(_statusPrefsChanged);_keymap.addListener(_keymapChanged);app.hasNavigationRail = false;app.railFocused = false;@@ -296,6 +307,8 @@ class _SwarmScreenState extends State<SwarmScreen>FocusManager.instance.addListener(_restoreEmptyFocus);FocusManager.instance.addListener(_syncKeyContext);grid.AppTheme.palette.addListener(_paletteChanged);+ terminalThemeStore.addListener(_paletteChanged);+ appearancePrefsStore.addListener(_statusPrefsChanged);terminalFontStore.addListener(_fontChanged);unawaited(_projects.load());unawaited(_navigation.load());@@ -377,6 +390,10 @@ class _SwarmScreenState extends State<SwarmScreen>_keymap.removeListener(_keymapChanged);_defaultKeymap.dispose();grid.AppTheme.palette.removeListener(_paletteChanged);+ terminalThemeStore.removeListener(_paletteChanged);+ appearancePrefsStore.removeListener(_statusPrefsChanged);+ _pullRequest.removeListener(_statusPrefsChanged);+ _pullRequest.dispose();terminalFontStore.removeListener(_fontChanged);app.removeListener(_recordNavigation);app.removeListener(_observeLearning);@@ -394,6 +411,7 @@ class _SwarmScreenState extends State<SwarmScreen>_navigation.dispose();_searchFocus.dispose();_searchText.dispose();+ _focusedModel.dispose();_tabScroll.dispose();_canvasFocus.dispose();_shellFocus.dispose();@@ -737,6 +755,45 @@ class _SwarmScreenState extends State<SwarmScreen>_paletteChanged();}+ void _statusPrefsChanged() {+ if (_native) _syncNative();+ if (mounted) setState(() {});+ }++ Map<String, Object> _nativeStatusLine(+ StatusLineParts parts,+ TerminalTheme theme, {+ int segmentOffset = 0,+ }) => {+ 'text': parts.text,+ 'segmented': parts.style.segmented,+ 'segments': [+ for (final part in statusLinePaintSegments(+ parts,+ theme,+ color: appearancePrefsStore.value.prompt.color,+ segmentOffset: segmentOffset,+ ))+ part.toJson(),+ ],+ };++ Future<void> _openFocusedPullRequest(String? expectedUrl) async {+ final pr = _pullRequest.value;+ if (pr == null || expectedUrl != pr.url.toString()) return;+ var opened = false;+ try {+ opened = await launchUrl(pr.url, mode: LaunchMode.externalApplication);+ } catch (_) {+ /* Show failure below. */+ }+ if (!opened && mounted) {+ ScaffoldMessenger.maybeOf(+ context,+ )?.showSnackBar(const SnackBar(content: Text('Could not open GitHub.')));+ }+ }+void _paletteChanged() {_machinesPanel?.rebuild();_searchOverlay?.markNeedsBuild();@@ -769,13 +826,57 @@ class _SwarmScreenState extends State<SwarmScreen>void _syncNative() {_syncMachines();+ final focused = WorkspacePaneContext.focused(app);+ final prefs = appearancePrefsStore.value.prompt;+ final parts = focused?.format(prefs);+ final names = workspaceTabNames(app);+ final terminalTheme = terminalThemeFor(+ grid.AppTheme.palette.value,+ terminalThemeStore.value,+ );final payload = {'enabled': _routeIsCurrent && !_dialogOpen && !_spokenPaletteOpen,'activeId': app.activeSwarmId,'palette': grid.AppTheme.palette.value.nativeColors,+ 'terminalStyle': {+ 'family': terminalFontStore.value.fontFamily,+ 'fallback': terminalFontStore.value.fontFamilyFallback,+ 'size': terminalFontStore.size,+ 'foreground': terminalTheme.foreground.toARGB32(),+ 'selection': terminalTheme.selection.toARGB32(),+ },+ 'focusedContext': focused == null+ ? null+ : {+ ..._nativeStatusLine(parts!, terminalTheme),+ 'detail': focused.detail,+ 'canSelectModel': _canSelectFocusedModel(focused),+ },+ 'pullRequest': _pullRequest.value == null+ ? null+ : {+ ..._nativeStatusLine(+ pullRequestStatusLineParts(+ number: _pullRequest.value!.number,+ state: _pullRequest.value!.state,+ style: prefs.statusStyle,+ ),+ terminalTheme,+ segmentOffset: parts?.segments.length ?? 0,+ ),+ 'url': _pullRequest.value!.url.toString(),+ 'detail': '${_pullRequest.value!.label} — Open on GitHub',+ 'canSelectModel': true,+ },'canReopen': app.canReopenLastClosed,'canFind': _canFindTerminal,'canClosePane': app.focusedPane != null,+ 'paneActions': {+ 'restartAgent': _canExecuteCommand('agent.restart'),+ 'shareAgent': _canExecuteCommand('agent.share'),+ 'toggleViewer': _canExecuteCommand('pane.toggle_viewer'),+ 'toggleComposer': _canExecuteCommand('pane.toggle_composer'),+ },'canGoBack': _navigation.canGoBack(app),'canGoForward': _navigation.canGoForward(app),'closedHistory': [@@ -838,6 +939,7 @@ class _SwarmScreenState extends State<SwarmScreen>{'id': swarm.id,'name': swarm.name,+ 'label': '${app.swarms.indexOf(swarm) + 1}:${names[swarm.id]}','kind': swarm.kind,'agentCount': _tabAgents(swarm).length,'engine': swarm.isStore ? 'store' : _tabEngine(swarm),@@ -1007,6 +1109,9 @@ class _SwarmScreenState extends State<SwarmScreen>'newTerminal' => 'terminal.new','cloneAgent' => 'agent.clone','restartAgent' => 'agent.restart',+ 'shareAgent' => 'agent.share',+ 'toggleViewer' => 'pane.toggle_viewer',+ 'toggleComposer' => 'pane.toggle_composer',_ => null,};if (nativeCommand != null || call.method == 'searchCommand') {@@ -1071,6 +1176,13 @@ class _SwarmScreenState extends State<SwarmScreen>// event any Flutter overlay can see itself.dismissTransientMenus();switch (call.method) {+ case 'focusedModel':+ final focused = WorkspacePaneContext.focused(app);+ if (focused != null && _canSelectFocusedModel(focused)) {+ _focusedModel.open();+ }+ case 'focusedPullRequest':+ await _openFocusedPullRequest(args['url'] as String?);case 'store':_openStore();case 'new':@@ -1115,6 +1227,14 @@ class _SwarmScreenState extends State<SwarmScreen>unawaited(_cloneAgent());case 'restartAgent':unawaited(_restartAgent());+ case 'shareAgent':+ if (_canExecuteCommand('agent.share')) unawaited(_shareAgent());+ case 'toggleViewer':+ if (_canExecuteCommand('pane.toggle_viewer')) _toggleFocusedViewer();+ case 'toggleComposer':+ if (_canExecuteCommand('pane.toggle_composer')) {+ app.toggleComposer(app.focusedPaneId!);+ }case 'runLocalModel':_toggleModels(initialTab: ModelsTab.local);case 'splitRight':@@ -1231,6 +1351,9 @@ class _SwarmScreenState extends State<SwarmScreen>'newTerminal','cloneAgent','restartAgent',+ 'shareAgent',+ 'toggleViewer',+ 'toggleComposer','runLocalModel','manageMachines','machineList',@@ -1283,7 +1406,7 @@ class _SwarmScreenState extends State<SwarmScreen>if (swarm == null) return;final name = await showSwarmRenameDialog(context,- swarm.name,+ workspaceTabNames(app)[id] ?? swarm.name,keymap: _keymap,);if (name != null) app.renameSwarm(id, name);@@ -1370,6 +1493,30 @@ class _SwarmScreenState extends State<SwarmScreen>keymap: _keymap,);});+ Future<void> _shareAgent() => _dialog(() async {+ final focused = WorkspacePaneContext.focused(app);+ final agent = focused?.agent;+ if (focused == null ||+ agent == null ||+ app.stateOf(focused.pane.machineId)?.machine.isShared != false) {+ return;+ }+ await showShareHarnessDialog(+ context,+ app,+ focused.pane.machineId,+ agent.id,+ agent.displayName,+ );+ });++ void _toggleFocusedViewer() {+ final focused = WorkspacePaneContext.focused(app);+ if (focused?.agentId case final id?) {+ unawaited(app.toggleViewerPane(focused!.pane.machineId, id));+ }+ }+Future<void> _customize() => _dialog(() => showHarnessCustomizePane(context));Future<void> _settings([SettingsSection? section]) => _dialog(@@ -1782,10 +1929,7 @@ class _SwarmScreenState extends State<SwarmScreen>app.cancelSwarmDraft(target);}},- // The popup is the terminal's own colour, so the- // screen behind it is dimmed rather than competed- // with — that, and the light shadow, are what carry- // the separation a different fill used to.+ // Keep the workspace quiet behind the focused pane.child: ColoredBox(color: Colors.black.withValues(alpha: .94),),@@ -2469,7 +2613,7 @@ class _SwarmScreenState extends State<SwarmScreen>);}} else {- final button = _sessionsButton.currentContext?.findRenderObject();+ final button = _paneContextAnchor.currentContext?.findRenderObject();if (button is RenderBox && button.hasSize) {target = button.localToGlobal(button.size.center(Offset.zero));}@@ -2674,6 +2818,11 @@ class _SwarmScreenState extends State<SwarmScreen>Widget _buildSearchOverlay(BuildContext context) {final search = _search!;+ final cell = terminalCellSizeOf(context);+ final terminalTheme = terminalThemeFor(+ grid.AppTheme.palette.value,+ terminalThemeStore.value,+ );// Results sit above a stable input line in the workspace command dock.// The input is visually below results, but Tab still starts at the first// result rather than a cached, offscreen ListView row below the input.@@ -2682,13 +2831,15 @@ class _SwarmScreenState extends State<SwarmScreen>final panel = Material(key: const ValueKey('swarm-search-results'),elevation: 0,- color: terminalThemeFor(- grid.AppTheme.palette.value,- terminalThemeStore.value,- ).background,+ color: terminalTheme.background,surfaceTintColor: Colors.transparent,+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(kTerminalCornerRadius),+ side: terminalPaneBorder(focused: true),+ ),+ clipBehavior: Clip.antiAlias,child: DefaultTextStyle.merge(- style: terminalContentStyle(color: Colors.white),+ style: terminalContentStyle(color: terminalTheme.foreground),child: FocusTraversalGroup(policy: OrderedTraversalPolicy(),// Fills its frame, as fzf does: the list takes every row the box@@ -2705,10 +2856,21 @@ class _SwarmScreenState extends State<SwarmScreen>children: [if (search.canGoBack || search.isGroupMode)Padding(- padding: const EdgeInsets.fromLTRB(18, 12, 18, 0),+ padding: EdgeInsets.fromLTRB(+ cell.width * 4,+ cell.height,+ cell.width * 2,+ 0,+ ),child: Text(search.title,- style: terminalContentStyle(color: kBoxFaint),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: terminalContentStyle(+ color: terminalTheme.foreground.withValues(+ alpha: .54,+ ),+ ),),),Semantics(@@ -2724,7 +2886,6 @@ class _SwarmScreenState extends State<SwarmScreen>onClose: _dismissSearch,onChanged: search.setQuery,onOpen: _focusSearch,- height: 44 * terminalTextScaleOf(context),terminal: true,bios: true,prompt: '>',@@ -2830,7 +2991,14 @@ class _SwarmScreenState extends State<SwarmScreen>namesRoute: true,explicitChildNodes: true,label: search.title,- child: panel,+ child: TextSelectionTheme(+ data: TextSelectionThemeData(+ cursorColor: terminalTheme.cursor,+ selectionColor: terminalTheme.selection,+ selectionHandleColor: terminalTheme.cursor,+ ),+ child: panel,+ ),);return KeymapProvider(keymap: _keymap,@@ -2848,9 +3016,8 @@ class _SwarmScreenState extends State<SwarmScreen>);return Stack(children: [- // A click outside still closes it; it just no longer dims. To a- // screen reader it IS modal: without the block, VoiceOver walks- // straight out of the box into the panes behind it.+ // A click outside closes it. Block the dimmed workspace from+ // VoiceOver while the dialog owns the keyboard.Positioned.fill(child: BlockSemantics(child: GestureDetector(@@ -3087,12 +3254,18 @@ class _SwarmScreenState extends State<SwarmScreen>'agent.rename': () => _editAgent(),'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);+ },// `agent.restart` and `agent.clone` come from `_actionHandlers` above:// both carry a ShortcutAction, so the loop already binds them.'machine.link': _openMachines,'machines.manage': _manageMachines,'machines.list': _openMachines,'models.list': _toggleModels,+ 'harnesses.list': _toggleSessions,'project.add': _addProject,'keyboard.open_config': () => openKeyboardConfig(context),'keyboard.quick_start': _startQuickStart,@@ -3113,6 +3286,25 @@ class _SwarmScreenState extends State<SwarmScreen>}if (id == 'keyboard.open_config') return _keymap.store != null;if (id == 'keyboard.pause_guide') return _learning.active;+ if (id == 'agent.share' || id == 'pane.toggle_viewer') {+ final focused = WorkspacePaneContext.focused(app);+ final agent = focused?.agent;+ return focused != null &&+ agent != null &&+ app.stateOf(focused.pane.machineId)?.machine.isShared == false &&+ (id == 'agent.share' ||+ agent.viewerUrl != null ||+ agent.viewerError != null);+ }+ if (id == 'pane.toggle_composer') {+ final pane = app.focusedPane;+ final machine = pane == null ? null : app.stateOf(pane.machineId);+ return pane?.session != null &&+ machine != null &&+ !machine.isLocalMachine &&+ !machine.machine.isShared &&+ !isTerminalEngine(pane!.session!.engineId);+ }if (id == 'keyboard.quick_start' ||id == 'keyboard.practice' ||id == 'app.onboarding_review') {@@ -3216,6 +3408,11 @@ class _SwarmScreenState extends State<SwarmScreen>),?mode('agent.new', 'New Harness', 'agent · machine · project'),?mode('app.store', 'Harness Store', 'Browse and install harnesses'),+ ?mode(+ 'harnesses.list',+ 'Harnesses',+ 'Manage running and paused harnesses',+ ),?mode('terminal.new', 'New terminal', 'A shell where you are'),?mode('agent.clone',@@ -3439,6 +3636,7 @@ class _SwarmScreenState extends State<SwarmScreen>backgroundColor: grid.AppPalette.swarmField,body: Column(children: [+ _focusedModelPicker(),if (!_native) _tabStrip(),if (_learning.active && app.viewer == null)WorkspaceQuickStart(@@ -3696,7 +3894,7 @@ class _SwarmScreenState extends State<SwarmScreen>);static const double _tabBarHeight = 40;- double _tabExtent = 188;+ List<double> _tabWidths = [];void _revealSelectedTab(double viewport) {final previous = _tabGeometry;@@ -3704,20 +3902,24 @@ class _SwarmScreenState extends State<SwarmScreen>if (previous != null &&previous.activeId == app.activeSwarmId &&previous.viewport == viewport &&- listEquals(previous.order, order)) {+ listEquals(previous.order, order) &&+ listEquals(previous.widths, _tabWidths)) {return;}_tabGeometry = (activeId: app.activeSwarmId,order: order,viewport: viewport,+ widths: List.of(_tabWidths),);final oldIndex = previous?.order.indexOf(previous.activeId) ?? -1;final wasVisible =_tabScroll.hasClients &&oldIndex >= 0 &&- (oldIndex + 1) * _tabExtent > _tabScroll.offset &&- oldIndex * _tabExtent < _tabScroll.offset + previous!.viewport;+ previous!.widths.take(oldIndex + 1).fold(0.0, (a, b) => a + b) >+ _tabScroll.offset &&+ previous.widths.take(oldIndex).fold(0.0, (a, b) => a + b) <+ _tabScroll.offset + previous.viewport;// A selected tab follows keyboard navigation and layout changes, but// background agent updates must not undo deliberate strip scrolling.if (previous != null &&@@ -3733,10 +3935,11 @@ class _SwarmScreenState extends State<SwarmScreen>final index = app.swarms.indexWhere((tab) => tab.id == app.activeSwarmId);if (index < 0) return;final position = _tabScroll.position;- final left = index * _tabExtent;- final right = left + _tabExtent;+ final left = _tabWidths.take(index).fold(0.0, (a, b) => a + b);+ final extent = _tabWidths[index];+ final right = left + extent;final offset =- left < position.pixels || _tabExtent > position.viewportDimension+ left < position.pixels || extent > position.viewportDimension? left: right > position.pixels + position.viewportDimension? right - position.viewportDimension@@ -3746,335 +3949,237 @@ class _SwarmScreenState extends State<SwarmScreen>});}- ButtonStyle _toolbarIconStyle(int notices) => ButtonStyle(- iconColor: WidgetStateProperty.resolveWith((states) {- if (notices > 0) return const Color(0xfff5f5f5);- if (states.contains(WidgetState.hovered) ||- states.contains(WidgetState.focused) ||- states.contains(WidgetState.pressed) ||- states.contains(WidgetState.selected)) {- return const Color(0xffd6d6d6);- }- return const Color(0xff999999);- }),- );+ bool _canSelectFocusedModel(WorkspacePaneContext data) {+ final machine = app.stateOf(data.pane.machineId);+ return data.agent != null &&+ data.agentId != null &&+ modelPickerSupports(data.engine) &&+ data.pane.session?.readOnly != true &&+ machine?.needsLink != true &&+ machine?.nodeOnline != false;+ }- Widget _toolbarBadge({- Key? key,- required int count,- required String label,- required Widget child,- OnboardingStep? step,- }) => Badge(- key: key,- isLabelVisible: count > 0,- backgroundColor: const Color(0xffcf4038),- textColor: Colors.white,- largeSize: 13,- alignment: Alignment.topRight,- label: Text(- count > 99 ? '99+' : '$count',- semanticsLabel: label,- style: const TextStyle(fontSize: 9, fontWeight: FontWeight.w600),- ),- child: step != null && _onboarding.showsDot(step)- ? Stack(- clipBehavior: Clip.none,- children: [- child,- Positioned(- right: -3,- top: count > 0 ? null : -3,- bottom: count > 0 ? -3 : null,- child: Semantics(- label: 'Suggested next step',- child: Container(- key: ValueKey('onboarding-${step.name}-dot'),- width: 6,- height: 6,- decoration: const BoxDecoration(- shape: BoxShape.circle,- color: Color(0xff99c2ed),- ),- ),- ),- ),- ],- )- : child,- );+ Widget _focusedModelPicker() {+ final data = WorkspacePaneContext.focused(app);+ if (data == null || !_canSelectFocusedModel(data)) {+ return const SizedBox.shrink();+ }+ final machineId = data.pane.machineId;+ final agentId = data.agentId!;+ return GridModelPicker(+ key: ValueKey(('workspace-model', machineId, agentId)),+ notifier: app,+ machineId: machineId,+ controller: _focusedModel,+ menuOnly: true,+ engineLabel: data.engine,+ currentModel: data.agent?.gridModel,+ webSearch: data.agent?.gridWebSearch,+ onSelected: (model) => unawaited(+ app.retargetAgentToGridModel(+ machineId,+ agentId,+ model.id,+ gridName: model.grid,+ ),+ ),+ onUseOwnLogin: () => unawaited(app.clearAgentGrid(machineId, agentId)),+ onRunLocalModel: () =>+ unawaited(app.runLocalModel(context, machineId: machineId)),+ );+ }Widget _tabStrip() => LayoutBuilder(builder: (context, constraints) {- final compactTools =- constraints.maxWidth < 650 * grid.appTextScaleOf(context);- return Container(- height: _tabBarHeight,+ final cell = terminalCellSizeOf(context);+ final theme = terminalThemeFor(+ grid.AppTheme.palette.value,+ terminalThemeStore.value,+ );+ final style = terminalContentStyle(color: theme.foreground);+ final names = workspaceTabNames(app);+ final labels = [+ for (var index = 0; index < app.swarms.length; index++)+ '${index + 1}:${names[app.swarms[index].id]}',+ ];+ final tabBudget = constraints.maxWidth * .45;+ _tabWidths = [+ for (final label in labels)+ math.min(+ math.min(label.characters.length + 2, 24) * cell.width,+ tabBudget,+ ),+ ];+ final total = _tabWidths.fold(0.0, (sum, width) => sum + width);+ final tabsWidth = math.min(total, tabBudget);+ final focused = WorkspacePaneContext.focused(app);+ final prefs = appearancePrefsStore.value.prompt;+ final parts = focused?.format(prefs);+ final pr = _pullRequest.value;+ final prParts = pr == null+ ? null+ : pullRequestStatusLineParts(+ number: pr.number,+ state: pr.state,+ style: prefs.statusStyle,+ );+ final joined =+ prefs.statusStyle.segmented &&+ parts != null &&+ parts.segments.isNotEmpty &&+ prParts != null;+ final prBackground = joined+ ? statusLinePaintSegments(+ prParts,+ theme,+ color: prefs.color,+ segmentOffset: parts.segments.length,+ ).first.background+ : null;+ final canSelectModel = focused != null && _canSelectFocusedModel(focused);+ _revealSelectedTab(tabsWidth);+ return Material(+ key: const ValueKey('workspace-status-bar'),color: grid.AppPalette.swarmTabBar,- child: Row(- children: [- Expanded(- child: LayoutBuilder(- builder: (context, constraints) {- _tabExtent = constraints.maxWidth.clamp(64, 188);- _revealSelectedTab(constraints.maxWidth);- return ReorderableListView.builder(- scrollController: _tabScroll,- itemExtent: _tabExtent,- scrollDirection: Axis.horizontal,- shrinkWrap: true,- buildDefaultDragHandles: false,- itemCount: app.swarms.length,- onReorderItem: (old, to) =>- app.reorderSwarm(app.swarms[old].id, to),- itemBuilder: (context, index) {- final swarm = app.swarms[index];- return ReorderableDragStartListener(- key: ValueKey(swarm.id),- index: index,- child: Listener(- // Middle-click closes the tab, as it does in every- // browser. On the UP, and only inside the tab it went- // down on: a press that slid off changed its mind.- onPointerDown: (event) {- _middleDownTab = event.buttons == kTertiaryButton- ? swarm.id- : null;- },- onPointerUp: (event) {- final armed = _middleDownTab;- _middleDownTab = null;- if (armed == swarm.id) {- unawaited(app.closeSwarm(swarm.id));- }- },- child: GestureDetector(- onDoubleTap: () => _rename(swarm.id),- child: _TabActionsReveal(- builder: (showClose) => Container(- width: _tabExtent - 2,- margin: const EdgeInsets.only(top: 4, right: 2),- decoration: ShapeDecoration(- color: app.activeSwarmId == swarm.id- ? grid.AppPalette.swarmField- : Colors.transparent,- shape: const TerminalTabBorder(),- ),- child: Row(- children: [- Expanded(- child: TextButton(- onPressed: () =>- app.selectSwarm(swarm.id),- style: TextButton.styleFrom(- shape: const RoundedRectangleBorder(- borderRadius: BorderRadius.all(- Radius.circular(- kTerminalCornerRadius,- ),- ),- ),- animationDuration: Duration.zero,- foregroundColor:- app.activeSwarmId == swarm.id- ? Colors.white- : Colors.white70,- ),- child: Row(- children: [- if (swarm.isStore)- StoreMark(- key: ValueKey(- 'tab-store:${swarm.id}',- ),- )- else if (_tabAgents(swarm).length ==- 1)- EngineMark(- key: ValueKey(- 'tab-engine:${swarm.id}',- ),- engine: _tabEngine(swarm),- size: 16,- )- else if (_tabAgents(swarm).length >- 1)- SwarmIcon(- key: ValueKey(- 'tab-group:${swarm.id}',- ),- size: 16,- color: Colors.white70,- )- else- const Icon(Icons.add, size: 16),- const SizedBox(width: 8),- Expanded(- child: Text(- swarm.name,- maxLines: 1,- overflow: TextOverflow.ellipsis,- // Like the native tabs.- style: grid.AppType.monoLabel(- color: Colors.white,- fontWeight: FontWeight.w400,- ),- ),- ),- ],- ),+ child: SizedBox(+ height: math.max(_tabBarHeight, cell.height * 2),+ child: Row(+ children: [+ SizedBox(width: cell.width),+ SizedBox(+ width: tabsWidth,+ child: ReorderableListView.builder(+ scrollController: _tabScroll,+ itemExtentBuilder: (index, _) => _tabWidths[index],+ scrollDirection: Axis.horizontal,+ shrinkWrap: true,+ buildDefaultDragHandles: false,+ itemCount: app.swarms.length,+ onReorderItem: (old, to) =>+ app.reorderSwarm(app.swarms[old].id, to),+ itemBuilder: (context, index) {+ final swarm = app.swarms[index];+ final selected = app.activeSwarmId == swarm.id;+ return ReorderableDragStartListener(+ key: ValueKey(swarm.id),+ index: index,+ child: Listener(+ onPointerDown: (event) {+ _middleDownTab = event.buttons == kTertiaryButton+ ? swarm.id+ : null;+ },+ onPointerUp: (event) {+ final armed = _middleDownTab;+ _middleDownTab = null;+ if (armed == swarm.id) {+ unawaited(app.closeSwarm(swarm.id));+ }+ },+ child: GestureDetector(+ onDoubleTap: () => _rename(swarm.id),+ child: Tooltip(+ message:+ '${swarm.name}\nClose Tab ${_keymap.hint('swarm.close') ?? ''}',+ child: Center(+ child: Container(+ height: cell.height,+ color: selected+ ? theme.selection+ : Colors.transparent,+ child: InkWell(+ onTap: () => app.selectSwarm(swarm.id),+ child: Semantics(+ selected: selected,+ button: true,+ label: '${labels[index]}: ${swarm.name}',+ child: Padding(+ padding: EdgeInsets.symmetric(+ horizontal: cell.width,),- ),- Opacity(- key: ValueKey('tab-close:${swarm.id}'),- opacity: showClose ? 1 : 0,- alwaysIncludeSemantics: true,- child: IconButton(- onPressed: () =>- app.closeSwarm(swarm.id),- icon: Icon(- Icons.close,- size: 13,- semanticLabel: 'Close ${swarm.name}',+ child: Center(+ child: Text(+ labels[index],+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ textAlign: TextAlign.center,+ style: style,),- constraints:- const BoxConstraints.tightFor(- width: 30,- height: 30,- ),- padding: EdgeInsets.zero,),),- ],+ ),),),),),),- );- },- );- },- ),- ),- IconButton(- key: const ValueKey('swarm-new-tab-button'),- onPressed: _newTab,- tooltip: 'New Tab ${_keymap.hint('swarm.new') ?? ''}'.trim(),- icon: const Icon(Icons.add, size: 18, semanticLabel: 'New Tab'),- ),- IconButton(- key: const ValueKey('swarm-machines-button'),- tooltip: 'Machines ${_keymap.hint('machines.list') ?? ''}'.trim(),- onPressed: _openMachines,- isSelected: _machinesPanel != null,- style: _toolbarIconStyle(_toolbarNotices.machineCount),- icon: _toolbarBadge(- key: const ValueKey('swarm-machines-badge'),- step: OnboardingStep.machines,- count: _toolbarNotices.machineCount,- label:- '${_toolbarNotices.machineCount} new ${_toolbarNotices.machineCount == 1 ? 'computer' : 'computers'} ready to connect',- child: const ToolbarIcon(name: 'Machines'),- ),- ),- IconButton(- key: const ValueKey('swarm-models-button'),- tooltip: 'Models ${_keymap.hint('models.list') ?? ''}'.trim(),- onPressed: _toggleModels,- isSelected: _modelsOverlay != null,- style: _toolbarIconStyle(_toolbarNotices.modelCount),- icon: _toolbarBadge(- key: const ValueKey('swarm-models-badge'),- step: OnboardingStep.models,- count: _toolbarNotices.modelCount,- label:- '${_toolbarNotices.modelCount} ${_toolbarNotices.modelCount == 1 ? 'model' : 'models'} ready to use',- child: const ToolbarIcon(name: 'Models'),+ ),+ );+ },+ ),),- ),- IconButton(- key: _sessionsButton,- tooltip: 'Harnesses',- onPressed: _toggleSessions,- isSelected: _sessionsOverlay != null,- style: _toolbarIconStyle(_unread),- icon: _toolbarBadge(- key: const ValueKey('swarm-unread-badge'),- step: OnboardingStep.harnesses,- count: _unread,- label:- '$_unread ${_unread == 1 ? 'harness has' : 'harnesses have'} news you have not seen',- child: const ToolbarIcon(name: 'Harnesses'),+ SizedBox(+ width: cell.width * 3,+ child: Tooltip(+ message: 'New Tab ${_keymap.hint('swarm.new') ?? ''}',+ child: InkWell(+ key: const ValueKey('swarm-new-tab-button'),+ onTap: _newTab,+ child: Text(+ '+',+ textAlign: TextAlign.center,+ semanticsLabel: 'New Tab',+ style: style,+ ),+ ),+ ),),- ),- const SizedBox(width: 6),- Tooltip(- message: 'Harness Store ${_keymap.hint('app.store') ?? ''}'- .trim(),- child: compactTools- ? IconButton(- key: const ValueKey('swarm-store-button'),- onPressed: _openStore,- icon: const StoreMark(),- )- : TextButton.icon(- key: const ValueKey('swarm-store-button'),- onPressed: _openStore,- style: TextButton.styleFrom(- foregroundColor: grid.AppPalette.swarmAccent,- backgroundColor: Color.alphaBlend(- grid.AppPalette.swarmAccent.withValues(alpha: 0.10),- grid.AppPalette.swarmField,- ),- overlayColor: grid.AppPalette.swarmAccent,- textStyle: grid.AppType.monoLabel(),- minimumSize: const Size(0, 28),- padding: const EdgeInsets.symmetric(horizontal: 12),- tapTargetSize: MaterialTapTargetSize.shrinkWrap,- shape: StadiumBorder(- side: BorderSide(- color: grid.AppPalette.swarmAccent.withValues(- alpha: 0.12,+ SizedBox(width: cell.width * 2),+ Expanded(+ child: Align(+ alignment: Alignment.centerRight,+ child: Tooltip(+ key: _paneContextAnchor,+ message: focused?.detail ?? '',+ child: InkWell(+ key: const ValueKey('workspace-pane-context'),+ onTap: canSelectModel ? _focusedModel.open : null,+ child: parts == null+ ? const SizedBox.shrink()+ : StatusLine(+ parts: parts,+ color: prefs.color,+ nextBackground: prBackground,),- ),- ),+ ),+ ),+ ),+ ),+ if (pr != null) ...[+ if (!joined) SizedBox(width: cell.width),+ ConstrainedBox(+ constraints: BoxConstraints(+ maxWidth: constraints.maxWidth * .28,+ ),+ child: Tooltip(+ message: '${pr.label} — Open on GitHub',+ child: InkWell(+ key: const ValueKey('workspace-pull-request'),+ onTap: () => _openFocusedPullRequest(pr.url.toString()),+ child: StatusLine(+ parts: prParts!,+ color: prefs.color,+ segmentOffset: parts?.segments.length ?? 0,),- icon: const StoreMark(),- label: const Text('Harness Store'),),- ),- const SizedBox(width: 6),- ],+ ),+ ),+ ],+ SizedBox(width: cell.width),+ ],+ ),),);},);}--/// Hovering or focusing one tab only rebuilds its own controls.-class _TabActionsReveal extends StatefulWidget {- const _TabActionsReveal({required this.builder});- final Widget Function(bool visible) builder;-- @override- State<_TabActionsReveal> createState() => _TabActionsRevealState();-}--class _TabActionsRevealState extends State<_TabActionsReveal> {- bool _hovered = false, _focused = false;-- @override- Widget build(BuildContext context) {- return MouseRegion(- onEnter: (_) => setState(() => _hovered = true),- onExit: (_) => setState(() => _hovered = false),- child: Focus(- canRequestFocus: false,- includeSemantics: false,- onFocusChange: (value) => setState(() => _focused = value),- child: widget.builder(_hovered || _focused),- ),- );- }-}diff --git a/desktop/lib/shared/theme/prompt_style.dart b/desktop/lib/shared/theme/prompt_style.dartindex 1f485caa7..99247f728 100644--- a/desktop/lib/shared/theme/prompt_style.dart+++ b/desktop/lib/shared/theme/prompt_style.dart@@ -1,5 +1,7 @@import 'package:flutter/foundation.dart';+import 'status_line_style.dart';+const kHarnessPromptMarker = '>_';enum PromptStyle {@@ -22,9 +24,11 @@ class PromptPrefs {this.machine = true,this.project = true,this.branch = true,+ this.statusStyle = StatusLineStyle.standard,});final PromptStyle style;+ final StatusLineStyle statusStyle;final bool color, machine, project, branch;PromptPrefs copyWith({@@ -33,12 +37,14 @@ class PromptPrefs {bool? machine,bool? project,bool? branch,+ StatusLineStyle? statusStyle,}) => PromptPrefs(style: style ?? this.style,color: color ?? this.color,machine: machine ?? this.machine,project: project ?? this.project,branch: branch ?? this.branch,+ statusStyle: statusStyle ?? this.statusStyle,);Map<String, Object> toJson() => {@@ -47,6 +53,7 @@ class PromptPrefs {'machine': machine,'project': project,'branch': branch,+ 'statusStyle': statusStyle.name,};factory PromptPrefs.fromJson(Object? json) {@@ -58,6 +65,7 @@ class PromptPrefs {machine: flag('machine'),project: flag('project'),branch: flag('branch'),+ statusStyle: StatusLineStyle.fromId(json['statusStyle']),);}@@ -65,13 +73,15 @@ class PromptPrefs {bool operator ==(Object other) =>other is PromptPrefs &&other.style == style &&+ other.statusStyle == statusStyle &&other.color == color &&other.machine == machine &&other.project == project &&other.branch == branch;@override- int get hashCode => Object.hash(style, color, machine, project, branch);+ int get hashCode =>+ Object.hash(style, statusStyle, color, machine, project, branch);}/// Identity supplied by the catalog, never inferred by parsing display text.diff --git a/desktop/lib/shared/theme/status_line_style.dart b/desktop/lib/shared/theme/status_line_style.dartnew file mode 100644index 000000000..4b9694eee--- /dev/null+++ b/desktop/lib/shared/theme/status_line_style.dart@@ -0,0 +1,221 @@+import 'package:flutter/painting.dart';+import 'package:xterm/xterm.dart';++/// One-line adaptations of shell prompts, using only known pane metadata.+enum StatusLineStyle {+ standard('Standard'),+ robbyrussell('Robbyrussell'),+ pure('Pure'),+ agnoster('Agnoster'),+ powerlevel10k('Powerlevel10k Rainbow');++ const StatusLineStyle(this.label);+ final String label;++ bool get segmented => this == agnoster || this == powerlevel10k;++ static StatusLineStyle fromId(Object? id) =>+ values.where((style) => style.name == id).firstOrNull ?? standard;+}++enum StatusLineTone {+ foreground,+ muted,+ black,+ white,+ blue,+ cyan,+ green,+ yellow,+ red,+ magenta,+}++class StatusLineSegment {+ const StatusLineSegment(+ this.text, {+ this.foreground = StatusLineTone.foreground,+ this.background,+ });+ final String text;+ final StatusLineTone foreground;+ final StatusLineTone? background;+}++class StatusLineParts {+ const StatusLineParts(this.style, this.segments);+ final StatusLineStyle style;+ final List<StatusLineSegment> segments;+ String get text =>+ segments.map((part) => part.text).join(style.segmented ? ' ' : '');+}++StatusLineParts statusLineParts({+ required String provider,+ required String machine,+ required String project,+ String? branch,+ StatusLineStyle style = StatusLineStyle.standard,+}) {+ final parts = <StatusLineSegment>[];+ void add(String text, StatusLineTone color, [StatusLineTone? background]) {+ if (text.isNotEmpty) {+ parts.add(+ StatusLineSegment(text, foreground: color, background: background),+ );+ }+ }++ void gap([String separator = ' ']) {+ if (parts.isNotEmpty) add(separator, StatusLineTone.foreground);+ }++ final git = branch ?? '';+ if (style.segmented) {+ if (style == StatusLineStyle.agnoster) {+ add(+ [provider, machine].where((s) => s.isNotEmpty).join(' '),+ StatusLineTone.white,+ StatusLineTone.black,+ );+ } else {+ add(provider, StatusLineTone.black, StatusLineTone.white);+ add(machine, StatusLineTone.yellow, StatusLineTone.black);+ }+ add(project, StatusLineTone.white, StatusLineTone.blue);+ add(git, StatusLineTone.black, StatusLineTone.green);+ } else {+ add(provider, StatusLineTone.foreground);+ if (machine.isNotEmpty || project.isNotEmpty || git.isNotEmpty) gap();+ switch (style) {+ case StatusLineStyle.standard:+ add(+ [machine, project].where((s) => s.isNotEmpty).join(':'),+ StatusLineTone.cyan,+ );+ if (git.isNotEmpty) {+ if (machine.isNotEmpty || project.isNotEmpty) gap();+ add('($git)', StatusLineTone.green);+ }+ case StatusLineStyle.robbyrussell:+ if (machine.isNotEmpty) add(machine, StatusLineTone.foreground);+ if (project.isNotEmpty) {+ if (machine.isNotEmpty) gap();+ add('➜ ', StatusLineTone.green);+ add(project, StatusLineTone.cyan);+ }+ if (git.isNotEmpty) {+ if (machine.isNotEmpty || project.isNotEmpty) gap(' ');+ add('git:(', StatusLineTone.blue);+ add(git, StatusLineTone.red);+ add(')', StatusLineTone.blue);+ }+ case StatusLineStyle.pure:+ add(machine, StatusLineTone.muted);+ if (project.isNotEmpty) {+ if (machine.isNotEmpty) gap();+ add(project, StatusLineTone.blue);+ }+ if (git.isNotEmpty) {+ if (machine.isNotEmpty || project.isNotEmpty) gap(' ');+ add(git, StatusLineTone.muted);+ }+ if (machine.isNotEmpty || project.isNotEmpty || git.isNotEmpty) {+ add(' ❯', StatusLineTone.magenta);+ }+ case StatusLineStyle.agnoster || StatusLineStyle.powerlevel10k:+ break;+ }+ }+ return StatusLineParts(style, parts);+}++StatusLineParts pullRequestStatusLineParts({+ required int number,+ required String state,+ StatusLineStyle style = StatusLineStyle.standard,+}) {+ final tone = switch (state) {+ 'Open' => StatusLineTone.green,+ 'Merged' => StatusLineTone.magenta,+ 'Closed' => StatusLineTone.red,+ _ => StatusLineTone.muted,+ };+ if (style.segmented) {+ return StatusLineParts(style, [+ StatusLineSegment(+ 'PR #$number · $state',+ foreground: state == 'Open' || state == 'Draft'+ ? StatusLineTone.black+ : StatusLineTone.white,+ background: tone,+ ),+ ]);+ }+ return StatusLineParts(style, [+ StatusLineSegment(+ 'PR #$number · ',+ foreground: switch (style) {+ StatusLineStyle.robbyrussell => StatusLineTone.blue,+ StatusLineStyle.pure => StatusLineTone.muted,+ _ => tone,+ },+ ),+ StatusLineSegment(state, foreground: tone),+ ]);+}++/// Resolved once in Dart so the Flutter preview and native bar use identical+/// ANSI colors. Backgrounds are static theme styling, not Git clean/dirty state.+class StatusLinePaintSegment {+ const StatusLinePaintSegment(this.text, this.foreground, this.background);+ final String text;+ final Color foreground;+ final Color? background;++ Map<String, Object> toJson() => {+ 'text': text,+ 'foreground': foreground.toARGB32(),+ if (background != null) 'background': background!.toARGB32(),+ };+}++List<StatusLinePaintSegment> statusLinePaintSegments(+ StatusLineParts parts,+ TerminalTheme theme, {+ bool color = true,+ int segmentOffset = 0,+}) {+ Color resolve(StatusLineTone tone) => switch (tone) {+ StatusLineTone.foreground => theme.foreground,+ StatusLineTone.muted => Color.lerp(+ theme.background,+ theme.foreground,+ .55,+ )!,+ StatusLineTone.black => theme.black,+ StatusLineTone.white => theme.white,+ StatusLineTone.blue => theme.blue,+ StatusLineTone.cyan => theme.cyan,+ StatusLineTone.green => theme.green,+ StatusLineTone.yellow => theme.yellow,+ StatusLineTone.red => theme.red,+ StatusLineTone.magenta => theme.magenta,+ };+ return [+ for (var i = 0; i < parts.segments.length; i++)+ StatusLinePaintSegment(+ parts.segments[i].text,+ color ? resolve(parts.segments[i].foreground) : theme.foreground,+ parts.segments[i].background == null+ ? null+ : color+ ? resolve(parts.segments[i].background!)+ : Color.lerp(+ theme.background,+ theme.foreground,+ (i + segmentOffset).isEven ? .12 : .22,+ ),+ ),+ ];+}diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dartindex d5e28e71f..c42373050 100644--- a/desktop/lib/shortcuts/keymap_commands.dart+++ b/desktop/lib/shortcuts/keymap_commands.dart@@ -312,6 +312,24 @@ final harnessCommands = <HarnessCommand>[const HarnessCommand('agent.rename', 'Rename Harness', ShortcutGroup.actions),const HarnessCommand('agent.stop', 'Stop Harness', ShortcutGroup.actions),const HarnessCommand('agent.fork', 'Fork Harness', ShortcutGroup.actions),+ const HarnessCommand(+ 'agent.share',+ 'Share Harness',+ ShortcutGroup.actions,+ nativeAction: 'shareAgent',+ ),+ const HarnessCommand(+ 'pane.toggle_viewer',+ 'Toggle Viewer',+ ShortcutGroup.panes,+ nativeAction: 'toggleViewer',+ ),+ const HarnessCommand(+ 'pane.toggle_composer',+ 'Toggle Message Composer',+ ShortcutGroup.panes,+ nativeAction: 'toggleComposer',+ ),const HarnessCommand('agent.clone','Clone Harness',@@ -363,6 +381,13 @@ final harnessCommands = <HarnessCommand>[ShortcutGroup.actions,nativeAction: 'linkMachine',),+ const HarnessCommand(+ 'harnesses.list',+ 'Harnesses',+ ShortcutGroup.actions,+ nativeAction: 'sessions',+ keywords: ['manage', 'running', 'paused', 'sessions'],+ ),const HarnessCommand('project.add','Add project',diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 286b0240f..dcc362f49 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -10390,7 +10390,9 @@ class AppNotifier extends ChangeNotifier {swarm.titleAgentId = raw['titleAgentId'] as String?;swarm.nameIsCustom =raw['nameIsCustom'] == true ||- (swarm.titleAgentId == null && swarm.name != Swarm.defaultName);+ (swarm.titleAgentId == null &&+ swarm.name != Swarm.defaultName &&+ !(swarm.isStore && swarm.name == Swarm.storeName));for (final item in (raw['panes'] as List).take(maxPanes)) {final entry = PaneLayoutEntry.fromJson(item);if (entry == null) continue;diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dartindex 19d56c389..2a6de42b9 100644--- a/desktop/lib/state/new_harness.dart+++ b/desktop/lib/state/new_harness.dart@@ -574,7 +574,7 @@ class NewHarnessController extends ChangeNotifier {return entry != null && !entry.isViewerPackage;}- /// A remembered harness the machine no longer offers opens as Coding. Only+ /// A remembered harness the machine no longer offers opens as Code. Only/// a remembered one: a harness someone asked for by name keeps its row, and/// its start explains what is wrong.void _forgetUnofferedHarness() {@@ -584,8 +584,7 @@ class NewHarnessController extends ChangeNotifier {_engine = _initialEngine(null);}- String get harnessLabel =>- _harnessId == null ? 'Coding' : labelOf(_harnessId!);+ String get harnessLabel => _harnessId == null ? 'Code' : labelOf(_harnessId!);bool advancedOpen = false;bool _selectionTouched = false, _advancedTouched = false;void toggleAdvanced() {@@ -2538,7 +2537,7 @@ class NewHarnessController extends ChangeNotifier {id,)?.id ??canonicalHarnessId(id);- // Recent harnesses, then Coding, then what this machine has installed,+ // Recent harnesses, then Code, then what this machine has installed,// then the rest of the Store — every harness is here, and searchable; one// that is not installed yet installs when it starts.final recents = <String>{@@ -2567,7 +2566,7 @@ class NewHarnessController extends ChangeNotifier {for (final id in recents) row(id),const NewHarnessOption(id: codingId,- title: 'Coding',+ title: 'Code',detail: 'Work in any code project',),for (final id in rest.where(installed)) row(id),diff --git a/desktop/lib/state/swarm.dart b/desktop/lib/state/swarm.dartindex ce33587b6..f282ecbe8 100644--- a/desktop/lib/state/swarm.dart+++ b/desktop/lib/state/swarm.dart@@ -1,7 +1,6 @@import 'dart:ui' show Size;-import '../core/models.dart'- show Agent, isAutomaticHarnessName, kUntitledPane;+import '../core/models.dart' show Agent, isAutomaticHarnessName, kUntitledPane;import 'pane_preset.dart';import 'pane_arrangement.dart';import 'terminal_pane.dart';@@ -17,7 +16,10 @@ class Swarm {this.isNewTabPage = false,bool? nameIsCustom,}) : name = nameIsCustom == true ? name : normalizeName(name),- nameIsCustom = nameIsCustom ?? (normalizeName(name) != defaultName);+ nameIsCustom =+ nameIsCustom ??+ (normalizeName(name) != defaultName &&+ !(kind == 'store' && name == storeName));/// What the tab holds: `harness` — panes of agents (the default); `store` —/// the Harness Store, no panes. A store tab is a tab like any other —diff --git a/desktop/lib/state/workspace_pull_request.dart b/desktop/lib/state/workspace_pull_request.dartnew file mode 100644index 000000000..a8f6ae13e--- /dev/null+++ b/desktop/lib/state/workspace_pull_request.dart@@ -0,0 +1,94 @@+import 'dart:async';++import 'package:flutter/foundation.dart';++import '../core/pull_request_status.dart';+import 'app_state.dart';+import 'workspace_status.dart';++typedef _Identity = (String, String, String?, String?, String?);++/// One PR reader for the focused harness, including a dependent viewer's owner.+/// Never publishes a late reply for a different pane or branch.+class WorkspacePullRequest extends ChangeNotifier {+ WorkspacePullRequest(+ this.app, {+ Future<Map<String, dynamic>> Function(String, String)? read,+ }) : _read = read ?? app.readAgentPullRequest {+ app.addListener(_focusChanged);+ _focusChanged();+ }+ final AppNotifier app;+ final Future<Map<String, dynamic>> Function(String, String) _read;+ final _cache = <_Identity, (DateTime, PullRequestStatus?)>{};+ _Identity? _identity;+ PullRequestStatus? value;+ Timer? _timer;+ int _revision = 0;++ void _focusChanged() {+ final focused = WorkspacePaneContext.focused(app);+ final agent = focused?.agent;+ final project = agent == null+ ? null+ : app.stateOf(focused!.pane.machineId)?.projectOf(agent);+ final identity =+ focused == null || agent == null || project?.shownBranch == null+ ? null+ : (+ focused.pane.machineId,+ agent.id,+ project?.cwd,+ project?.remote,+ project?.shownBranch,+ );+ if (identity == _identity) return;+ _identity = identity;+ final revision = ++_revision;+ _timer?.cancel();+ final cached = _cache[identity];+ value = cached?.$2;+ notifyListeners();+ if (identity == null) return;+ final age = cached == null+ ? const Duration(seconds: 60)+ : DateTime.now().difference(cached.$1);+ if (age < const Duration(seconds: 60)) {+ _timer = Timer(+ const Duration(seconds: 60) - age,+ () => _refresh(identity, revision),+ );+ } else {+ unawaited(_refresh(identity, revision));+ }+ }++ Future<void> _refresh(_Identity identity, int revision) async {+ Map<String, dynamic>? result;+ try {+ result = await _read(identity.$1, identity.$2);+ } catch (_) {+ /* Hidden until available. */+ }+ if (revision != _revision) return;+ value = PullRequestStatus.fromResult(result);+ if (_cache.length >= 32 && !_cache.containsKey(identity)) {+ _cache.remove(_cache.keys.first);+ }+ _cache[identity] = (DateTime.now(), value);+ notifyListeners();+ if (revision != _revision) return;+ _timer = Timer(+ const Duration(seconds: 60),+ () => _refresh(identity, revision),+ );+ }++ @override+ void dispose() {+ _revision++;+ _timer?.cancel();+ app.removeListener(_focusChanged);+ super.dispose();+ }+}diff --git a/desktop/lib/state/workspace_status.dart b/desktop/lib/state/workspace_status.dartnew file mode 100644index 000000000..cd3bc8450--- /dev/null+++ b/desktop/lib/state/workspace_status.dart@@ -0,0 +1,190 @@+import '../core/models.dart';+import '../shared/theme/prompt_style.dart';+import '../shared/theme/status_line_style.dart';+import '../widgets/engine_identity.dart';+import 'app_state.dart';+import 'swarm.dart';+import 'terminal_pane.dart';++/// A tab's type describes its harness panes. Viewers never cast a second vote+/// for their owner. Ties follow pane order, independently of keyboard focus.+String tabHarnessType(AppNotifier app, Swarm tab) {+ if (tab.isStore) return 'store';+ if (tab.isOrchestrator) return 'orchestrator';+ final counts = <String, int>{};+ for (final pane in tab.panes) {+ if (pane.isWeb || pane.agentId == null) continue;+ final agent = _agentFor(app, pane.machineId, pane.agentId);+ final engine = agent?.identityEngine ?? pane.session?.engineId;+ if (engine == null || engine.isEmpty) continue;+ final identity = engineIdentity(engine);+ final type = identity.category == 'Code' && !isHarnessId(engine)+ ? 'code'+ : identity.id.split('/').last;+ counts.update(type, (count) => count + 1, ifAbsent: () => 1);+ }+ var winner = 'new';+ var largest = 0;+ for (final entry in counts.entries) {+ if (entry.value > largest) {+ winner = entry.key;+ largest = entry.value;+ }+ }+ return winner;+}++enum _TabTrait { type, project, machine }++typedef _TabName = ({_TabTrait trait, String label, int count});++/// Prefer the strongest shared trait, then the one least repeated in other+/// tabs. Type wins otherwise equal choices; focus and custom names never vote.+Map<String, String> workspaceTabNames(AppNotifier app) {+ final candidates = <String, List<_TabName>>{};+ for (final tab in app.swarms) {+ if (tab.nameIsCustom) {+ candidates[tab.id] = [];+ continue;+ }+ final counts = <_TabTrait, Map<String, int>>{+ for (final trait in _TabTrait.values) trait: {},+ };+ final seen = <(String, String)>{};+ void vote(_TabTrait trait, String? label) {+ if (label == null || label.isEmpty) return;+ counts[trait]!.update(label, (n) => n + 1, ifAbsent: () => 1);+ }++ for (final pane in tab.panes) {+ final id = pane.agentId;+ if (pane.isWeb || id == null || !seen.add((pane.machineId, id))) continue;+ final machine = app.stateOf(pane.machineId);+ final agent = _agentFor(app, pane.machineId, id);+ final engine = agent?.identityEngine ?? pane.session?.engineId;+ if (engine != null && engine.isNotEmpty) {+ final identity = engineIdentity(engine);+ vote(+ _TabTrait.type,+ identity.category == 'Code' && !isHarnessId(engine)+ ? 'code'+ : identity.id.split('/').last,+ );+ }+ vote(+ _TabTrait.project,+ agent == null ? null : machine?.projectOf(agent)?.label,+ );+ vote(_TabTrait.machine, machine?.machine.displayName ?? pane.machineId);+ }+ candidates[tab.id] = [+ for (final trait in _TabTrait.values)+ if (counts[trait]!.isNotEmpty)+ (() {+ final winner = counts[trait]!.entries.reduce(+ (a, b) => b.value > a.value ? b : a,+ );+ return (trait: trait, label: winner.key, count: winner.value);+ })(),+ ];+ }+ int repetitions(_TabName name) => candidates.values+ .where(+ (choices) => choices.any(+ (other) => other.trait == name.trait && other.label == name.label,+ ),+ )+ .length;+ return {+ for (final tab in app.swarms)+ tab.id: tab.nameIsCustom+ ? tab.name+ : tab.isStore+ ? 'store'+ : tab.isOrchestrator+ ? 'orchestrator'+ : candidates[tab.id]!.isEmpty+ ? 'new'+ : candidates[tab.id]!.reduce((a, b) {+ if (b.count != a.count) return b.count > a.count ? b : a;+ return repetitions(b) < repetitions(a) ? b : a;+ }).label,+ };+}++Agent? _agentFor(AppNotifier app, String machineId, String? agentId) => app+ .stateOf(machineId)+ ?.agents+ .where((agent) => agent.id == agentId)+ .firstOrNull;++/// The focused viewer reports its owner's context, just like its terminal.+class WorkspacePaneContext {+ const WorkspacePaneContext({+ required this.pane,+ required this.machineName,+ required this.provider,+ required this.location,+ required this.detail,+ this.projectName = '',+ this.agent,+ this.branch,+ });++ final TerminalPane pane;+ final Agent? agent;+ final String machineName, provider, location, detail;+ final String projectName;+ final String? branch;+ String? get agentId => pane.isWeb ? pane.ownerAgentId : pane.agentId;+ String? get engine => agent?.engine ?? pane.session?.engineId;+ String get suffix => branch == null ? '' : ' ($branch)';+ String get text => '${provider.isEmpty ? '' : '$provider '}$location$suffix';+ StatusLineParts format(PromptPrefs prefs) => statusLineParts(+ provider: provider,+ machine: prefs.machine ? machineName : '',+ project: prefs.project ? projectName : '',+ branch: prefs.branch ? branch : null,+ style: prefs.statusStyle,+ );++ static WorkspacePaneContext? focused(AppNotifier app) {+ final pane = app.focusedPane;+ if (pane == null) return null;+ final machine = app.stateOf(pane.machineId);+ final agentId = pane.isWeb ? pane.ownerAgentId : pane.agentId;+ final agent = _agentFor(app, pane.machineId, agentId);+ final project = agent == null ? null : machine?.projectOf(agent);+ final machineName = machine?.machine.displayName ?? pane.machineId;+ final engine = agent?.engine ?? pane.session?.engineId;+ final provider =+ agent?.gridModel ??+ switch (engine) {+ 'codex' => 'OpenAI',+ 'claude' => 'Anthropic',+ 'terminal' || null => '',+ _ => engineIdentity(engine).label,+ };+ final projectName = project?.label ?? '';+ final branch = project?.detached == true+ ? 'detached:${project!.branch!.substring(kDetachedBranchPrefix.length)}'+ : project?.shownBranch;+ return WorkspacePaneContext(+ pane: pane,+ agent: agent,+ machineName: machineName,+ provider: provider,+ projectName: projectName,+ location: '$machineName${projectName.isEmpty ? '' : ':$projectName'}',+ branch: branch,+ detail: [+ if (agent != null) agent.displayName,+ if (provider.isNotEmpty) provider,+ machineName,+ if (project != null) 'Project: ${project.label}',+ if (project != null) project.cwd,+ ?project?.branchDetail,+ ].join('\n'),+ );+ }+}diff --git a/desktop/lib/terminal/terminal_text.dart b/desktop/lib/terminal/terminal_text.dartindex ff0598696..518eb7744 100644--- a/desktop/lib/terminal/terminal_text.dart+++ b/desktop/lib/terminal/terminal_text.dart@@ -31,6 +31,20 @@ TextStyle terminalContentStyle({Color? color}) => terminalFontStore.value.toTextStyle(color: color).copyWith(letterSpacing: 0, wordSpacing: 0);+/// One character column and one text row, measured just as the terminal does.+/// Terminal dialogs use whole cells for their margins, gutters and selection.+Size terminalCellSizeOf(BuildContext context) {+ TerminalFontScope.watch(context);+ final painter = TextPainter(+ text: TextSpan(text: 'mmmmmmmmmm', style: terminalContentStyle()),+ textDirection: TextDirection.ltr,+ textScaler: MediaQuery.textScalerOf(context),+ )..layout();+ final size = Size(painter.width / 10, painter.height);+ painter.dispose();+ return size;+}+/// Keeps retained widgets and open overlays on the same live typography.class TerminalFontScope extends InheritedNotifier<TerminalFontStore> {TerminalFontScope({super.key, required super.child})diff --git a/desktop/lib/widgets/box_chrome.dart b/desktop/lib/widgets/box_chrome.dartindex 88b16c2bf..69260b91d 100644--- a/desktop/lib/widgets/box_chrome.dart+++ b/desktop/lib/widgets/box_chrome.dart@@ -7,6 +7,12 @@ import '../terminal/terminal_text.dart';const double kTerminalCornerRadius = 3;+/// One rim for workspace panes and the dialogs that take their keyboard focus.+BorderSide terminalPaneBorder({bool focused = false}) => BorderSide(+ color: focused ? grid.AppPalette.accentOnSurface : grid.AppPalette.divider,+ width: 1,+);+/// One gutter around the workspace, between panes, and beside command docks.const double kWorkspaceInset = 9.5;diff --git a/desktop/lib/widgets/grid_model_picker.dart b/desktop/lib/widgets/grid_model_picker.dartindex a94449d9a..1ffb2b7c3 100644--- a/desktop/lib/widgets/grid_model_picker.dart+++ b/desktop/lib/widgets/grid_model_picker.dart@@ -45,6 +45,10 @@ bool modelPickerSupports(String? engine) =>/// The list is fetched when the menu opens rather than held in state, because it is live: an engine/// can join or leave a grid between two openings, and an offer nobody is serving any more is worse/// than a moment's spinner.+class GridModelPickerController extends ChangeNotifier {+ void open() => notifyListeners();+}+class GridModelPicker extends StatefulWidget {final AppNotifier notifier;final String machineId;@@ -75,6 +79,11 @@ class GridModelPicker extends StatefulWidget {final String? engineLabel;final bool compact;+ /// Native workspace chrome opens the same picker without duplicating its+ /// label in every pane. The menu anchors to the top of the Flutter surface.+ final bool menuOnly;+ final GridModelPickerController? controller;+const GridModelPicker({super.key,required this.notifier,@@ -86,6 +95,8 @@ class GridModelPicker extends StatefulWidget {this.webSearch,this.engineLabel,this.compact = false,+ this.menuOnly = false,+ this.controller,});@override@@ -112,6 +123,7 @@ class _GridModelPickerState extends State<GridModelPicker> {_last = widget.notifier.gridPictures[widget.machineId];widget.notifier.gridPictures.addListener(_pictureChanged);widget.notifier.foreground.addListener(_foregroundChanged);+ widget.controller?.addListener(_openFromController);// A reading that lands while the menu is open redraws its Subscription row, rather than// leaving "Checking usage…" there until the next open._usage.addListener(_redrawOpenMenu);@@ -196,6 +208,10 @@ class _GridModelPickerState extends State<GridModelPicker> {@overridevoid didUpdateWidget(GridModelPicker oldWidget) {super.didUpdateWidget(oldWidget);+ if (widget.controller != oldWidget.controller) {+ oldWidget.controller?.removeListener(_openFromController);+ widget.controller?.addListener(_openFromController);+ }if (widget.currentModel == oldWidget.currentModel) return;if (_expecting && _settles(widget.currentModel)) {_expiry?.cancel();@@ -250,6 +266,7 @@ class _GridModelPickerState extends State<GridModelPicker> {void dispose() {widget.notifier.gridPictures.removeListener(_pictureChanged);widget.notifier.foreground.removeListener(_foregroundChanged);+ widget.controller?.removeListener(_openFromController);_expiry?.cancel();// A pane can go away under an open menu — closed, moved, or its swarm switched — and an overlay// entry outlives the State that inserted it.@@ -277,6 +294,8 @@ class _GridModelPickerState extends State<GridModelPicker> {Map<String, Object?>? _subscriptionRow() =>subscriptionRowFor(widget.engineLabel, _usage.rows);+ void _openFromController() => unawaited(_open());+Future<void> _open() async {if (_loading) return;// A warm answer opens the menu with no wait at all. It is at most seconds old — the daemon's own@@ -317,12 +336,14 @@ class _GridModelPickerState extends State<GridModelPicker> {Overlay.of(context).context.findRenderObject() as RenderBox?;if (box == null || overlay == null) return;final origin = box.localToGlobal(Offset.zero, ancestor: overlay);- final position = RelativeRect.fromLTRB(- origin.dx,- origin.dy + box.size.height + 6,- overlay.size.width - origin.dx - box.size.width,- 0,- );+ final position = widget.menuOnly+ ? RelativeRect.fromLTRB(overlay.size.width - 12, 0, 12, 0)+ : RelativeRect.fromLTRB(+ origin.dx,+ origin.dy + box.size.height + 6,+ overlay.size.width - origin.dx - box.size.width,+ 0,+ );final chosen = await _showMenu(position: position,@@ -475,6 +496,7 @@ class _GridModelPickerState extends State<GridModelPicker> {@overrideWidget build(BuildContext context) {TerminalFontScope.watch(context);+ if (widget.menuOnly) return const SizedBox.shrink();final sentence = _webSearchSentence;final current =widget.currentModel ??diff --git a/desktop/lib/widgets/harness_customize_pane.dart b/desktop/lib/widgets/harness_customize_pane.dartindex b7b3a8c1b..12cee3930 100644--- a/desktop/lib/widgets/harness_customize_pane.dart+++ b/desktop/lib/widgets/harness_customize_pane.dart@@ -82,7 +82,7 @@ class HarnessCustomizePane extends StatelessWidget {dividerColor: grid.AppPalette.divider,labelStyle: grid.AppType.label(),tabs: const [- Tab(key: ValueKey('customize-prompt'), text: 'Pane'),+ Tab(key: ValueKey('customize-prompt'), text: 'Status'),Tab(key: ValueKey('customize-appearance'),text: 'Appearance',diff --git a/desktop/lib/widgets/new_harness_form.dart b/desktop/lib/widgets/new_harness_form.dartindex c0570f962..df569cf3d 100644--- a/desktop/lib/widgets/new_harness_form.dart+++ b/desktop/lib/widgets/new_harness_form.dart@@ -3,6 +3,7 @@ import 'dart:async';import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';+import 'package:xterm/xterm.dart' show TerminalTheme;import '../shortcuts/app_keymap.dart';import '../shortcuts/keymap.dart';@@ -14,7 +15,7 @@ import '../terminal/terminal_text.dart';import '../terminal/terminal_theme.dart';import '../terminal/terminal_theme_store.dart';import '../state/new_harness.dart';-import 'box_chrome.dart';+import 'box_chrome.dart' show kTerminalCornerRadius, terminalPaneBorder;import 'dsh_install_panel.dart' show describeInstallFailure;/// Every answer a new harness needs, on one screen, changed where it stands.@@ -678,21 +679,20 @@ class _NewHarnessFormState extends State<NewHarnessForm> {return KeyEventResult.handled;}- Color get _rule => Colors.white.withValues(alpha: .16);+ TerminalTheme get _theme =>+ terminalThemeFor(grid.AppTheme.palette.value, terminalThemeStore.value);- Color get _popupFill => terminalThemeFor(- grid.AppTheme.palette.value,- terminalThemeStore.value,- ).background;+ Color get _rule => _theme.foreground.withValues(alpha: .16);+ Color get _faint => _theme.foreground.withValues(alpha: .54);// Only the column that owns the keys carries Open Harness's full highlight.- Color get _activeFill => Colors.white.withValues(alpha: .12);+ Color get _activeFill => _theme.selection;/// A machine that cannot be picked — unlinked or offline — in dark grey,/// darker than the faint of an idle list, so it recedes rather than warns.- Color get _unavailableInk => Colors.white.withValues(alpha: .28);+ Color get _unavailableInk => _theme.foreground.withValues(alpha: .28);- Color get _idleFill => Colors.white.withValues(alpha: .04);+ Color get _idleFill => _theme.foreground.withValues(alpha: .04);/// One face, one size, everywhere on this screen — and it is the/// TERMINAL's size, the one ⌘+ and ⌘− set, not the UI's fixed 13pt. A box@@ -702,10 +702,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {/// wrapped ones included — lands on the grid by itself. A two-line notice/// is exactly two rows; nothing needs a box around it to stay in step.TextStyle _ink([Color? color]) =>- terminalContentStyle(color: color ?? Colors.white).copyWith(- height: _rowHeight / _font,- leadingDistribution: TextLeadingDistribution.even,- );+ terminalContentStyle(color: color ?? _theme.foreground);/// THE GRID. A terminal has two units and positions nothing in pixels:///@@ -724,16 +721,10 @@ class _NewHarnessFormState extends State<NewHarnessForm> {double _rowHeight = 20;void _measureGrid(BuildContext context) {- final scaler = MediaQuery.textScalerOf(context);- _font = scaler.scale(terminalFontStore.size);- _rowHeight = (_font * 1.6).roundToDouble();- final painter = TextPainter(- text: TextSpan(text: '0000000000', style: terminalContentStyle()),- textDirection: TextDirection.ltr,- textScaler: scaler,- )..layout();- _cell = painter.width / 10;- painter.dispose();+ _font = MediaQuery.textScalerOf(context).scale(terminalFontStore.size);+ final cell = terminalCellSizeOf(context);+ _cell = cell.width;+ _rowHeight = cell.height;}/// Where each pane's rows sit: one cell in from the pane's edge, so the@@ -767,7 +758,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {_revealRow();}_measureGrid(context);- return KeymapRegion(+ final form = KeymapRegion(contextKind: KeymapContext.picker,composing: _isComposing,actions: {@@ -791,9 +782,15 @@ class _NewHarnessFormState extends State<NewHarnessForm> {focusNode: _focus,onKeyEvent: _onKey,child: Material(+ key: const ValueKey('new-harness-surface'),elevation: 0,- color: _popupFill,+ color: _theme.background,surfaceTintColor: Colors.transparent,+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(kTerminalCornerRadius),+ side: terminalPaneBorder(focused: true),+ ),+ clipBehavior: Clip.antiAlias,child: DefaultTextStyle.merge(style: _ink(),child: LayoutBuilder(@@ -844,6 +841,14 @@ class _NewHarnessFormState extends State<NewHarnessForm> {),),);+ return TextSelectionTheme(+ data: TextSelectionThemeData(+ cursorColor: _theme.cursor,+ selectionColor: _theme.selection,+ selectionHandleColor: _theme.cursor,+ ),+ child: form,+ );}Widget _items() => Padding(@@ -922,7 +927,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {maxLines: 1,softWrap: false,overflow: TextOverflow.clip,- style: _ink(grid.AppPalette.swarmAccent),+ style: _ink(_theme.cursor),),),SizedBox(width: _cell * 2),@@ -932,7 +937,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {maxLines: 1,softWrap: false,overflow: TextOverflow.clip,- style: _ink(kBoxFaint),+ style: _ink(_faint),),),],@@ -984,10 +989,10 @@ class _NewHarnessFormState extends State<NewHarnessForm> {Icon(LucideIcons.chevronLeft300,size: _font,- color: kBoxFaint,+ color: _faint,),),- Text(_label(_row), style: _ink(kBoxFaint)),+ Text(_label(_row), style: _ink(_faint)),],),),@@ -999,7 +1004,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {_atTextColumn(Semantics(liveRegion: true,- child: Text(status, style: _ink(kBoxFaint)),+ child: Text(status, style: _ink(_faint)),),),SizedBox(height: _rowHeight),@@ -1076,39 +1081,39 @@ class _NewHarnessFormState extends State<NewHarnessForm> {: run.failed? '$name did not install on ${box.machineLabel}': 'Installing $name on ${box.machineLabel}',- end: _Elapsed(run: run, style: _ink(kBoxFaint)),+ end: _Elapsed(run: run, style: _ink(_faint)),),SizedBox(height: _rowHeight),for (final (phase, label) in steps) ...[if (failedPhase == phase)- line('✗', label, color: Colors.orangeAccent)+ line('✗', label, color: _theme.red)else if (run.done || (run.reached(phase) && run.phase != phase))line('✓',label,end: run.took(phase) == null? null- : Text(_took(run.took(phase)!), style: _ink(kBoxFaint)),+ : Text(_took(run.took(phase)!), style: _ink(_faint)),)else if (run.phase == phase && run.inProgress) ...[line('>', label),if (run.line ?? run.detail case final now?)- line(null, now, color: kBoxFaint),+ line(null, now, color: _faint),] else- line(' ', label, color: kBoxFaint),+ line(' ', label, color: _faint),],if (tail.isNotEmpty && !run.done && failure == null) ...[SizedBox(height: _rowHeight),- for (final entry in tail) line(null, entry, color: kBoxFaint),+ for (final entry in tail) line(null, entry, color: _faint),],if (failure != null) ...[SizedBox(height: _rowHeight),- line(null, failure.title, color: Colors.orangeAccent),+ line(null, failure.title, color: _theme.red),if (failure.body case final body?)- line(null, body, color: kBoxFaint),+ line(null, body, color: _faint),if (failure.command case final command?) line(null, command),if (failure.hint case final hint?)- line(null, hint, color: kBoxFaint),+ line(null, hint, color: _faint),],SizedBox(height: _rowHeight),line(@@ -1118,7 +1123,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {: run.done? 'Starting the harness…': 'The first install takes a few minutes.',- color: kBoxFaint,+ color: _faint,),],),@@ -1136,7 +1141,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {child: Text(box.error ?? box.status!,key: const ValueKey('new-harness-status'),- style: _ink(box.error != null ? Colors.orangeAccent : kBoxFaint),+ style: _ink(box.error != null ? _theme.red : _faint),),);@@ -1168,18 +1173,18 @@ class _NewHarnessFormState extends State<NewHarnessForm> {crossAxisAlignment: CrossAxisAlignment.stretch,children: [if (_row == _Row.model && box.modelNotice != null) ...[- _atTextColumn(Text(box.modelNotice!, style: _ink(kBoxFaint))),+ _atTextColumn(Text(box.modelNotice!, style: _ink(_faint))),SizedBox(height: _rowHeight),],if (shown.isEmpty &&!_prompts.contains(box.field) &&!box.refreshingChoices)- _atTextColumn(Text('No matches', style: _ink(kBoxFaint))),+ _atTextColumn(Text('No matches', style: _ink(_faint))),for (var i = 0; i < shown.length; i++) ...[if (blankBefore(i)) SizedBox(height: _rowHeight),if (shown[i].group != null &&(i == 0 || shown[i].group != shown[i - 1].group))- _atTextColumn(Text(shown[i].group!, style: _ink(kBoxFaint))),+ _atTextColumn(Text(shown[i].group!, style: _ink(_faint))),_matchRow(shown[i]),],],@@ -1223,7 +1228,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {'>',key: const ValueKey('new-harness-prompt'),textAlign: TextAlign.center,- style: _ink(_picking ? Colors.white : kBoxFaint),+ style: _ink(_picking ? _theme.foreground : _faint),),),Expanded(@@ -1242,8 +1247,8 @@ class _NewHarnessFormState extends State<NewHarnessForm> {focusNode: _inputFocus,readOnly: box.locked,showCursor: _picking,- style: _ink(Colors.white),- cursorColor: Colors.white70,+ style: _ink(_theme.foreground),+ cursorColor: _theme.cursor,// A block caret, one cell wide, as a terminal draws it.cursorWidth: _cell,cursorRadius: Radius.zero,@@ -1258,7 +1263,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {onTapOutside: (_) {},decoration: InputDecoration(hintText: _promptHint,- hintStyle: _ink(kBoxFaint),+ hintStyle: _ink(_faint),hintMaxLines: 1,isDense: true,isCollapsed: true,@@ -1285,7 +1290,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {height: _rowHeight,),iconSize: _font,- icon: Icon(LucideIcons.refreshCw300, color: kBoxFaint),+ icon: Icon(LucideIcons.refreshCw300, color: _faint),),],),@@ -1341,12 +1346,10 @@ class _NewHarnessFormState extends State<NewHarnessForm> {unavailable? _unavailableInk: !_picking || !option.enabled- ? kBoxFaint+ ? _faint: option.synthetic- ? grid.AppPalette.swarmAccent- : on- ? Colors.white- : Colors.white70,+ ? _theme.cursor+ : _theme.foreground,),);return Semantics(@@ -1383,7 +1386,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {// or never linked — which a dimmed row alone cannot.if (note != null) ...[SizedBox(width: _cell * 2),- Text(note, style: _ink(kBoxFaint)),+ Text(note, style: _ink(_faint)),],],),@@ -1398,7 +1401,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {child: _oneRow(Text(option.detail,- style: _ink(kBoxFaint),+ style: _ink(_faint),maxLines: 1,overflow: TextOverflow.ellipsis,),@@ -1454,11 +1457,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {final highlighted = row == _row;final blocked = _blocked(row);final value = blocked ?? _value(row);- final ink = blocked != null || _picking- ? kBoxFaint- : highlighted- ? Colors.white- : Colors.white70;+ final ink = blocked != null || _picking ? _faint : _theme.foreground;return Semantics(key: ValueKey('new-harness-field-${row.name}'),label: '${_label(row)}, $value',@@ -1477,7 +1476,7 @@ class _NewHarnessFormState extends State<NewHarnessForm> {child: LayoutBuilder(builder: (context, constraints) {final stacked = constraints.maxWidth < 360 * _scale;- final label = Text(_label(row), style: _ink(kBoxFaint));+ final label = Text(_label(row), style: _ink(_faint));final content = Text(value,style: _ink(ink),diff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dartindex 876379819..c46663577 100644--- a/desktop/lib/widgets/pane_grid.dart+++ b/desktop/lib/widgets/pane_grid.dart@@ -30,7 +30,6 @@ import 'harness_join_guide_screen.dart';import 'link_machine_screen.dart';import 'new_agent_dialog.dart';import 'delete_agent_dialog.dart';-import 'fork_agent_dialog.dart';import 'restart_agent_action.dart';import 'terminal_panel.dart';import 'web_pane_panel.dart';@@ -1243,21 +1242,10 @@ class _PaneCell extends StatelessWidget {// The rim is always drawn — it is what gives an unfocused card its// edge, now that no shared line does. It only CHANGES COLOUR on// focus, so nothing resizes as focus moves.- border: Border.all(- // FOCUS IS THE ENGINE'S OWN COLOUR, not the app's blue.- //- // One colour per pane, and only its EXTENT changes: the engine's- // line runs along the top edge normally and around all four when- // the pane is focused. The blue ring said the same thing in a- // second colour — and, worse, the old treatment blanked the band- // underneath it, so the focused pane was the one pane on the grid- // that no longer told you which engine it was running. It went- // quiet exactly when you looked at it.- //- // Only meaningful with company: a ring around the only tile would- // be decoration, since there is nowhere else focus could be.- color: !_single && focused ? AppColors.accent : AppColors.border,- width: 1,+ border: Border.fromBorderSide(+ // A lone pane needs no focus distinction. Dialogs use this same+ // rim in its focused state while they own the keyboard.+ terminalPaneBorder(focused: !_single && focused),),),// Attention, drawn OVER the terminal and inside the border above, so a@@ -1526,20 +1514,6 @@ class _PaneContent extends StatelessWidget {notice: notice,onToggleComposer: () => notifier.toggleComposer(pane.id),onClose: single && !swarmMode ? null : close,- onRestart: agent == null || offline || needsLink- ? null- : () =>- restartHarness(context, notifier, pane.machineId, agent.id),- onFork: agent == null || offline || needsLink || !agent.canFork- ? null- : () => forkHarness(- context,- notifier,- pane.machineId,- agent.id,- agent.displayName,- engine: agent.engine,- ),// The same confirmation the rail's row menu opens. Only for an// agent the machine still lists — a pane whose agent is already// gone has nothing to end.diff --git a/desktop/lib/widgets/pane_header_actions.dart b/desktop/lib/widgets/pane_header_actions.dartindex 59668891e..e6d5a3da6 100644--- a/desktop/lib/widgets/pane_header_actions.dart+++ b/desktop/lib/widgets/pane_header_actions.dart@@ -1,463 +1,106 @@-import 'dart:async';-import 'package:flutter/material.dart';-import 'package:lucide_icons_flutter/lucide_icons.dart';import '../shared/theme/app_theme.dart' as grid;-import '../theme/app_theme.dart';-import 'box_chrome.dart';-import 'pane_menu.dart';+import '../terminal/terminal_text.dart';+import '../terminal/terminal_theme.dart';+import '../terminal/terminal_theme_store.dart';-/// Direct pane controls, in a stable order even when an action is unavailable.+/// Three quiet terminal characters: close this view, zoom, and stop its harness.class PaneHeaderActions extends StatelessWidget {const PaneHeaderActions({super.key,required this.zoomed,this.onZoom,- this.onRestart,- this.onFork,- this.onShare,this.onDelete,this.onClose,- this.onToggleComposer,- this.composerVisible = false,- this.onToggleViewer,- this.viewerVisible = false,- this.viewerColor,this.details,this.trailing,this.modelPicker,this.terminal = false,- this.compact = false,});- final bool zoomed, composerVisible;-- /// The pane is a shell, not a harness: Restart and Stop say so, because- /// "Stop Harness" over a terminal reads as a button for something else.- final bool terminal;- final bool compact;- final VoidCallback? onShare;- final VoidCallback? onZoom,- onRestart,- onFork,- onDelete,- onClose,- onToggleComposer;-- /// A harness agent's viewer: show it beside this terminal, or hide it.- /// Absent for an agent that has no viewer.- final VoidCallback? onToggleViewer;- final bool viewerVisible;-- /// The harness's own colour: the sparkles glow with it while the viewer- /// is open, and go quiet when it is hidden.- final Color? viewerColor;+ final bool zoomed, terminal;+ final VoidCallback? onZoom, onDelete, onClose;+ final Widget? details, trailing, modelPicker;- /// Folder, branch and machine share the controls' space while idle. Both- /// layers keep their size so hovering never changes the title's width.- final Widget? details;-- /// Supplemental branch context, hidden with details when controls appear.- final Widget? trailing;-- /// The current model stays visible beside the pane's contextual controls.- final Widget? modelPicker;+ /// Two columns per control, including the space around a single character.+ static double widthOf(BuildContext context) =>+ terminalCellSizeOf(context).width * 6;@overrideWidget build(BuildContext context) {grid.AppTheme.watch(context);-- Widget action(String tooltip, IconData icon, VoidCallback? callback) =>- IconButton(- tooltip: tooltip,+ final cell = terminalCellSizeOf(context);+ final theme = terminalThemeFor(+ grid.AppTheme.palette.value,+ terminalThemeStore.value,+ );+ Widget action(+ String symbol,+ String label,+ VoidCallback? callback, {+ bool? toggled,+ }) => Tooltip(+ message: label,+ child: Semantics(+ label: label,+ button: true,+ enabled: callback != null,+ toggled: toggled,+ child: TextButton(onPressed: callback,- icon: Icon(icon, size: 16),style: ButtonStyle(- fixedSize: const WidgetStatePropertyAll(Size(28, 28)),- minimumSize: const WidgetStatePropertyAll(Size(28, 28)),+ fixedSize: WidgetStatePropertyAll(+ Size(cell.width * 2, cell.height * 2),+ ),+ minimumSize: const WidgetStatePropertyAll(Size.zero),padding: const WidgetStatePropertyAll(EdgeInsets.zero),tapTargetSize: MaterialTapTargetSize.shrinkWrap,visualDensity: VisualDensity.standard,- shape: WidgetStatePropertyAll(- RoundedRectangleBorder(- borderRadius: BorderRadius.circular(kTerminalCornerRadius),- ),- ),+ textStyle: WidgetStatePropertyAll(terminalContentStyle()),+ shape: const WidgetStatePropertyAll(RoundedRectangleBorder()),foregroundColor: WidgetStateProperty.resolveWith((states) {if (states.contains(WidgetState.disabled)) {- return grid.AppPalette.textFaint;+ return theme.foreground.withValues(alpha: .2);}if (states.contains(WidgetState.hovered) ||states.contains(WidgetState.focused)) {- return AppColors.text;+ return theme.foreground;}- return AppColors.mutedStrong.withValues(alpha: .8);+ return theme.foreground.withValues(alpha: .55);}),- overlayColor: WidgetStatePropertyAll(grid.AppSurface.hoverFill),+ overlayColor: WidgetStatePropertyAll(+ theme.foreground.withValues(alpha: .08),+ ),),- );-- final visible = _PaneHeaderVisibility.of(context);- // The ⋮ menu is always in view: it is one small mark at the edge, not a row of icons that- // would crowd the title at rest.- final shown = visible || compact;- final controls = IgnorePointer(- ignoring: !shown,- child: AnimatedOpacity(- opacity: shown ? 1 : 0,- alwaysIncludeSemantics: true,- duration: MediaQuery.disableAnimationsOf(context)- ? Duration.zero- : grid.AppMotion.hover,- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- if (!compact && onShare != null) ...[- action('Share harness', Icons.person_add_alt_1_outlined, onShare),- const SizedBox(width: 2),- ],- if (compact)- // The row of icons, as a menu: each action keeps the icon it had in the row.- _CompactPaneActions(- items: [- if (onShare != null)- (- label: 'Share harness',- icon: Icons.person_add_alt_1_outlined,- callback: onShare,- ),- if (onToggleViewer != null)- (- label: viewerVisible ? 'Hide viewer' : 'Show viewer',- icon: LucideIcons.sparkles,- callback: onToggleViewer,- ),- if (onToggleComposer != null)- (- label: composerVisible- ? 'Hide message composer'- : 'Show message composer',- icon: LucideIcons.keyboard,- callback: onToggleComposer,- ),- (- label: 'Zoom Pane',- icon: zoomed ? LucideIcons.minimize : LucideIcons.maximize,- callback: onZoom,- ),- (- label: terminal ? 'Restart Terminal' : 'Restart Harness',- icon: LucideIcons.refreshCw,- callback: onRestart,- ),- if (onFork != null)- (- label: 'Fork Harness',- icon: LucideIcons.gitFork,- callback: onFork,- ),- (- label: terminal ? 'Stop Terminal' : 'Stop Harness',- icon: Icons.stop_rounded,- callback: onDelete,- ),- (label: 'Close Pane', icon: LucideIcons.x, callback: onClose),- ],- )- else ...[- if (onToggleViewer != null) ...[- _ViewerToggle(- key: const ValueKey('pane-viewer-toggle'),- on: viewerVisible,- color: viewerColor ?? AppColors.text,- onPressed: onToggleViewer,- ),- const SizedBox(width: 2),- ],- if (onToggleComposer != null) ...[- action(- composerVisible- ? 'Hide message composer'- : 'Show message composer',- LucideIcons.keyboard,- onToggleComposer,- ),- const SizedBox(width: 2),- ],- action(- 'Zoom Pane',- zoomed ? LucideIcons.minimize : LucideIcons.maximize,- onZoom,- ),- const SizedBox(width: 2),- action(- terminal ? 'Restart Terminal' : 'Restart Harness',- LucideIcons.refreshCw,- onRestart,- ),- const SizedBox(width: 2),- if (onFork != null) ...[- action('Fork Harness', LucideIcons.gitFork, onFork),- const SizedBox(width: 2),- ],- action(- terminal ? 'Stop Terminal' : 'Stop Harness',- Icons.stop_rounded,- onDelete,- ),- const SizedBox(width: 2),- action('Close Pane', LucideIcons.x, onClose),- ],- ],+ child: ExcludeSemantics(child: Text(symbol)),),),);- final actionArea = details == null- ? controls- : Stack(- alignment: Alignment.centerRight,- children: [- IgnorePointer(- ignoring: visible,- child: AnimatedOpacity(- key: const ValueKey('pane-header-details'),- opacity: visible ? 0 : 1,- duration: MediaQuery.disableAnimationsOf(context)- ? Duration.zero- : grid.AppMotion.hover,- child: ExcludeSemantics(- excluding: visible,- child: trailing == null- ? details!- : Row(- mainAxisSize: MainAxisSize.min,- children: [- Flexible(child: details!),- trailing!,- ],- ),- ),- ),- ),- controls,- ],- );- if (modelPicker == null) return actionArea;- // The model, then folder, branch and PR, then the ⋮ menu on the right edge. With the actions- // in one menu there is nothing for the details to swap with on hover, so they stay in view.return Row(mainAxisSize: MainAxisSize.min,children: [- modelPicker!,- if (details != null)- // The gap shrinks WITH the details: a pane too narrow for them gives the picker and- // the menu every pixel rather than overflowing by the width of a gap beside nothing.+ if (modelPicker != null) Flexible(child: modelPicker!),+ if (details != null || trailing != null)Flexible(- child: Padding(- padding: const EdgeInsets.only(left: 8),- child: trailing == null- ? details!- : Row(- mainAxisSize: MainAxisSize.min,- children: [- Flexible(child: details!),- trailing!,- ],- ),- ),- ),- const SizedBox(width: 2),- controls,- ],- );- }-}--/// A small pane keeps the same actions in a keyboard-navigable menu, leaving-/// room for its title. Native titlebar actions dismiss this menu too.-class _CompactPaneActions extends StatefulWidget {- const _CompactPaneActions({required this.items});- final List<({String label, IconData icon, VoidCallback? callback})> items;-- @override- State<_CompactPaneActions> createState() => _CompactPaneActionsState();-}--class _CompactPaneActionsState extends State<_CompactPaneActions> {- bool _open = false;-- /// The pane menu, the same surface as the model picker beside it: its box, its rows and its- /// hover. Each row keeps the icon the action had when it was a row of icons.- Future<void> _show() async {- if (_open) return;- final box = context.findRenderObject() as RenderBox?;- final overlay =- Overlay.of(context).context.findRenderObject() as RenderBox?;- if (box == null || overlay == null) return;- final enabled = widget.items- .where((item) => item.callback != null)- .toList();- if (enabled.isEmpty) return;- final origin = box.localToGlobal(Offset.zero, ancestor: overlay);- setState(() => _open = true);- final chosen = await showPaneMenu<VoidCallback>(- context: context,- position: RelativeRect.fromLTRB(- origin.dx,- origin.dy + box.size.height + 6,- overlay.size.width - origin.dx - box.size.width,- 0,- ),- minWidth: 200,- maxWidth: 340,- children: (close) => [- for (final item in enabled)- paneMenuItem(- onTap: () => close(item.callback),- child: Padding(- padding: const EdgeInsets.symmetric(- horizontal: kPaneMenuRowPadding,- vertical: 7,- ),- child: Row(- children: [- Icon(item.icon, size: 15, color: AppColors.mutedStrong),- const SizedBox(width: 10),- // Flexible: a large text setting shortens the label rather than overflowing.- Flexible(- child: Text(- item.label,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: grid.AppType.body(color: AppColors.text),- ),- ),- ],- ),+ child: Row(+ key: const ValueKey('pane-header-details'),+ mainAxisSize: MainAxisSize.min,+ children: [+ if (details != null) Flexible(child: details!),+ ?trailing,+ ],),),- ],- );- if (mounted) setState(() => _open = false);- chosen?.call();- }-- @override- Widget build(BuildContext context) => IconButton(- tooltip: 'Pane actions',- onPressed: widget.items.any((item) => item.callback != null)- ? () => unawaited(_show())- : null,- icon: const Icon(Icons.more_vert, size: 16),- style: IconButton.styleFrom(- foregroundColor: _open ? AppColors.text : AppColors.mutedStrong,- fixedSize: const Size(28, 28),- minimumSize: const Size(28, 28),- padding: EdgeInsets.zero,- tapTargetSize: MaterialTapTargetSize.shrinkWrap,- ),- );-}--/// Only header controls depend on this hover state, so the terminal and title-/// are retained as the pointer crosses the bar. Keyboard focus reveals them too.-class PaneHeaderHover extends StatefulWidget {- const PaneHeaderHover({super.key, required this.child});- final Widget child;- @override- State<PaneHeaderHover> createState() => _PaneHeaderHoverState();-}--class _PaneHeaderHoverState extends State<PaneHeaderHover> {- bool _hovered = false, _focused = false;- @override- Widget build(BuildContext context) {- return MouseRegion(- onEnter: (_) => setState(() => _hovered = true),- onExit: (_) => setState(() => _hovered = false),- child: Focus(- canRequestFocus: false,- includeSemantics: false,- onFocusChange: (value) => setState(() => _focused = value),- child: _PaneHeaderVisibility(- visible: _hovered || _focused,- child: widget.child,- ),- ),- );- }-}--class _PaneHeaderVisibility extends InheritedWidget {- const _PaneHeaderVisibility({required this.visible, required super.child});- final bool visible;- static bool of(BuildContext context) =>- context- .dependOnInheritedWidgetOfExactType<_PaneHeaderVisibility>()- ?.visible ??- true;- @override- bool updateShouldNotify(_PaneHeaderVisibility oldWidget) =>- visible != oldWidget.visible;-}--/// The way into the magic box: sparkles that glow in the harness's colour-/// while its viewer is open, and sit muted when it is hidden. Same footprint-/// as the other header actions, so the row never shifts.-class _ViewerToggle extends StatelessWidget {- const _ViewerToggle({- super.key,- required this.on,- required this.color,- required this.onPressed,- });-- final bool on;- final Color color;- final VoidCallback? onPressed;-- @override- Widget build(BuildContext context) {- final glow = color.withValues(alpha: .55);- return IconButton(- tooltip: on ? 'Hide viewer' : 'Show viewer',- onPressed: onPressed,- icon: AnimatedContainer(- duration: grid.AppMotion.swap,- curve: Curves.easeOut,- decoration: BoxDecoration(- shape: BoxShape.circle,- boxShadow: on- ? [- BoxShadow(color: glow, blurRadius: 10, spreadRadius: 1),- BoxShadow(- color: color.withValues(alpha: .25),- blurRadius: 18,- spreadRadius: 4,- ),- ]- : const [],- ),- child: Icon(- LucideIcons.sparkles,- size: 16,- color: on ? color : AppColors.mutedStrong.withValues(alpha: .6),- ),- ),- style: ButtonStyle(- fixedSize: const WidgetStatePropertyAll(Size(28, 28)),- minimumSize: const WidgetStatePropertyAll(Size(28, 28)),- padding: const WidgetStatePropertyAll(EdgeInsets.zero),- tapTargetSize: MaterialTapTargetSize.shrinkWrap,- visualDensity: VisualDensity.standard,- shape: WidgetStatePropertyAll(- RoundedRectangleBorder(- borderRadius: BorderRadius.circular(kTerminalCornerRadius),- ),+ action('-', 'Close Pane', onClose),+ action(+ '[]',+ zoomed ? 'Restore Pane' : 'Zoom Pane',+ onZoom,+ toggled: zoomed,),- overlayColor: WidgetStatePropertyAll(grid.AppSurface.hoverFill),- ),+ action('x', terminal ? 'Stop Terminal' : 'Stop Harness', onDelete),+ ],);}}diff --git a/desktop/lib/widgets/prompt_customize.dart b/desktop/lib/widgets/prompt_customize.dartindex c37bdf031..ec69c0bda 100644--- a/desktop/lib/widgets/prompt_customize.dart+++ b/desktop/lib/widgets/prompt_customize.dart@@ -1,13 +1,15 @@import 'dart:async';import 'package:flutter/material.dart';-import 'package:harness/terminal/terminal_text.dart';import '../shared/theme/app_theme.dart' as grid;import '../shared/theme/appearance_prefs_store.dart';import '../shared/theme/prompt_style.dart';-import 'box_chrome.dart';-import 'prompt_context.dart';+import '../shared/theme/status_line_style.dart';+import '../terminal/terminal_text.dart';+import '../terminal/terminal_theme.dart';+import '../terminal/terminal_theme_store.dart';+import 'status_line.dart';class PromptCustomize extends StatelessWidget {const PromptCustomize({super.key, required this.store});@@ -16,128 +18,133 @@ class PromptCustomize extends StatelessWidget {@overrideWidget build(BuildContext context) {TerminalFontScope.watch(context);- return ValueListenableBuilder<AppearancePrefs>(- valueListenable: store,- builder: (context, appearance, _) {- final prefs = appearance.prompt;+ grid.AppTheme.watch(context);+ return ListenableBuilder(+ listenable: Listenable.merge([store, terminalThemeStore]),+ builder: (context, _) {+ final prefs = store.value.prompt;+ final cell = terminalCellSizeOf(context);+ final theme = terminalThemeFor(+ grid.AppTheme.palette.value,+ terminalThemeStore.value,+ );+ final style = terminalContentStyle(color: theme.foreground);void choose(PromptPrefs next) => unawaited(store.setPrompt(next));+ StatusLineParts example(StatusLineStyle format) => statusLineParts(+ provider: 'OpenAI',+ machine: prefs.machine ? 'M2' : '',+ project: prefs.project ? 'app' : '',+ branch: prefs.branch ? 'main' : null,+ style: format,+ );+ final previewContext = example(prefs.statusStyle);+ final preview = StatusLineParts(prefs.statusStyle, [+ ...previewContext.segments,+ if (!prefs.statusStyle.segmented &&+ previewContext.segments.isNotEmpty)+ const StatusLineSegment(' '),+ ...pullRequestStatusLineParts(+ number: 298,+ state: 'Merged',+ style: prefs.statusStyle,+ ).segments,+ ]);+ final buttonStyle = TextButton.styleFrom(+ alignment: Alignment.centerLeft,+ foregroundColor: theme.foreground,+ minimumSize: Size.zero,+ padding: EdgeInsets.symmetric(horizontal: cell.width),+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,+ shape: const RoundedRectangleBorder(),+ textStyle: style,+ );Widget toggle(String name,String label,bool value,- ValueChanged<bool> onChanged,- ) => TextButton(- key: ValueKey('prompt-$name'),- style: TextButton.styleFrom(- alignment: Alignment.centerLeft,- foregroundColor: grid.AppPalette.textPrimary,- shape: const RoundedRectangleBorder(- borderRadius: BorderRadius.all(- Radius.circular(kTerminalCornerRadius),- ),- ),- ),- onPressed: () => onChanged(!value),- child: Semantics(- checked: value,- label: label,- child: ExcludeSemantics(- child: Text(- '${value ? '[x]' : '[ ]'} $label',- style: grid.AppType.monoLabel(- color: grid.AppPalette.textPrimary,- fontWeight: FontWeight.w400,- ),+ ValueChanged<bool> change,+ ) => SizedBox(+ height: cell.height,+ child: TextButton(+ key: ValueKey('prompt-$name'),+ style: buttonStyle,+ onPressed: () => change(!value),+ child: Semantics(+ checked: value,+ label: label,+ child: ExcludeSemantics(+ child: Text('${value ? '[x]' : '[ ]'} $label', style: style),),),),);return SingleChildScrollView(- padding: const EdgeInsets.all(16),+ padding: EdgeInsets.symmetric(+ horizontal: cell.width * 2,+ vertical: cell.height,+ ),child: Column(crossAxisAlignment: CrossAxisAlignment.stretch,children: [- Text(- 'header style',- style: grid.AppType.monoMeta(- color: grid.AppPalette.textSecondary,- ),- ),- const SizedBox(height: 8),- for (final style in PromptStyle.values)- TextButton(- key: ValueKey('prompt-style-${style.name}'),- onPressed: () => choose(prefs.copyWith(style: style)),- style: TextButton.styleFrom(- alignment: Alignment.centerLeft,- backgroundColor: prefs.style == style- ? grid.AppSurface.selectedFill- : null,- padding: const EdgeInsets.symmetric(- horizontal: 10,- vertical: 10,+ Text('Status line', style: style),+ SizedBox(height: cell.height),+ for (final format in StatusLineStyle.values) ...[+ SizedBox(+ height: cell.height,+ child: TextButton(+ key: ValueKey('prompt-style-${format.name}'),+ style: buttonStyle.copyWith(+ backgroundColor: WidgetStatePropertyAll(+ prefs.statusStyle == format+ ? theme.selection+ : Colors.transparent,+ ),),- shape: const RoundedRectangleBorder(- borderRadius: BorderRadius.all(- Radius.circular(kTerminalCornerRadius),+ onPressed: () =>+ choose(prefs.copyWith(statusStyle: format)),+ child: Semantics(+ selected: prefs.statusStyle == format,+ child: Text(+ '${prefs.statusStyle == format ? '>' : ' '} ${format.label}',+ style: style,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,),),),- child: Semantics(- selected: prefs.style == style,- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(- '${prefs.style == style ? '>' : ' '} ${style.label}',- style: grid.AppType.monoLabel(- color: grid.AppPalette.textPrimary,- fontWeight: FontWeight.w400,- ),- ),- Padding(- padding: const EdgeInsets.only(left: 16, top: 3),- child: Text(- style.description,- style: grid.AppType.body(- color: grid.AppPalette.textSecondary,- ),- ),- ),- ],+ ),+ Padding(+ padding: EdgeInsets.only(left: cell.width * 3),+ child: SizedBox(+ height: cell.height,+ child: StatusLine(+ key: ValueKey('prompt-example-${format.name}'),+ parts: example(format),+ color: prefs.color,+ textAlign: TextAlign.left,),),),- const SizedBox(height: 16),- Text(- 'preview',- style: grid.AppType.monoMeta(- color: grid.AppPalette.textSecondary,- ),- ),- const SizedBox(height: 6),- TerminalBox(+ SizedBox(height: cell.height),+ ],+ Text('Preview', style: style),+ SizedBox(height: cell.height),+ ColoredBox(+ color: theme.background,child: Padding(- padding: const EdgeInsets.all(12),- child: PromptContextView(+ padding: EdgeInsets.symmetric(+ horizontal: cell.width,+ vertical: cell.height,+ ),+ child: StatusLine(key: const ValueKey('prompt-preview'),- store: store,- contextData: const PromptContext(- harness: 'Codex',- machine: 'devbox',- project: 'openharness',- branch: 'main',- ),+ parts: preview,+ color: prefs.color,+ textAlign: TextAlign.left,),),),- const SizedBox(height: 16),- Text(- 'context',- style: grid.AppType.monoMeta(- color: grid.AppPalette.textSecondary,- ),- ),+ SizedBox(height: cell.height),toggle('machine','Machine',@@ -162,20 +169,29 @@ class PromptCustomize extends StatelessWidget {prefs.color,(value) => choose(prefs.copyWith(color: value)),),- const SizedBox(height: 8),+ SizedBox(height: cell.height),Text(- 'Applies to agent search and pane headers. Changes are saved as you choose.',- style: grid.AppType.body(color: grid.AppPalette.textSecondary),+ 'Applies to the focused pane in the top bar. Saved as you choose.',+ style: style.copyWith(+ color: theme.foreground.withValues(alpha: .6),+ ),),- const SizedBox(height: 12),- TextButton(- key: const ValueKey('prompt-reset'),- onPressed: () => choose(const PromptPrefs()),- child: Text(- 'Reset header style',- style: grid.AppType.label(- color: grid.AppPalette.textSecondary,+ SizedBox(height: cell.height),+ SizedBox(+ height: cell.height,+ child: TextButton(+ key: const ValueKey('prompt-reset'),+ style: buttonStyle,+ onPressed: () => choose(+ prefs.copyWith(+ statusStyle: StatusLineStyle.standard,+ machine: true,+ project: true,+ branch: true,+ color: true,+ ),),+ child: Text('[ Reset status line ]', style: style),),),],diff --git a/desktop/lib/widgets/pull_request_badge.dart b/desktop/lib/widgets/pull_request_badge.dartindex 49ec31645..77cf36507 100644--- a/desktop/lib/widgets/pull_request_badge.dart+++ b/desktop/lib/widgets/pull_request_badge.dart@@ -4,6 +4,7 @@ import 'package:flutter/material.dart';import 'package:url_launcher/url_launcher.dart';import '../shared/theme/app_theme.dart' as grid;+import '../core/pull_request_status.dart';/// A separate PR label: branch colour does not encode review state.class PullRequestBadge extends StatefulWidget {@@ -67,23 +68,9 @@ class _PullRequestBadgeState extends State<PullRequestBadge> {@overrideWidget build(BuildContext context) {grid.AppTheme.watch(context);- final result = _result;- if (result?['status'] == 'none') return const SizedBox.shrink();- final number = result?['number'];- final state = result?['state'];- final uri = Uri.tryParse(- result?['url'] is String ? result!['url'] as String : '',- );- final found =- result?['status'] == 'found' &&- number is int &&- number > 0 &&- const ['Draft', 'Open', 'Merged', 'Closed'].contains(state) &&- uri?.scheme == 'https' &&- uri?.host == 'github.com' &&- uri!.userInfo.isEmpty &&- uri.path.endsWith('/pull/$number');- if (!found) return const SizedBox.shrink();+ final pr = PullRequestStatus.fromResult(_result);+ if (pr == null) return const SizedBox.shrink();+ final number = pr.number, state = pr.state, uri = pr.url;final label = '${widget.compact ? '' : 'PR '}#$number · $state';return Tooltip(message: 'PR #$number · $state — Open on GitHub',@@ -93,18 +80,16 @@ class _PullRequestBadgeState extends State<PullRequestBadge> {padding: const EdgeInsets.symmetric(horizontal: 6),textStyle: grid.AppType.monoLabel(),),- onPressed: found- ? () async {- final opened =- await (widget.open?.call(uri) ??- launchUrl(uri, mode: LaunchMode.externalApplication));- if (!opened && context.mounted) {- ScaffoldMessenger.maybeOf(context)?.showSnackBar(- const SnackBar(content: Text('Could not open GitHub.')),- );- }- }- : null,+ onPressed: () async {+ final opened =+ await (widget.open?.call(uri) ??+ launchUrl(uri, mode: LaunchMode.externalApplication));+ if (!opened && context.mounted) {+ ScaffoldMessenger.maybeOf(context)?.showSnackBar(+ const SnackBar(content: Text('Could not open GitHub.')),+ );+ }+ },child: Text(label, maxLines: 1, overflow: TextOverflow.ellipsis),),);diff --git a/desktop/lib/widgets/status_line.dart b/desktop/lib/widgets/status_line.dartnew file mode 100644index 000000000..0431e5ec5--- /dev/null+++ b/desktop/lib/widgets/status_line.dart@@ -0,0 +1,222 @@+import 'dart:math' as math;++import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../shared/theme/status_line_style.dart';+import '../terminal/terminal_text.dart';+import '../terminal/terminal_theme.dart';+import '../terminal/terminal_theme_store.dart';++/// Shares resolved text/color segments with the native macOS status bar.+class StatusLine extends StatelessWidget {+ const StatusLine({+ super.key,+ required this.parts,+ this.color = true,+ this.textAlign = TextAlign.right,+ this.nextBackground,+ this.segmentOffset = 0,+ });+ final StatusLineParts parts;+ final bool color;+ final TextAlign textAlign;++ /// Fill behind the final arrow to join a separately clickable next segment.+ final Color? nextBackground;+ final int segmentOffset;++ @override+ Widget build(BuildContext context) {+ TerminalFontScope.watch(context);+ grid.AppTheme.watch(context);+ return ValueListenableBuilder(+ valueListenable: terminalThemeStore,+ builder: (context, _, _) {+ final theme = terminalThemeFor(+ grid.AppTheme.palette.value,+ terminalThemeStore.value,+ );+ final style = terminalContentStyle(color: theme.foreground);+ final segments = statusLinePaintSegments(+ parts,+ theme,+ color: color,+ segmentOffset: segmentOffset,+ );+ if (!parts.style.segmented) {+ return Text.rich(+ TextSpan(+ children: [+ for (final segment in segments)+ TextSpan(+ text: segment.text,+ style: TextStyle(color: segment.foreground),+ ),+ ],+ ),+ style: style,+ maxLines: 1,+ softWrap: false,+ overflow: TextOverflow.ellipsis,+ textAlign: textAlign,+ );+ }+ final cell = terminalCellSizeOf(context);+ final scaler = MediaQuery.textScalerOf(context);+ return Semantics(+ label: parts.text,+ child: LayoutBuilder(+ builder: (context, constraints) {+ // Below one text cell per segment, show ordinary text rather than+ // spending all available room on arrows and padding.+ if (constraints.maxWidth < segments.length * cell.width * 4) {+ return ExcludeSemantics(+ child: Text(+ parts.text,+ style: style,+ maxLines: 1,+ softWrap: false,+ overflow: TextOverflow.ellipsis,+ textAlign: textAlign,+ ),+ );+ }+ final widths = [+ for (final segment in segments)+ _measure(segment.text, style, scaler),+ ];+ final natural =+ widths.fold(0.0, (a, b) => a + b) ++ segments.length * cell.width * 3;+ return Align(+ widthFactor: 1,+ alignment: textAlign == TextAlign.left+ ? Alignment.centerLeft+ : Alignment.centerRight,+ child: CustomPaint(+ size: Size(+ math.min(natural, constraints.maxWidth),+ cell.height,+ ),+ painter: _StatusSegmentsPainter(+ segments,+ widths,+ cell,+ style,+ scaler,+ nextBackground,+ ),+ ),+ );+ },+ ),+ );+ },+ );+ }+}++double _measure(String text, TextStyle style, TextScaler scaler) {+ final painter = TextPainter(+ text: TextSpan(text: text, style: style),+ textDirection: TextDirection.ltr,+ textScaler: scaler,+ maxLines: 1,+ )..layout();+ final width = painter.width;+ painter.dispose();+ return width;+}++/// Short values retain their width; the longest values share the remaining+/// space. Native AppKit uses the same cap when a segmented status is shortened.+List<double> fitStatusLineWidths(List<double> widths, double available) {+ if (widths.fold(0.0, (a, b) => a + b) <= available) return widths;+ var low = 0.0;+ var high = widths.fold(0.0, math.max);+ for (var i = 0; i < 24; i++) {+ final cap = (low + high) / 2;+ if (widths.fold(0.0, (sum, width) => sum + math.min(width, cap)) >+ available) {+ high = cap;+ } else {+ low = cap;+ }+ }+ return [for (final width in widths) math.min(width, low)];+}++class _StatusSegmentsPainter extends CustomPainter {+ const _StatusSegmentsPainter(+ this.segments,+ this.widths,+ this.cell,+ this.style,+ this.scaler,+ this.nextBackground,+ );+ final List<StatusLinePaintSegment> segments;+ final List<double> widths;+ final Size cell;+ final TextStyle style;+ final TextScaler scaler;+ final Color? nextBackground;++ @override+ void paint(Canvas canvas, Size size) {+ final fitted = fitStatusLineWidths(+ widths,+ math.max(0, size.width - segments.length * cell.width * 3),+ );+ canvas.save();+ canvas.clipRect(Offset.zero & size);+ var x = 0.0;+ for (var i = 0; i < segments.length; i++) {+ final segment = segments[i];+ final inset = cell.width * (i == 0 ? 1 : 2);+ final width = fitted[i] + inset + cell.width;+ if (i == segments.length - 1 && nextBackground != null) {+ canvas.drawRect(+ Rect.fromLTWH(x + width, 0, cell.width, cell.height),+ Paint()..color = nextBackground!,+ );+ }+ final shape = Path()+ ..moveTo(x, 0)+ ..lineTo(x + width, 0)+ ..lineTo(x + width + cell.width, cell.height / 2)+ ..lineTo(x + width, cell.height)+ ..lineTo(x, cell.height)+ ..lineTo(x + (i == 0 ? 0 : cell.width), cell.height / 2)+ ..close();+ canvas.drawPath(shape, Paint()..color = segment.background!);+ final painter = TextPainter(+ text: TextSpan(+ text: segment.text,+ style: style.copyWith(color: segment.foreground),+ ),+ textDirection: TextDirection.ltr,+ textScaler: scaler,+ maxLines: 1,+ ellipsis: '…',+ )..layout(maxWidth: fitted[i]);+ painter.paint(+ canvas,+ Offset(x + inset, (cell.height - painter.height) / 2),+ );+ painter.dispose();+ x += width;+ }+ canvas.restore();+ }++ @override+ bool shouldRepaint(_StatusSegmentsPainter oldDelegate) =>+ segments != oldDelegate.segments ||+ widths != oldDelegate.widths ||+ cell != oldDelegate.cell ||+ style != oldDelegate.style ||+ scaler != oldDelegate.scaler ||+ nextBackground != oldDelegate.nextBackground;+}diff --git a/desktop/lib/widgets/swarm_search_input.dart b/desktop/lib/widgets/swarm_search_input.dartindex b52791435..4e42b62ef 100644--- a/desktop/lib/widgets/swarm_search_input.dart+++ b/desktop/lib/widgets/swarm_search_input.dart@@ -3,6 +3,8 @@ import 'package:harness/terminal/terminal_text.dart';import '../shared/theme/app_theme.dart' as grid;import '../state/swarm_search.dart';+import '../terminal/terminal_theme.dart';+import '../terminal/terminal_theme_store.dart';import 'box_chrome.dart';/// The shared input for the start page, Open Agent and split searches.@@ -65,7 +67,7 @@ class SwarmSearchInput extends StatelessWidget {@overrideWidget build(BuildContext context) {- TerminalFontScope.watch(context);+ grid.AppTheme.watch(context);return ListenableBuilder(// Command mode changes with the editor value. Result highlights do not,// so arrow navigation must not rebuild the text field.@@ -77,9 +79,20 @@ class SwarmSearchInput extends StatelessWidget {Widget _buildInput(BuildContext context) {final open = search != null;final terminalStyle = terminal || prompt != null;+ final theme = terminalThemeFor(+ grid.AppTheme.palette.value,+ terminalThemeStore.value,+ );final style = bios- ? terminalContentStyle(color: Colors.white)+ ? terminalContentStyle(color: theme.foreground): boxMonoStyle();+ final cell = bios ? terminalCellSizeOf(context) : Size.zero;+ final hint =+ search?.isCommandMode == true ||+ search?.isHelpMode == true ||+ search?.isGroupMode == true+ ? search!.hint+ : hintText ?? search?.hint ?? kSwarmSearchHint;final border = OutlineInputBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(rounded ? (prominent ? 32 : 28) : 12),@@ -95,7 +108,7 @@ class SwarmSearchInput extends StatelessWidget {? BorderSide(color: Colors.white.withValues(alpha: .10)): BorderSide.none,);- return TextField(+ final field = TextField(key: inputKey,groupId: groupId ?? EditableText,controller: controller,@@ -106,96 +119,137 @@ class SwarmSearchInput extends StatelessWidget {onTapOutside: onTapOutside == null ? null : (_) => onTapOutside!(),onChanged: onChanged,style: terminalStyle ? style : grid.AppType.mono(color: Colors.white),- cursorColor: bios ? Colors.white70 : grid.AppPalette.swarmAccent,- cursorWidth: bios ? terminalFontStore.size * .62 : 2,+ cursorColor: bios ? theme.cursor : grid.AppPalette.swarmAccent,+ cursorWidth: bios ? cell.width : 2,cursorRadius: Radius.zero,cursorOpacityAnimates: !bios,+ autocorrect: !bios,+ enableSuggestions: !bios,textAlignVertical: TextAlignVertical.center,- decoration: InputDecoration(- hintText:- search?.isCommandMode == true ||- search?.isHelpMode == true ||- search?.isGroupMode == true- ? search!.hint- : hintText ?? search?.hint ?? kSwarmSearchHint,- hintStyle: terminalStyle- ? style.copyWith(color: kBoxFaint)- : grid.AppType.mono(color: Colors.white60),- hintMaxLines: 1,- prefixIcon: prompt != null- ? Padding(- padding: EdgeInsets.only(- left: bios ? 28 : 14,- right: bios ? 12 : 10,- ),- child: Center(- widthFactor: 1,- heightFactor: 1,- child: SizedBox(- width: bios ? terminalFontStore.size * 1.25 : null,- child: Text(- prompt!,- key: const ValueKey('swarm-search-prompt'),- textAlign: TextAlign.center,- style: style.copyWith(- color: bios- ? Colors.white- : grid.AppPalette.swarmAccent,+ decoration: bios+ ? InputDecoration(+ hintText: hint,+ hintStyle: style.copyWith(+ color: theme.foreground.withValues(alpha: .54),+ ),+ hintMaxLines: 1,+ isDense: true,+ isCollapsed: true,+ constraints: const BoxConstraints(),+ contentPadding: EdgeInsets.zero,+ border: InputBorder.none,+ enabledBorder: InputBorder.none,+ focusedBorder: InputBorder.none,+ filled: false,+ )+ : InputDecoration(+ hintText: hint,+ hintStyle: terminalStyle+ ? style.copyWith(color: kBoxFaint)+ : grid.AppType.mono(color: Colors.white60),+ hintMaxLines: 1,+ prefixIcon: prompt != null+ ? Padding(+ padding: const EdgeInsets.only(left: 14, right: 10),+ child: Center(+ widthFactor: 1,+ heightFactor: 1,+ child: Text(+ prompt!,+ key: const ValueKey('swarm-search-prompt'),+ textAlign: TextAlign.center,+ style: style.copyWith(+ color: grid.AppPalette.swarmAccent,+ ),+ ),),+ )+ : terminal+ ? null+ : Icon(+ Icons.search,+ size: fontSize + 4,+ color: Colors.white60,),- ),- ),- )- : terminal- ? null- : Icon(Icons.search, size: fontSize + 4, color: Colors.white60),- prefixIconConstraints: BoxConstraints(- minWidth: prompt != null- ? 36- : fontSize >= 20- ? 64- : 52,- minHeight: height ?? (prominent ? 64 : 56),- ),- suffixIcon: showClose || trailing != null- ? Padding(- padding: const EdgeInsets.only(right: 12),- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- ?trailing,- if (showClose)- TextButton(- onPressed: onClose,- style: TextButton.styleFrom(- foregroundColor: Colors.white60,- minimumSize: const Size(36, 28),- ),- child: Text('esc', style: grid.AppType.monoMeta()),+ prefixIconConstraints: BoxConstraints(+ minWidth: prompt != null+ ? 36+ : fontSize >= 20+ ? 64+ : 52,+ minHeight: height ?? (prominent ? 64 : 56),+ ),+ suffixIcon: showClose || trailing != null+ ? Padding(+ padding: const EdgeInsets.only(right: 12),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ ?trailing,+ if (showClose)+ TextButton(+ onPressed: onClose,+ style: TextButton.styleFrom(+ foregroundColor: Colors.white60,+ minimumSize: const Size(36, 28),+ ),+ child: Text(+ 'esc',+ style: grid.AppType.monoMeta(),+ ),+ ),+ ],),- ],- ),- )- : null,- // TerminalBox owns the dock surface. An unfilled field also avoids- // Material's extra inset, keeping the input aligned with result text.- filled: !terminal,- fillColor:- fillColor ??- (terminalStyle- ? grid.AppPalette.swarmField- : grid.AppPalette.swarmSearchSurface),- hoverColor: Colors.transparent,- contentPadding: EdgeInsets.symmetric(- horizontal: 18,- vertical: height == null- ? (prominent ? 22 : 18)- : ((height! - fontSize * 1.2) / 2).clamp(0, double.infinity),+ )+ : null,+ // TerminalBox owns the dock surface. An unfilled field also avoids+ // Material's extra inset, keeping the input aligned with result text.+ filled: !terminal,+ fillColor:+ fillColor ??+ (terminalStyle+ ? grid.AppPalette.swarmField+ : grid.AppPalette.swarmSearchSurface),+ hoverColor: Colors.transparent,+ contentPadding: EdgeInsets.symmetric(+ horizontal: 18,+ vertical: height == null+ ? (prominent ? 22 : 18)+ : ((height! - fontSize * 1.2) / 2).clamp(+ 0,+ double.infinity,+ ),+ ),+ isDense: true,+ border: terminalStyle ? InputBorder.none : border,+ enabledBorder: terminalStyle ? InputBorder.none : border,+ focusedBorder: terminalStyle ? InputBorder.none : border,+ ),+ );+ if (!bios) return field;+ return Padding(+ padding: EdgeInsets.symmetric(+ horizontal: cell.width * 2,+ vertical: cell.height,+ ),+ child: SizedBox(+ height: cell.height,+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.baseline,+ textBaseline: TextBaseline.alphabetic,+ children: [+ SizedBox(+ width: cell.width * 2,+ child: Text(+ prompt ?? '>',+ key: const ValueKey('swarm-search-prompt'),+ textAlign: TextAlign.center,+ style: style,+ ),+ ),+ Expanded(child: field),+ ],),- isDense: true,- border: terminalStyle ? InputBorder.none : border,- enabledBorder: terminalStyle ? InputBorder.none : border,- focusedBorder: terminalStyle ? InputBorder.none : border,),);}diff --git a/desktop/lib/widgets/swarm_search_preview.dart b/desktop/lib/widgets/swarm_search_preview.dartindex 21357befd..737baf7a8 100644--- a/desktop/lib/widgets/swarm_search_preview.dart+++ b/desktop/lib/widgets/swarm_search_preview.dart@@ -6,11 +6,13 @@ import 'package:lucide_icons_flutter/lucide_icons.dart';import 'package:harness/terminal/terminal_text.dart';import '../core/models.dart';+import '../shared/theme/app_theme.dart' as grid;import '../shared/theme/app_type.dart';-import '../shared/theme/prompt_style.dart';import '../state/app_state.dart';import '../state/swarm_navigation.dart';import '../state/swarm_search.dart';+import '../terminal/terminal_theme.dart';+import '../terminal/terminal_theme_store.dart';import 'box_chrome.dart';import 'engine_identity.dart';@@ -163,7 +165,18 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {@overrideWidget build(BuildContext context) {- TerminalFontScope.watch(context);+ grid.AppTheme.watch(context);+ final cell = widget.terminal ? terminalCellSizeOf(context) : Size.zero;+ final padding = widget.terminal+ ? EdgeInsets.symmetric(+ horizontal: cell.width * 2,+ vertical: cell.height,+ )+ : EdgeInsets.all(widget.compactHeader ? 16 : 24);+ final theme = terminalThemeFor(+ grid.AppTheme.palette.value,+ terminalThemeStore.value,+ );return AnimatedBuilder(animation: Listenable.merge([app, app.sessionPreviews]),builder: (context, _) {@@ -180,18 +193,14 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {? ListView.builder(key: ValueKey('preview-content:${row.id}'),controller: _scroll,- padding: EdgeInsets.all(- widget.terminal- ? 24- : widget.compactHeader- ? 16- : 24,- ),+ padding: padding,scrollCacheExtent: const ScrollCacheExtent.pixels(120),itemCount: agents.length + 1,itemBuilder: (context, index) => index == 0? Padding(- padding: const EdgeInsets.only(bottom: 24),+ padding: EdgeInsets.only(+ bottom: widget.terminal ? cell.height : 24,+ ),child: Column(crossAxisAlignment: CrossAxisAlignment.start,children: [@@ -199,28 +208,37 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {row.title,// The list leads the eye; this confirms it.style: widget.terminal- ? terminalContentStyle()+ ? terminalContentStyle(+ color: theme.foreground,+ ): AppType.monoLabel(fontWeight: FontWeight.w600,),),- const SizedBox(height: 6),+ if (!widget.terminal) const SizedBox(height: 6),Text(row.detail,style: widget.terminal- ? terminalContentStyle(color: kBoxFaint)+ ? terminalContentStyle(+ color: theme.foreground.withValues(+ alpha: .54,+ ),+ ): _muted,),// Nothing exists yet behind the create row, so// there is no session to be missing text from.if (agents.isEmpty && !row.isCreate)Padding(- padding: EdgeInsets.only(top: 24),+ padding: EdgeInsets.only(+ top: widget.terminal ? cell.height : 24,+ ),child: Text('No recent session text available.',style: widget.terminal? terminalContentStyle(- color: kBoxFaint,+ color: theme.foreground+ .withValues(alpha: .54),): _muted,),@@ -229,7 +247,13 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {),): Padding(- padding: EdgeInsets.only(top: index > 1 ? 20 : 0),+ padding: EdgeInsets.only(+ top: index > 1+ ? widget.terminal+ ? cell.height+ : 20+ : 0,+ ),child: Column(crossAxisAlignment: CrossAxisAlignment.start,children: [@@ -240,7 +264,9 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {terminal: widget.terminal,),if (index < agents.length)- const SizedBox(height: 20),+ SizedBox(+ height: widget.terminal ? cell.height : 20,+ ),],),),@@ -248,13 +274,7 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {: SingleChildScrollView(key: ValueKey('preview-content:${row.id}'),controller: _scroll,- padding: EdgeInsets.all(- widget.terminal- ? 24- : widget.compactHeader- ? 16- : 24,- ),+ padding: padding,child: _AgentPreview(app: app,item: agents.single,@@ -292,10 +312,17 @@ class _AgentPreview extends StatelessWidget {@overrideWidget build(BuildContext context) {- TerminalFontScope.watch(context);- final muted = terminal ? terminalContentStyle(color: kBoxFaint) : _muted;+ grid.AppTheme.watch(context);+ final cell = terminal ? terminalCellSizeOf(context) : Size.zero;+ final theme = terminalThemeFor(+ grid.AppTheme.palette.value,+ terminalThemeStore.value,+ );+ final muted = terminal+ ? terminalContentStyle(color: theme.foreground.withValues(alpha: .54))+ : _muted;final body = terminal- ? terminalContentStyle(color: const Color(0xffe1e1e4))+ ? terminalContentStyle(color: theme.foreground): _body;Widget section(String label, String text, {int? maxLines}) =>_Section(label, text, maxLines: maxLines, terminal: terminal);@@ -317,11 +344,17 @@ class _AgentPreview extends StatelessWidget {? 'Working': 'Idle';final color = offline- ? Colors.white54+ ? muted.color!: waiting != null- ? const Color(0xffe9bf79)+ ? terminal+ ? theme.yellow+ : const Color(0xffe9bf79): working- ? const Color(0xffadc5eb)+ ? terminal+ ? theme.blue+ : const Color(0xffadc5eb)+ : terminal+ ? theme.green: const Color(0xff9abea5);final project = machine.projectOf(agent);final request =@@ -344,18 +377,17 @@ class _AgentPreview extends StatelessWidget {crossAxisAlignment: CrossAxisAlignment.start,children: [if (terminal) ...[- Text(agent.displayName, style: terminalContentStyle()),- const SizedBox(height: 8),+ Text(agent.displayName, style: body),Text.rich(TextSpan(children: [TextSpan(text: '$state ',- style: const TextStyle(color: kBoxFaint),+ style: TextStyle(color: color),),TextSpan(text:- '$kHarnessPromptMarker ${agentIdentity(agent).label} · ${machine.machine.name}',+ '${agentIdentity(agent).label} @ ${machine.machine.name}',),],),@@ -431,7 +463,7 @@ class _AgentPreview extends StatelessWidget {),],if (compact) ...[- const SizedBox(height: 10),+ SizedBox(height: terminal ? cell.height : 10),Text(_displayText(excerpt ?? 'No recent session text available.'),maxLines: 4,@@ -440,7 +472,7 @@ class _AgentPreview extends StatelessWidget {),if (project != null)Padding(- padding: const EdgeInsets.only(top: 8),+ padding: EdgeInsets.only(top: terminal ? cell.height : 8),child: Text([project.label, project.branch].whereType<String>().join(' · '),style: muted,@@ -449,7 +481,7 @@ class _AgentPreview extends StatelessWidget {] else ...[SizedBox(height: terminal- ? 24+ ? cell.height: dense? 16: 26,@@ -457,32 +489,36 @@ class _AgentPreview extends StatelessWidget {if (waiting != null) ...[Container(width: double.infinity,- padding: EdgeInsets.all(terminal ? 8 : 16),- decoration: BoxDecoration(- color: color.withValues(alpha: .06),- border: Border.all(color: color.withValues(alpha: .24)),- borderRadius: BorderRadius.circular(terminal ? 0 : 12),- ),+ padding: terminal ? EdgeInsets.zero : const EdgeInsets.all(16),+ decoration: terminal+ ? null+ : BoxDecoration(+ color: color.withValues(alpha: .06),+ border: Border.all(color: color.withValues(alpha: .24)),+ borderRadius: BorderRadius.circular(12),+ ),child: Column(crossAxisAlignment: CrossAxisAlignment.start,children: [Text('Needs your input',- style: AppType.monoLabel(- fontWeight: FontWeight.w600,- color: color,- ),+ style: terminal+ ? terminalContentStyle(color: color)+ : AppType.monoLabel(+ fontWeight: FontWeight.w600,+ color: color,+ ),),- const SizedBox(height: 8),+ if (!terminal) const SizedBox(height: 8),Text(_displayText(waiting.prompt), style: body),if (waiting.options.isNotEmpty) ...[- const SizedBox(height: 12),+ SizedBox(height: terminal ? cell.height : 12),Text(waiting.options.take(6).join(' · '), style: muted),],],),),- const SizedBox(height: 24),+ SizedBox(height: terminal ? cell.height : 24),],if (working) ...[if (request != null) section(requestLabel, request),@@ -505,17 +541,21 @@ class _AgentPreview extends StatelessWidget {),if (record?.earlierResponses.isNotEmpty == true)Padding(- padding: const EdgeInsets.only(bottom: 24),+ padding: EdgeInsets.only(bottom: terminal ? cell.height : 24),child: Column(crossAxisAlignment: CrossAxisAlignment.start,children: [Text('Earlier in this session',- style: muted.copyWith(fontWeight: FontWeight.w500),+ style: terminal+ ? muted+ : muted.copyWith(fontWeight: FontWeight.w500),),for (final text in record!.earlierResponses)Padding(- padding: EdgeInsets.only(top: terminal ? 12 : 10),+ padding: EdgeInsets.only(+ top: terminal ? cell.height : 10,+ ),child: Text(_displayText(text),maxLines: 4,@@ -532,29 +572,32 @@ class _AgentPreview extends StatelessWidget {],if (record?.hasContent != true && waiting == null)Padding(- padding: const EdgeInsets.only(bottom: 24),+ padding: EdgeInsets.only(bottom: terminal ? cell.height : 24),child: Text('No recent session text available.', style: muted),),- const SizedBox(height: 8),+ if (!terminal) const SizedBox(height: 8),if (project?.cwd case final cwd?) Text(cwd, style: muted),if (project?.branch case final branch?)- Padding(- padding: EdgeInsets.only(top: terminal ? 8 : 4),- child: Row(- children: [- const Icon(- LucideIcons.gitBranch300,- size: 12,- color: Colors.white54,- ),- const SizedBox(width: 6),- Expanded(child: Text(branch, style: muted)),- ],+ if (terminal)+ Text('git: $branch', style: muted)+ else+ Padding(+ padding: const EdgeInsets.only(top: 4),+ child: Row(+ children: [+ Icon(+ LucideIcons.gitBranch300,+ size: 12,+ color: muted.color,+ ),+ const SizedBox(width: 6),+ Expanded(child: Text(branch, style: muted)),+ ],+ ),),- ),if (record?.receivedAt case final at?)Padding(- padding: EdgeInsets.only(top: terminal ? 12 : 8),+ padding: EdgeInsets.only(top: terminal ? cell.height : 8),child: Text('${offline || record?.unavailable == true ? 'Saved text · ' : ''}Received ${TimeOfDay.fromDateTime(at).format(context)}',style: muted,@@ -573,22 +616,32 @@ class _Section extends StatelessWidget {final bool terminal;@overrideWidget build(BuildContext context) {- TerminalFontScope.watch(context);+ grid.AppTheme.watch(context);+ final theme = terminalThemeFor(+ grid.AppTheme.palette.value,+ terminalThemeStore.value,+ );return Padding(- padding: const EdgeInsets.only(bottom: 24),+ padding: EdgeInsets.only(+ bottom: terminal ? terminalCellSizeOf(context).height : 24,+ ),child: Column(crossAxisAlignment: CrossAxisAlignment.start,children: [Text(label,style: terminal- ? terminalContentStyle(color: kBoxFaint)+ ? terminalContentStyle(+ color: theme.foreground.withValues(alpha: .54),+ ): _muted.copyWith(fontWeight: FontWeight.w500),),- SizedBox(height: terminal ? 8 : 7),+ if (!terminal) const SizedBox(height: 7),Text(_displayText(text),- style: terminal ? terminalContentStyle() : _body,+ style: terminal+ ? terminalContentStyle(color: theme.foreground)+ : _body,maxLines: maxLines,overflow: maxLines == null ? null : TextOverflow.ellipsis,),diff --git a/desktop/lib/widgets/swarm_switcher.dart b/desktop/lib/widgets/swarm_switcher.dartindex 2843a98cb..78290eab5 100644--- a/desktop/lib/widgets/swarm_switcher.dart+++ b/desktop/lib/widgets/swarm_switcher.dart@@ -12,6 +12,8 @@ import '../shortcuts/keymap.dart';import 'box_chrome.dart';import 'prompt_context.dart';import '../terminal/terminal_text.dart';+import '../terminal/terminal_theme.dart';+import '../terminal/terminal_theme_store.dart';import 'search_result_text.dart';import '../shared/theme/app_theme.dart' as grid;@@ -20,7 +22,6 @@ import '../state/app_state.dart';import '../state/swarm_navigation.dart';import '../state/swarm_search.dart';import '../state/harness_sessions.dart' show harnessActivityAge;-import '../shared/theme/prompt_style.dart';import '../store/store_mark.dart';import 'engine_identity.dart';import 'swarm_icon.dart';@@ -547,8 +548,13 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {@overrideWidget build(BuildContext context) {- TerminalFontScope.watch(context);+ grid.AppTheme.watch(context);+ final theme = terminalThemeFor(+ grid.AppTheme.palette.value,+ terminalThemeStore.value,+ );final scale = MediaQuery.textScalerOf(context);+ final cell = widget.bios ? terminalCellSizeOf(context) : Size.zero;final acceptKey = effectiveCommandHint(context,'picker.accept',@@ -582,13 +588,9 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {stacked: stacked,);if (widget.bios) {- // Two terminal lines, a 4 px title/context gap, and 12 px above- // and below each session keep adjacent entries distinct.- _rowHeight =- scale.scale(terminalFontStore.size) *- terminalFontStore.value.height *- 2 +- 28;+ // A name, its context, then one blank terminal row. Only the name+ // receives the selection bar, exactly as in New Harness.+ _rowHeight = cell.height * 3;}final height = widget.fitRows? _fittedHeight(@@ -624,9 +626,11 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {alreadyHere,highlighted ? (search.canAccept, search.actionLabel(row)) : null,_rowHeight,+ cell,compactAction,grid.AppType.monoFamily,grid.AppTheme.palette.value,+ widget.bios ? theme : null,acceptKey,widget.terminal,stacked,@@ -640,143 +644,155 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {child: previous.child,);}- final tile = ListTile(- key: ValueKey(row.id),- minTileHeight: _rowHeight,- enabled: canSubmit,- onFocusChange: (focused) {- if (focused) _focusResult(row.id);- },- selected: highlighted,- selectedColor: Colors.white,- hoverColor: Colors.transparent,- // BoxRowHighlight draws the selection, the same- // in both modes of the box.- selectedTileColor: Colors.transparent,- shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(widget.terminal ? 0 : 6),- ),- dense: true,- visualDensity: VisualDensity.compact,- minVerticalPadding: 0,- horizontalTitleGap: widget.bios ? 12 : 10,- minLeadingWidth: 20,- contentPadding: EdgeInsets.symmetric(- horizontal: widget.bios ? 16 : 10,- ),- // The dock uses its full-row highlight for- // selection; prefixes only appear in the input.- leading: widget.bios- ? row.isCreate- ? Icon(- LucideIcons.plus300,- size: terminalFontStore.size * 1.25,- color: grid.AppPalette.swarmAccent,- )- : row.agentId != null- ? EngineMark(- engine: row.engine,- size: terminalFontStore.size * 1.25,- enabled: canSubmit,- )- : null- : widget.terminal- ? null- : Row(- mainAxisSize: MainAxisSize.min,- children: [- // Every command wore the same ⌘: a column- // of identical marks says nothing. Its- // own key, at the right, says something.- row.isCommand || row.pickerQuery != null- ? const SizedBox(width: 2)- : row.isCreate- ? const Icon(- LucideIcons.plus300,- size: 18,- color: Colors.white70,- )- : row.isStore- ? StoreMark(size: 20, enabled: canSubmit)- : row.agentId != null ||- (row.isSwarm && row.members.length == 1)- ? EngineMark(- engine: row.engine,- size: 20,- enabled: canSubmit,- )- : row.isProject- ? const Icon(- LucideIcons.folderOpen,- size: 18,- color: Colors.white60,- )- : row.isMachine- ? const Icon(- LucideIcons.monitor300,- size: 18,- color: Colors.white60,- )- : const SwarmIcon(size: 20, color: Colors.white60),- ],+ final tile = widget.bios+ ? Semantics(+ selected: highlighted,+ enabled: canSubmit,+ button: true,+ child: InkWell(+ key: ValueKey(row.id),+ onFocusChange: (focused) {+ if (focused) _focusResult(row.id);+ },+ onTap: canSubmit ? () => _submit(row) : null,+ hoverColor: Colors.transparent,+ focusColor: Colors.transparent,+ highlightColor: Colors.transparent,+ splashFactory: NoSplash.splashFactory,+ child: _SearchRowContent(+ search: search,+ row: row,+ terminal: true,+ stacked: true,+ bios: true,+ highlighted: highlighted,+ enabled: canSubmit,+ cellSize: cell,+ activityAge: activityAge,+ ),),- title: _SearchRowContent(- search: search,- row: row,- terminal: widget.terminal,- stacked: stacked,- bios: widget.bios,- highlighted: highlighted,- activityAge: activityAge,- ),- trailing: widget.bios- ? null- : widget.terminal- ? (highlighted+ )+ : ListTile(+ key: ValueKey(row.id),+ minTileHeight: _rowHeight,+ enabled: canSubmit,+ onFocusChange: (focused) {+ if (focused) _focusResult(row.id);+ },+ selected: highlighted,+ selectedColor: Colors.white,+ hoverColor: Colors.transparent,+ // BoxRowHighlight draws the selection, the same+ // in both modes of the box.+ selectedTileColor: Colors.transparent,+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(+ widget.terminal ? 0 : 6,+ ),+ ),+ dense: true,+ visualDensity: VisualDensity.compact,+ minVerticalPadding: 0,+ horizontalTitleGap: 10,+ minLeadingWidth: 20,+ contentPadding: const EdgeInsets.symmetric(horizontal: 10),+ // The dock uses its full-row highlight for+ // selection; prefixes only appear in the input.+ leading: widget.terminal+ ? null+ : Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ // Every command wore the same ⌘: a column+ // of identical marks says nothing. Its+ // own key, at the right, says something.+ row.isCommand || row.pickerQuery != null+ ? const SizedBox(width: 2)+ : row.isCreate+ ? const Icon(+ LucideIcons.plus300,+ size: 18,+ color: Colors.white70,+ )+ : row.isStore+ ? StoreMark(size: 20, enabled: canSubmit)+ : row.agentId != null ||+ (row.isSwarm && row.members.length == 1)+ ? EngineMark(+ engine: row.engine,+ size: 20,+ enabled: canSubmit,+ )+ : row.isProject+ ? const Icon(+ LucideIcons.folderOpen,+ size: 18,+ color: Colors.white60,+ )+ : row.isMachine+ ? const Icon(+ LucideIcons.monitor300,+ size: 18,+ color: Colors.white60,+ )+ : const SwarmIcon(+ size: 20,+ color: Colors.white60,+ ),+ ],+ ),+ title: _SearchRowContent(+ search: search,+ row: row,+ terminal: widget.terminal,+ stacked: stacked,+ ),+ trailing: widget.terminal+ ? (highlighted+ ? Text(+ acceptKey ?? '',+ key: const ValueKey('swarm-row-action'),+ style: boxMonoStyle(color: kBoxFaint),+ )+ : row.shortcut == null+ ? null+ : Text(+ row.shortcut!,+ style: boxMonoStyle(color: kBoxFaint),+ ))+ : alreadyHere && search.placement == null? Text(- acceptKey ?? '',- key: const ValueKey('swarm-row-action'),- style: boxMonoStyle(color: kBoxFaint),+ 'Already added',+ style: boxMonoStyle(color: Colors.white54),+ )+ : highlighted+ ? ConstrainedBox(+ constraints: BoxConstraints(+ maxWidth:+ 170 *+ scale.scale(grid.AppType.bodySize) /+ grid.AppType.bodySize,+ ),+ child: TextButton(+ key: const ValueKey('swarm-row-action'),+ onPressed: search.canAccept ? _submit : null,+ style: TextButton.styleFrom(+ foregroundColor: Colors.white,+ ),+ child: SwarmSearchActionLabel(+ search.actionLabel(row),+ compact: compactAction,+ ),+ ),): row.shortcut == null? null: Text(row.shortcut!,- style: boxMonoStyle(color: kBoxFaint),- ))- : alreadyHere && search.placement == null- ? Text(- 'Already added',- style: boxMonoStyle(color: Colors.white54),- )- : highlighted- ? ConstrainedBox(- constraints: BoxConstraints(- maxWidth:- 170 *- scale.scale(grid.AppType.bodySize) /- grid.AppType.bodySize,- ),- child: TextButton(- key: const ValueKey('swarm-row-action'),- onPressed: search.canAccept ? _submit : null,- style: TextButton.styleFrom(- foregroundColor: Colors.white,- ),- child: SwarmSearchActionLabel(- search.actionLabel(row),- compact: compactAction,- ),- ),- )- : row.shortcut == null- ? null- : Text(- row.shortcut!,- style: boxMonoStyle(color: Colors.white60),- ),- onTap: canSubmit ? () => _submit(row) : null,- );+ style: boxMonoStyle(color: Colors.white60),+ ),+ onTap: canSubmit ? () => _submit(row) : null,+ );_rowWidgets[row.id] = (presentation: presentation,child: MouseRegion(@@ -789,23 +805,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {}},child: widget.bios- ? Material(- color: highlighted- ? Colors.white.withValues(alpha: .12)- : Colors.transparent,- child: row.isCreate- ? DecoratedBox(- decoration: BoxDecoration(- border: Border(- bottom: BorderSide(- color: Colors.white.withValues(alpha: .12),- ),- ),- ),- child: tile,- )- : tile,- )+ ? tile: BoxRowHighlight(terminal: widget.terminal,highlighted: highlighted,@@ -847,16 +847,26 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {: search.adding? 'No matching harnesses': 'No matching results',- style: grid.AppType.monoLabel(- fontWeight: FontWeight.w400,- color: Colors.white60,- ),+ style: widget.bios+ ? terminalContentStyle(+ color: theme.foreground.withValues(+ alpha: .54,+ ),+ )+ : grid.AppType.monoLabel(+ fontWeight: FontWeight.w400,+ color: Colors.white60,+ ),),): Padding(padding: EdgeInsets.only(- top: 8,- bottom: pinCreate ? 0 : 8,+ top: widget.bios ? 0 : 8,+ bottom: pinCreate+ ? 0+ : widget.bios+ ? cell.height+ : 8,),child: FocusTraversalOrder(order: const NumericFocusOrder(1),@@ -865,7 +875,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {child: ListView.builder(key: const ValueKey('swarm-search-result-list'),padding: EdgeInsets.symmetric(- horizontal: widget.bios ? 12 : 8,+ horizontal: widget.bios ? cell.width : 8,),controller: _scroll,// The dock only shows a few rows. Building the@@ -891,9 +901,11 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {),if (unavailable) ...[SizedBox(- height: 48,+ height: widget.bios ? cell.height * 2 : 48,child: Padding(- padding: const EdgeInsets.symmetric(horizontal: 12),+ padding: EdgeInsets.symmetric(+ horizontal: widget.bios ? cell.width * 4 : 12,+ ),child: Row(children: [Expanded(@@ -907,10 +919,16 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {: 'No room to open this ${selected.isSwarm || selected.isGroup ? 'group' : 'harness'}',maxLines: 1,overflow: TextOverflow.ellipsis,- style: grid.AppType.monoLabel(- fontWeight: FontWeight.w400,- color: Colors.white60,- ),+ style: widget.bios+ ? terminalContentStyle(+ color: theme.foreground.withValues(+ alpha: .54,+ ),+ )+ : grid.AppType.monoLabel(+ fontWeight: FontWeight.w400,+ color: Colors.white60,+ ),),),],@@ -942,7 +960,8 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {VerticalDivider(width: 1,thickness: 1,- color: Colors.white.withValues(alpha: .16),+ color: (widget.bios ? theme.foreground : Colors.white)+ .withValues(alpha: .16),)elseconst SizedBox(width: 8),@@ -979,7 +998,14 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {children: [Expanded(child: content),Padding(- padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),+ padding: widget.bios+ ? EdgeInsets.fromLTRB(+ cell.width,+ 0,+ cell.width,+ cell.height,+ )+ : const EdgeInsets.fromLTRB(8, 0, 8, 8),child: SizedBox(height: _rowHeight,child: buildRow(context, 0),@@ -1021,7 +1047,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {}// Typing changes the match text even when the row, its controls, and its focus-// state stay the same. Listen here so the cached ListTile can keep that state.+// state stay the same. Listen here so the cached row can keep that state.class _SearchRowContent extends StatefulWidget {const _SearchRowContent({required this.search,@@ -1030,6 +1056,8 @@ class _SearchRowContent extends StatefulWidget {required this.stacked,this.bios = false,this.highlighted = false,+ this.enabled = true,+ this.cellSize,this.activityAge,});@@ -1039,6 +1067,8 @@ class _SearchRowContent extends StatefulWidget {final bool stacked;final bool bios;final bool highlighted;+ final bool enabled;+ final Size? cellSize;final String? activityAge;@override@@ -1085,69 +1115,93 @@ class _SearchRowContentState extends State<_SearchRowContent> {final row = widget.row;final matches = searchResultMatches(row, swarmQueryTerms(_query.$1));if (widget.bios) {+ final theme = terminalThemeFor(+ grid.AppTheme.palette.value,+ terminalThemeStore.value,+ );+ final muted = theme.foreground.withValues(alpha: .54);final style = terminalContentStyle(- color: row.isCreate- ? grid.AppPalette.swarmAccent- : widget.highlighted- ? Colors.white- : Colors.white70,+ color: !widget.enabled+ ? theme.foreground.withValues(alpha: .28)+ : row.isCreate+ ? theme.cursor+ : theme.foreground,);+ final cell = widget.cellSize!;final data = row.promptContext;+ final detail = data == null+ ? row.terminalDetail ?? row.detail+ : [+ if (data.harness?.isNotEmpty == true) data.harness!,+ if (data.leading?.isNotEmpty == true) data.leading!,+ if (data.machine?.isNotEmpty == true) '@ ${data.machine}',+ if (data.project?.isNotEmpty == true) '/ ${data.project}',+ if (data.branch?.isNotEmpty == true) 'git: ${data.branch}',+ ].join(' ');return Semantics(label: row.isCreate? 'New Harness': '${row.title}\n${row.terminalDetail ?? row.detail}''${widget.activityAge == null ? '' : ', Last active ${widget.activityAge} ago'}',excludeSemantics: true,- child: row.isCreate- ? Text('New Harness', style: style)- : Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.stretch,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Container(+ key: ValueKey('swarm-search-line:${row.id}'),+ height: cell.height,+ color: widget.highlighted ? theme.selection : Colors.transparent,+ padding: EdgeInsets.symmetric(horizontal: cell.width),+ child: Row(children: [- Row(- children: [- Expanded(- child: SearchResultText(- row.title,- matches: matches.where((match) => match.title),- style: style,- ),- ),- if (widget.activityAge case final age?) ...[- const SizedBox(width: 12),- Tooltip(- message:- 'Last active ${row.lastActivityAt!.toLocal()}',- child: Text(- age,- style: terminalContentStyle(color: Colors.white38),+ // Match Cmd-N's empty two-cell gutter. Agent identities are+ // text in the context line, never logos or icon-font glyphs.+ SizedBox(width: cell.width * 2),+ Expanded(+ child: row.isCreate+ ? Text('New Harness', style: style, maxLines: 1)+ : SearchResultText(+ row.title,+ matches: matches.where((match) => match.title),+ style: style,),- ),- ],- ],),- if (data != null || row.detail.isNotEmpty)- const SizedBox(height: 4),- if (data != null)- PromptContextView(- contextData: PromptContext(- machine: data.machine,- project: data.project,- branch: data.branch,- leading: data.leading,+ if (widget.activityAge case final age?) ...[+ SizedBox(width: cell.width * 2),+ Tooltip(+ message: 'Last active ${row.lastActivityAt!.toLocal()}',+ child: Text(+ age,+ maxLines: 1,+ style: terminalContentStyle(+ color: theme.foreground.withValues(alpha: .38),+ ),),- textStyle: terminalContentStyle(color: kBoxFaint),- matches: matches.where((match) => !match.title),- )- else if (row.detail.isNotEmpty)- SearchResultText(- row.detail,- matches: matches.where((match) => !match.title),- style: style.copyWith(color: kBoxFaint),),+ ],],),+ ),+ if (!row.isCreate && detail.isNotEmpty)+ Padding(+ padding: EdgeInsets.only(+ left: cell.width * 3,+ right: cell.width,+ ),+ child: SizedBox(+ height: cell.height,+ child: Align(+ alignment: Alignment.centerLeft,+ child: SearchResultText(+ detail,+ matches: matches.where((match) => !match.title),+ style: terminalContentStyle(color: muted),+ ),+ ),+ ),+ ),+ ],+ ),);}final title = SearchResultText(diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dartindex b4e3f97c9..9dd15616d 100644--- a/desktop/lib/widgets/terminal_panel.dart+++ b/desktop/lib/widgets/terminal_panel.dart@@ -1,7 +1,6 @@import 'pull_request_badge.dart';import '../shared/theme/prompt_style.dart';import 'prompt_context.dart';-import '../sharing/share_harness_dialog.dart';import 'dart:async';import 'dart:math' as math;@@ -90,10 +89,7 @@ class TerminalPanel extends StatefulWidget {/// Takes this tile off the grid. Null when the terminal is the whole window,/// where there is nothing to close it back to.final VoidCallback? onClose;- final VoidCallback? onRestart;- /// Forks this harness — a second agent with its history (fork_agent_dialog.dart).- final VoidCallback? onFork;final VoidCallback? onDelete;final VoidCallback? onToggleZoom;@@ -166,8 +162,6 @@ class TerminalPanel extends StatefulWidget {this.notice,this.onToggleComposer,this.onClose,- this.onRestart,- this.onFork,this.onDelete,this.onToggleZoom,this.zoomed = false,@@ -1802,8 +1796,6 @@ class _TerminalPanelState extends State<TerminalPanel>project: agent == null ? null : machine?.projectOf(agent),compact: widget.compactHeader,close: widget.onClose != null,- restart: widget.onRestart != null,- fork: widget.onFork != null,delete: widget.onDelete != null,composer: widget.composerVisible,toggleComposer: widget.onToggleComposer != null,@@ -1825,18 +1817,10 @@ class _TerminalPanelState extends State<TerminalPanel>? null: () => widget.onToggleZoom?.call(),onClose: widget.onClose == null ? null : () => widget.onClose?.call(),- onRestart: widget.onRestart == null- ? null- : () => widget.onRestart?.call(),- onFork: widget.onFork == null ? null : () => widget.onFork?.call(),onDelete: widget.onDelete == null? null: () => widget.onDelete?.call(),onReconnect: () => unawaited(_takeControl()),- composerVisible: widget.composerVisible,- onToggleComposer: widget.onToggleComposer == null- ? null- : () => widget.onToggleComposer?.call(),paneDrag: widget.paneDrag,);}@@ -1850,8 +1834,6 @@ class _TerminalHeader extends StatelessWidget {final TerminalNotice? notice;final bool readOnly;final VoidCallback? onClose;- final VoidCallback? onRestart;- final VoidCallback? onFork;/// Ends the agent (with a confirmation), as the rail's row menu does. Null/// where the pane cannot name a live agent to end.@@ -1863,8 +1845,6 @@ class _TerminalHeader extends StatelessWidget {final bool compact;final VoidCallback? onToggleZoom;final bool zoomed;- final VoidCallback? onToggleComposer;- final bool composerVisible;/// This strip's drag gesture, or null when there is nothing to drag.///@@ -1882,21 +1862,26 @@ class _TerminalHeader extends StatelessWidget {this.notice,this.readOnly = false,this.onClose,- this.onRestart,- this.onFork,this.onDelete,required this.onReconnect,this.compact = false,this.onToggleZoom,this.zoomed = false,this.paneDrag,- this.onToggleComposer,- this.composerVisible = false,});@override- Widget build(BuildContext context) {+ Widget build(BuildContext context) =>+ MediaQuery.withNoTextScaling(child: Builder(builder: _buildHeader));++ Widget _buildHeader(BuildContext context) {TerminalFontScope.watch(context);+ final titleStyle = terminalContentStyle(+ color: terminalThemeFor(+ grid.AppTheme.palette.value,+ terminalThemeStore.value,+ ).foreground,+ );final color = switch (session.status) {TerminalSessionStatus.controlling => AppColors.success,TerminalSessionStatus.opening ||@@ -1970,335 +1955,297 @@ class _TerminalHeader extends StatelessWidget {if (profile != null) 'Codex profile: $profile','Double-click to rename',].join('\n');- // A terminal has no prompt to compose a message for — a shell reads keys,- // and the composer's Enter-to-send would be a line nobody asked for.- final remoteComposer =- machine != null &&- !machine.isLocalMachine &&- !isTerminalEngine(session.engineId)- ? onToggleComposer- : null;// Reserve space for the visible model name and the pane controls.// Engines without a picker keep their existing header width.- final showModelPicker = !readOnly && modelPickerSupports(session.engineId);+ final showModelPicker =+ !compact && !readOnly && modelPickerSupports(session.engineId);// The picker: a model id up to 220px, its arrow and padding.final pickerWidth = showModelPicker ? 250.0 : 0.0;- // The model, then the one ⋮ menu that holds every pane action.- final actionsWidth = 36.0 + pickerWidth;+ // Reserve the same measured columns used by the three ASCII controls.+ final actionsWidth = PaneHeaderActions.widthOf(context) + pickerWidth;// A fork says so first: "forked from X" is the one fact about this pane// that the folder and the branch — shared with its source — cannot tell.final forkedFrom = agent?.forkedFrom;- final strip = PaneHeaderHover(- child: SizedBox(- height: compact ? 38 : 46,- child: Padding(- padding: const EdgeInsets.symmetric(horizontal: _stripPadding),- child: LayoutBuilder(- builder: (context, constraints) {- final scale = grid.appTextScaleOf(context);- final narrow = constraints.maxWidth < 560 * math.max(1, scale);- // Keep PR state visible before spending space on branch prose.- // A compact badge also fits beside the compact action menu.- final showPr =- agent != null &&- project?.shownBranch != null &&- constraints.maxWidth >= 360 * math.max(1, scale);- final badgeWidth = showPr ? (narrow ? 150.0 : 180.0) : 0.0;- // The room the left side needs: the mark, the whole name as it will be drawn, and- // the status beside it — capped at 45% so a very long name still leaves the right- // side most of the header.- double titleRoom() {- final name = TextPainter(- text: TextSpan(- text: session.agentName,- style: grid.AppType.monoLabel(fontWeight: FontWeight.w600),- ),- textDirection: TextDirection.ltr,- textScaler: MediaQuery.textScalerOf(context),- maxLines: 1,- )..layout();- final width = name.width;- name.dispose();- return math.min(- 17 + 10 + width + 8 + (status == null ? 16 : 120) + 8,- constraints.maxWidth * .45,- );- }-- final rightWidth = narrow- ? math.max(- (showModelPicker ? 100.0 : 28.0) + badgeWidth,- constraints.maxWidth * .36,- )- : math.max(- actionsWidth + badgeWidth,- // Everything the name does not use. A fixed 55% left the folder and branch- // shortened to "…" beside a short name with half the header empty.- constraints.maxWidth - titleRoom(),- );- return Row(- children: [- if (agent != null)- EngineMark.forAgent(agent, size: 17)- else- EngineMark(engine: session.engineId, size: 17),- // Icon and name, the same as every other pane (owner,- // 2026-09-15): a harness agent is its harness here, and the- // engine it runs on is the dialog's and the tooltip's to say.- const SizedBox(width: 10),- Expanded(- child: Row(- children: [- Flexible(- child: Tooltip(- message: identityDetail,- waitDuration: const Duration(milliseconds: 700),- child: GestureDetector(- behavior: HitTestBehavior.opaque,- onDoubleTap: () => unawaited(- showAgentRenameDialog(- context,- notifier,- session.machineId,- session.agentId,- session.agentName,- ),- ),- child: Text(+ final strip = SizedBox(+ height: compact ? 38 : 46,+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: _stripPadding),+ child: LayoutBuilder(+ builder: (context, constraints) {+ final scale = grid.appTextScaleOf(context);+ final narrow = constraints.maxWidth < 560 * math.max(1, scale);+ // Workspace panes show PR state once in the main status bar.+ // Standalone terminals retain their own PR badge.+ final showPr =+ !compact &&+ agent != null &&+ project?.shownBranch != null &&+ constraints.maxWidth >= 360 * math.max(1, scale);+ final badgeWidth = showPr ? (narrow ? 150.0 : 180.0) : 0.0;+ // The room the left side needs: the mark, the whole name as it will be drawn, and+ // the status beside it — capped at 45% so a very long name still leaves the right+ // side most of the header.+ double titleRoom() {+ final name = TextPainter(+ text: TextSpan(text: session.agentName, style: titleStyle),+ textDirection: TextDirection.ltr,+ textScaler: MediaQuery.textScalerOf(context),+ maxLines: 1,+ )..layout();+ final width = name.width;+ name.dispose();+ return math.min(+ 17 + 10 + width + 8 + (status == null ? 16 : 120) + 8,+ constraints.maxWidth * .45,+ );+ }++ final desiredRightWidth = narrow+ ? math.max(+ PaneHeaderActions.widthOf(context) ++ (showModelPicker ? 64.0 : 0.0) ++ badgeWidth,+ constraints.maxWidth * .36,+ )+ : math.max(+ actionsWidth + badgeWidth,+ // Everything the name does not use. A fixed 55% left the folder and branch+ // shortened to "…" beside a short name with half the header empty.+ constraints.maxWidth - titleRoom(),+ );+ // The name/status retain space while model and project text yield.+ final rightWidth = math.min(+ desiredRightWidth,+ math.max(+ PaneHeaderActions.widthOf(context),+ constraints.maxWidth - 99,+ ),+ );+ return Row(+ children: [+ if (agent != null)+ EngineMark.forAgent(agent, size: 17)+ else+ EngineMark(engine: session.engineId, size: 17),+ // Icon and name, the same as every other pane (owner,+ // 2026-09-15): a harness agent is its harness here, and the+ // engine it runs on is the dialog's and the tooltip's to say.+ const SizedBox(width: 10),+ Expanded(+ child: Row(+ children: [+ Flexible(+ child: Tooltip(+ message: identityDetail,+ waitDuration: const Duration(milliseconds: 700),+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onDoubleTap: () => unawaited(+ showAgentRenameDialog(+ context,+ notifier,+ session.machineId,+ session.agentId,session.agentName,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: grid.AppType.monoLabel(- color: AppColors.text,- fontWeight: FontWeight.w600,- ),),),+ child: Text(+ session.agentName,+ key: const ValueKey('terminal-pane-title'),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: titleStyle,+ ),),),- if (status != null || !compact)- const SizedBox(width: 8),- if (status != null && narrow)- Tooltip(- message: '${status.label}: ${status.detail}',- child: IconButton(- tooltip: status.actionLabel ?? status.label,- onPressed: statusAction,- icon: Icon(status.icon, size: 14),- style: IconButton.styleFrom(- foregroundColor: color,- disabledForegroundColor: color,- fixedSize: const Size(28, 28),- minimumSize: const Size(28, 28),- padding: EdgeInsets.zero,- tapTargetSize: MaterialTapTargetSize.shrinkWrap,- ),+ ),+ if (status != null || !compact) const SizedBox(width: 8),+ if (status != null && narrow)+ Tooltip(+ message: '${status.label}: ${status.detail}',+ child: IconButton(+ tooltip: status.actionLabel ?? status.label,+ onPressed: statusAction,+ icon: Icon(status.icon, size: 14),+ style: IconButton.styleFrom(+ foregroundColor: color,+ disabledForegroundColor: color,+ fixedSize: const Size(28, 28),+ minimumSize: const Size(28, 28),+ padding: EdgeInsets.zero,+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,),- )- else if (status != null)- ConstrainedBox(- constraints: BoxConstraints(- maxWidth: math.max(- 0,- math.min(- constraints.maxWidth * .22,- constraints.maxWidth - actionsWidth - 110,- ),+ ),+ )+ else if (status != null)+ ConstrainedBox(+ constraints: BoxConstraints(+ maxWidth: math.max(+ 0,+ math.min(+ constraints.maxWidth * .22,+ constraints.maxWidth - actionsWidth - 110,),),- child: Align(- alignment: Alignment.centerLeft,- child: Tooltip(- message: status.detail,- child: TextButton(- onPressed: statusAction,- style: TextButton.styleFrom(- foregroundColor: color,- disabledForegroundColor: AppColors.textSoft,- minimumSize: Size.zero,- tapTargetSize:- MaterialTapTargetSize.shrinkWrap,- padding: const EdgeInsets.symmetric(- horizontal: 6,- vertical: 4,- ),+ ),+ child: Align(+ alignment: Alignment.centerLeft,+ child: Tooltip(+ message: status.detail,+ child: TextButton(+ onPressed: statusAction,+ style: TextButton.styleFrom(+ foregroundColor: color,+ disabledForegroundColor: AppColors.textSoft,+ minimumSize: Size.zero,+ tapTargetSize:+ MaterialTapTargetSize.shrinkWrap,+ padding: const EdgeInsets.symmetric(+ horizontal: 6,+ vertical: 4,),- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- Icon(status.icon, size: 14),- const SizedBox(width: 6),- Flexible(- child: Text(- // The chip names the STATE; what- // pressing it does is in the tooltip- // and in `actionLabel`. "Link- // required" that can be pressed reads- // better than a bare verb where every- // neighbour is a status.- status.label,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: grid.AppType.monoLabel(- fontWeight: FontWeight.w400,- ),+ ),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Icon(status.icon, size: 14),+ const SizedBox(width: 6),+ Flexible(+ child: Text(+ // The chip names the STATE; what+ // pressing it does is in the tooltip+ // and in `actionLabel`. "Link+ // required" that can be pressed reads+ // better than a bare verb where every+ // neighbour is a status.+ status.label,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: grid.AppType.monoLabel(+ fontWeight: FontWeight.w400,),),- ],- ),+ ),+ ],),),),- )- else if (!compact)- Padding(- padding: const EdgeInsets.all(4),- child: Icon(Icons.circle, size: 8, color: color),),- ],- ),+ )+ else if (!compact)+ Padding(+ padding: const EdgeInsets.all(4),+ child: Icon(Icons.circle, size: 8, color: color),+ ),+ ],),- const SizedBox(width: 8),- // Which of the three paths carries this pane's bytes. Absent for a local machine's own- // terminal, which has no such distinction and so gets no badge.- //- // The wire word and the word a person reads differ for the middle state, deliberately:- // the CLI sends 'turn' (it is a TURN allocation) but both middle and last are relays to- // a reader, so they read as "relay" and "ws". 'relay' on the wire kept its original- // meaning — the backend WebSocket — so an older CLI is never mislabelled.- if (!compact && !narrow && session.linkMode != null)- Padding(- padding: const EdgeInsets.symmetric(horizontal: 2),- child: _LinkModeMark(mode: session.linkMode!),- ),- ConstrainedBox(- constraints: BoxConstraints(maxWidth: rightWidth),- child: PaneHeaderActions(- trailing: showPr- ? ConstrainedBox(- constraints: BoxConstraints(maxWidth: badgeWidth),- child: PullRequestBadge(- compact: narrow,- identity: (- session.machineId,- agent.id,- project?.cwd,- project?.shownBranch,- ),- read: () => notifier.readAgentPullRequest(- session.machineId,- agent.id,- ),- ),- )- : null,- // One ⋮ menu for the pane's actions at every width, not a row of icons.- compact: true,- // Keep the current model visible, including while the- // terminal reconnects, without shifting the other controls.- modelPicker: showModelPicker- ? GridModelPicker(+ ),+ const SizedBox(width: 8),+ // Which of the three paths carries this pane's bytes. Absent for a local machine's own+ // terminal, which has no such distinction and so gets no badge.+ //+ // The wire word and the word a person reads differ for the middle state, deliberately:+ // the CLI sends 'turn' (it is a TURN allocation) but both middle and last are relays to+ // a reader, so they read as "relay" and "ws". 'relay' on the wire kept its original+ // meaning — the backend WebSocket — so an older CLI is never mislabelled.+ if (!compact && !narrow && session.linkMode != null)+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 2),+ child: _LinkModeMark(mode: session.linkMode!),+ ),+ ConstrainedBox(+ constraints: BoxConstraints(maxWidth: rightWidth),+ child: PaneHeaderActions(+ trailing: showPr+ ? ConstrainedBox(+ constraints: BoxConstraints(maxWidth: badgeWidth),+ child: PullRequestBadge(compact: narrow,- notifier: notifier,- machineId: session.machineId,- currentModel: agent?.gridModel,- webSearch: agent?.gridWebSearch,- engineLabel: session.engineId,- onSelected: (model) => unawaited(- notifier.retargetAgentToGridModel(- session.machineId,- session.agentId,- model.id,- gridName: model.grid,- ),+ identity: (+ session.machineId,+ agent.id,+ project?.cwd,+ project?.shownBranch,),- onUseOwnLogin: () => unawaited(- notifier.clearAgentGrid(- session.machineId,- session.agentId,- ),+ read: () => notifier.readAgentPullRequest(+ session.machineId,+ agent.id,),- // Discovery opens the local Models popover. Selection above- // continues to target this pane's existing session.- onRunLocalModel: () => unawaited(- notifier.runLocalModel(- context,- machineId: session.machineId,- ),+ ),+ )+ : null,+ // Keep the current model visible, including while the+ // terminal reconnects, without shifting the other controls.+ modelPicker: showModelPicker+ ? GridModelPicker(+ compact: narrow,+ notifier: notifier,+ machineId: session.machineId,+ currentModel: agent?.gridModel,+ webSearch: agent?.gridWebSearch,+ engineLabel: session.engineId,+ onSelected: (model) => unawaited(+ notifier.retargetAgentToGridModel(+ session.machineId,+ session.agentId,+ model.id,+ gridName: model.grid,),- )- : null,- onShare:- readOnly ||- notifier- .stateOf(session.machineId)- ?.machine- .isShared ==- true- ? null- : () => showShareHarnessDialog(- context,- notifier,- session.machineId,- session.agentId,- session.agentName,),- zoomed: zoomed,- onZoom: onToggleZoom,- onRestart: onRestart,- onFork: onFork,- onDelete: onDelete,- onClose: onClose,- terminal: isTerminalEngine(session.engineId),- onToggleComposer: remoteComposer,- composerVisible: composerVisible,- // A harness agent's viewer, shown or hidden from the- // pane it belongs to.- onToggleViewer:- agent?.viewerUrl == null && agent?.viewerError == null- ? null- : () => notifier.toggleViewerPane(- session.machineId,- agent!.id,+ onUseOwnLogin: () => unawaited(+ notifier.clearAgentGrid(+ session.machineId,+ session.agentId,+ ),+ ),+ // Discovery opens the local Models popover. Selection above+ // continues to target this pane's existing session.+ onRunLocalModel: () => unawaited(+ notifier.runLocalModel(+ context,+ machineId: session.machineId,+ ),+ ),+ )+ : null,+ zoomed: zoomed,+ onZoom: onToggleZoom,+ onDelete: onDelete,+ onClose: onClose,+ terminal: isTerminalEngine(session.engineId),+ details: compact || narrow+ ? null+ : Tooltip(+ message: [+ if (forkedFrom != null)+ 'Forked from ${forkedFrom.name}',+ if (project != null) project.cwd,+ ?project?.branchDetail,+ machineName,+ ].join('\n'),+ child: PromptContextView(+ contextData: PromptContext(+ // This computer goes without saying.+ machine: machine?.isLocalMachine == true+ ? null+ : machineName,+ // The folder as it was chosen and its repository's branch;+ // the full working folder is in the tooltip.+ project: narrow ? null : project?.label,+ // Not a branch Harness made up that waits for the+ // session's name, nor a commit an agent checked out.+ branch: narrow ? null : project?.shownBranch,+ leading: !narrow && forkedFrom != null+ ? 'forked from ${forkedFrom.name}'+ : null,+ ),),- viewerVisible:- agent != null &&- notifier.viewerPaneShown(session.machineId, agent.id),- viewerColor: agent == null- ? null- : agentIdentity(agent).color,- details: Tooltip(- message: [- if (forkedFrom != null)- 'Forked from ${forkedFrom.name}',- if (project != null) project.cwd,- ?project?.branchDetail,- machineName,- ].join('\n'),- child: PromptContextView(- contextData: PromptContext(- // This computer goes without saying.- machine: machine?.isLocalMachine == true- ? null- : machineName,- // The folder as it was chosen and its repository's branch;- // the full working folder is in the tooltip.- project: narrow ? null : project?.label,- // Not a branch Harness made up that waits for the- // session's name, nor a commit an agent checked out.- branch: narrow ? null : project?.shownBranch,- leading: !narrow && forkedFrom != null- ? 'forked from ${forkedFrom.name}'- : null,),- ),- ),- ),),- ],- );- },- ),+ ),+ ],+ );+ },),),);diff --git a/desktop/lib/widgets/web_pane_panel.dart b/desktop/lib/widgets/web_pane_panel.dartindex d0952874c..e900d03ce 100644--- a/desktop/lib/widgets/web_pane_panel.dart+++ b/desktop/lib/widgets/web_pane_panel.dart@@ -12,7 +12,7 @@ import '../state/app_state.dart';import '../state/terminal_pane.dart';import '../theme/app_theme.dart';import 'engine_identity.dart';-import 'pane_header_actions.dart';+import '../terminal/terminal_text.dart';import 'verdict_marks.dart';/// A domain harness's viewer, in a tile beside its agent's terminal.@@ -214,80 +214,80 @@ class _WebPanePanelState extends State<WebPanePanel> {);}- Widget _header(BuildContext context) {+ Widget _header(BuildContext context) =>+ MediaQuery.withNoTextScaling(child: Builder(builder: _buildHeader));++ Widget _buildHeader(BuildContext context) {+ TerminalFontScope.watch(context);final compact = widget.compactHeader;- return PaneHeaderHover(- child: SizedBox(- height: compact ? 38 : 46,- child: Padding(- padding: const EdgeInsets.symmetric(horizontal: 14),- child: Row(- children: [- EngineMark(- engine: widget.ownerEngine,- displayName: widget.ownerDisplayName,- size: 17,- ),- const SizedBox(width: 10),- // The name, and one status after it — ready, or what stands in- // the way, or where the work is — in the place a "Viewer" label- // would only repeat what the pane shows. A status, not a history.- Expanded(- child: Tooltip(- message: [widget.ownerName, ?widget.pane.url].join('\n'),- waitDuration: const Duration(milliseconds: 700),- child: Row(- children: [- Flexible(- child: Text(- widget.title,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: grid.AppType.monoLabel(- color: AppColors.text,- fontWeight: FontWeight.w600,- ),- ),+ return SizedBox(+ height: compact ? 38 : 46,+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: 14),+ child: Row(+ children: [+ EngineMark(+ engine: widget.ownerEngine,+ displayName: widget.ownerDisplayName,+ size: 17,+ ),+ const SizedBox(width: 10),+ // The name, and one status after it — ready, or what stands in+ // the way, or where the work is — in the place a "Viewer" label+ // would only repeat what the pane shows. A status, not a history.+ Expanded(+ child: Tooltip(+ message: [widget.ownerName, ?widget.pane.url].join('\n'),+ waitDuration: const Duration(milliseconds: 700),+ child: Row(+ children: [+ Flexible(+ child: Text(+ widget.title,+ key: const ValueKey('viewer-pane-title'),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: terminalContentStyle(color: AppColors.text),),- if (widget.verdict case final verdict?) ...[- Text(- ' · ',- style: grid.AppType.monoLabel(- color: AppColors.mutedStrong,- ),+ ),+ if (widget.verdict case final verdict?) ...[+ Text(+ ' · ',+ style: grid.AppType.monoLabel(+ color: AppColors.mutedStrong,),- Flexible(- child: VerdictStatus(- verdict: verdict,- working: widget.working,- ),+ ),+ Flexible(+ child: VerdictStatus(+ verdict: verdict,+ working: widget.working,),- ],+ ),],- ),+ ],),),- const SizedBox(width: 8),- // coverage:ignore-start- // Only a real webview's navigation sets _loading; none under test.- if (_loading)- const Padding(- padding: EdgeInsets.symmetric(horizontal: 6),- child: SizedBox(- width: 12,- height: 12,- child: CircularProgressIndicator(strokeWidth: 1.5),- ),+ ),+ const SizedBox(width: 8),+ // coverage:ignore-start+ // Only a real webview's navigation sets _loading; none under test.+ if (_loading)+ const Padding(+ padding: EdgeInsets.symmetric(horizontal: 6),+ child: SizedBox(+ width: 12,+ height: 12,+ child: CircularProgressIndicator(strokeWidth: 1.5),),- // coverage:ignore-end- _ViewerActions(- zoomed: widget.zoomed,- onReload: _controller == null ? null : _reload,- onZoom: widget.onToggleZoom,- onClose: widget.onClose,),- ],- ),+ // coverage:ignore-end+ _ViewerActions(+ zoomed: widget.zoomed,+ onReload: _controller == null ? null : _reload,+ onZoom: widget.onToggleZoom,+ onClose: widget.onClose,+ ),+ ],),),);@@ -334,9 +334,7 @@ class _WebPanePanelState extends State<WebPanePanel> {}}-/// Reload, zoom, close — the terminal header's controls, minus the one that-/// ends an agent, because a viewer has no agent to end. Same 28px buttons,-/// same hover reveal ([PaneHeaderHover]), so the two headers read as one kind.+/// Viewer navigation never stops the harness that owns it.class _ViewerActions extends StatelessWidget {const _ViewerActions({required this.zoomed,diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swiftindex 6b4c021d9..f96f12b67 100644--- a/desktop/macos/Runner/SwarmTitlebar.swift+++ b/desktop/macos/Runner/SwarmTitlebar.swift@@ -15,6 +15,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {private var canReopen = falseprivate var canFind = falseprivate var canClosePane = false+ private var paneActions: [String: Bool] = [:]private let historyMenu = NSMenu(title: "History")private var historyMenuNeedsRebuild = falseprivate var historyMenuIsOpen = false@@ -49,6 +50,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {self.canReopen = state["canReopen"] as? Bool == trueself.canFind = state["canFind"] as? Bool == trueself.canClosePane = state["canClosePane"] as? Bool == true+ self.paneActions = state["paneActions"] as? [String: Bool] ?? [:]self.canGoBack = state["canGoBack"] as? Bool == trueself.canGoForward = state["canGoForward"] as? Bool == trueself.updateHistory(state["history"] as? [[String: Any]] ?? [], closed: state["closedHistory"] as? [[String: Any]] ?? [])@@ -61,14 +63,13 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {result(nil)case "sessionsAnchor":guard let content = self.window?.contentViewController?.view else { result(nil); return }- let rect = self.strip.sessionsButton.convert(self.strip.sessionsButton.bounds, to: content)+ let rect = self.strip.contextButton.convert(self.strip.contextButton.bounds, to: content)result(["x": rect.midX,"y": content.isFlipped ? rect.midY : content.bounds.height - rect.midY,"reduceMotion": NSWorkspace.shared.accessibilityDisplayShouldReduceMotion,])case "sessionMinimized":- self.strip.sessionsButton.receiveSession()result(nil)case "playAlert":// A named macOS system sound. Every Mac has these, so no audio asset ships with the app,@@ -111,7 +112,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {}private func sendTabAction(_ method: String, arguments: Any?) {- guard ["select", "close", "new", "rename", "commands", "notifications", "store", "sessions", "models", "addAgent", "newAgent", "newTerminal", "cloneAgent", "restartAgent", "movePaneToTab", "runLocalModel", "splitRight", "splitDown", "zoomPane", "pinPane", "machineDestination", "machineAgent", "manageMachines", "machineList"].contains(method) else {+ guard ["focusedModel", "select", "close", "new", "rename", "commands", "notifications", "store", "sessions", "models", "addAgent", "newAgent", "newTerminal", "cloneAgent", "restartAgent", "shareAgent", "toggleViewer", "toggleComposer", "movePaneToTab", "runLocalModel", "splitRight", "splitDown", "zoomPane", "pinPane", "machineDestination", "machineAgent", "manageMachines", "machineList"].contains(method) else {channel.invokeMethod(method, arguments: arguments)return}@@ -154,9 +155,6 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {keymap = map// Mouse controls teach the effective shortcuts, including user remaps.strip.newButton.toolTip = "New Tab " + (map.hint(for: "swarm.new", context: "workspace") ?? "")- strip.machinesButton.toolTip = "Machines " + (map.hint(for: "machines.list", context: "workspace") ?? "")- strip.modelsButton.toolTip = "Models " + (map.hint(for: "models.list", context: "workspace") ?? "")- strip.storeButton.toolTip = "Harness Store " + (map.hint(for: "app.store", context: "workspace") ?? "")if let main = NSApp.mainMenu, let window {let menu = main as? HarnessKeymapMenu ?? HarnessKeymapMenu.replacing(main)if NSApp.mainMenu !== menu { NSApp.mainMenu = menu }@@ -258,6 +256,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {let symbols = ["new": "plus.square", "newAgent": "plus", "addAgent": "arrow.up.right.square", "newTerminal": "terminal","cloneAgent": "plus.square.on.square", "restartAgent": "arrow.clockwise",+ "shareAgent": "square.and.arrow.up","renameActive": "pencil", "closeActive": "xmark","splitRight": "rectangle.split.2x1", "splitDown": "rectangle.split.1x2","zoomPane": "viewfinder", "movePaneToTab": "arrow.right.square", "closePane": "xmark",@@ -284,6 +283,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")file.addItem(.separator())add(file, "New Tab", "t", "new")add(file, "Rename Tab", "r", "renameActive", [.command, .shift])@@ -307,10 +307,14 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {}if let view = main.item(withTitle: "View")?.submenu {view.addItem(.separator())+ add(view, "Harnesses", "", "sessions")add(view, "Harnesses Needing Input…", "i", "notifications", [.command, .shift])add(view, "Machines", "m", "machineList")add(view, "Models", "i", "models")add(view, "Machine Monitor", "", "manageMachines")+ view.addItem(.separator())+ add(view, "Toggle Viewer", "", "toggleViewer")+ add(view, "Toggle Message Composer", "", "toggleComposer")}installTerminalFindMenu(main)}@@ -454,6 +458,9 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {return machine.agents.contains(where: { $0.id == target["agentId"] && $0.canOpen })}let action = menuItem.representedObject as? String ?? ""+ if ["restartAgent", "shareAgent", "toggleViewer", "toggleComposer"].contains(action) {+ return actionsEnabled && paneActions[action] == true+ }if menuItem.action == #selector(machineAction(_:)) {return actionsEnabled && machines.contains(where: { $0.id == action })}@@ -883,106 +890,6 @@ private class SwarmIconButton: NSButton {}}-/// A quiet filled pill, with the Store's colorful mark as its focal point.-/// Drawing the content keeps the same spacing across AppKit button styles.-private final class SwarmStoreButton: SwarmIconButton {- var palette = SwarmNativePalette() { didSet { needsDisplay = true } }- var preferredWidth: CGFloat {- ceil((title as NSString).size(withAttributes: [- .font: font ?? SwarmTabStrip.uiFont(weight: .medium),- ]).width) + 48- }-- override func draw(_ dirtyRect: NSRect) {- let shape = NSBezierPath(roundedRect: bounds.insetBy(dx: 0.5, dy: 0.5),- xRadius: bounds.height / 2, yRadius: bounds.height / 2)- palette.workspace.setFill()- shape.fill()- let alpha: CGFloat = !isEnabled ? 0.04 : isHighlighted ? 0.24 : hovered ? 0.18 : 0.10- palette.accent.withAlphaComponent(alpha).setFill()- shape.fill()- palette.accent.withAlphaComponent(hasKeyboardFocus && isEnabled ? 0.85 : 0.12).setStroke()- shape.lineWidth = hasKeyboardFocus && isEnabled ? 1.5 : 1- shape.stroke()- image?.draw(in: NSRect(x: 12, y: (bounds.height - 16) / 2, width: 16, height: 16),- from: .zero, operation: .sourceOver, fraction: isEnabled ? 1 : 0.45,- respectFlipped: true, hints: [.interpolation: NSImageInterpolation.high])- let attributes: [NSAttributedString.Key: Any] = [- .font: font ?? SwarmTabStrip.uiFont(weight: .medium),- .foregroundColor: palette.accent.withAlphaComponent(isEnabled ? 1 : 0.45),- ]- let text = title as NSString- let height = text.size(withAttributes: attributes).height- text.draw(at: NSPoint(x: 36, y: (bounds.height - height) / 2), withAttributes: attributes)- }-}--private class SwarmNoticeButton: SwarmIconButton {- var onboarding = false { didSet { needsDisplay = true } }- var attention = 0 { didSet { contentTintColor = iconTint; needsDisplay = true } }- var expanded = false { didSet { contentTintColor = iconTint; needsDisplay = true } }-- var iconTint: NSColor {- let bright = isEnabled && (expanded || state == .on || hovered || hasKeyboardFocus || isHighlighted)- return NSColor(white: attention > 0 ? 0.96 : bright ? 0.84 : 0.60, alpha: 1)- }-- var attentionLabel: String? {- attention > 0 ? (attention > 99 ? "99+" : String(attention)) : nil- }-- func badgeFrame(textWidth: CGFloat) -> NSRect {- let width = max(12, ceil(textWidth) + 5)- return NSRect(x: bounds.maxX - width,- y: isFlipped ? bounds.minY : bounds.maxY - 12, width: width, height: 12)- }-- override func draw(_ dirtyRect: NSRect) {- if contentTintColor != iconTint { contentTintColor = iconTint }- if expanded {- NSColor.white.withAlphaComponent(0.08).setFill()- NSBezierPath(roundedRect: bounds.insetBy(dx: 1, dy: 1), xRadius: 7, yRadius: 7).fill()- }- super.draw(dirtyRect)- if let label = attentionLabel {- let attributes: [NSAttributedString.Key: Any] = [- .font: NSFont.monospacedDigitSystemFont(ofSize: 9, weight: .semibold),- .foregroundColor: NSColor.white,- ]- let text = label as NSString- let size = text.size(withAttributes: attributes)- let badge = badgeFrame(textWidth: size.width)- NSColor.systemRed.withAlphaComponent(isEnabled ? 1 : 0.45).setFill()- NSBezierPath(roundedRect: badge, xRadius: 6, yRadius: 6).fill()- text.draw(at: NSPoint(x: badge.midX - size.width / 2, y: badge.midY - size.height / 2),- withAttributes: attributes)- }- if onboarding {- // A quiet next-step dot never replaces a red unread count.- let offset: CGFloat = attention > 0 ? 19 : 3- let y = isFlipped ? bounds.minY + offset : bounds.maxY - offset - 6- NSColor(calibratedRed: 0.60, green: 0.76, blue: 0.93,- alpha: isEnabled ? 1 : 0.45).setFill()- NSBezierPath(ovalIn: NSRect(x: bounds.maxX - 7, y: y, width: 6, height: 6)).fill()- }- }--}--private final class SwarmSessionsButton: SwarmNoticeButton {- var running = 0 { didSet { needsDisplay = true } }-- func receiveSession() {- guard !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion else { return }- wantsLayer = true- let pulse = CAKeyframeAnimation(keyPath: "transform.scale")- pulse.values = [1, 1.18, 1]- pulse.keyTimes = [0, 0.4, 1]- pulse.duration = 0.24- layer?.add(pulse, forKey: "session-arrived")- }-}-private final class SwarmStripScrollView: NSScrollView {override func scrollWheel(with event: NSEvent) {let dx = event.scrollingDeltaX, dy = event.scrollingDeltaY@@ -999,53 +906,146 @@ private final class SwarmStripScrollView: NSScrollView {}}-private final class SwarmTabStrip: NSView {- /// The title bar's own face: the system one, at the system size.- ///- /// The tabs wore the terminal's face until 2026-09-23. It reads as a terminal- /// costume on furniture that is not the terminal — no other Mac window names- /// its tabs in mono — and the workspace's own chrome, a pane header and the- /// command box, carries that face where it belongs (owner).- static func uiFont(weight: NSFont.Weight = .regular) -> NSFont {- NSFont.systemFont(ofSize: NSFont.systemFontSize, weight: weight)+private func statusColor(_ value: Any?, fallback: NSColor) -> NSColor {+ guard let number = value as? NSNumber else { return fallback }+ let argb = number.uint32Value+ return NSColor(srgbRed: CGFloat((argb >> 16) & 255) / 255,+ green: CGFloat((argb >> 8) & 255) / 255, blue: CGFloat(argb & 255) / 255,+ alpha: CGFloat((argb >> 24) & 255) / 255)+}++private struct SwarmStatusSegment {+ let text: String+ let foreground: NSColor+ let background: NSColor?+}++/// Dart sends the same resolved segments that Flutter uses for its previews.+/// Shapes are drawn in cells; no Powerline/Nerd Font installation is needed.+private final class SwarmContextButton: NSButton {+ var foreground = NSColor.white+ private var text = ""+ private var segments: [SwarmStatusSegment] = []+ private var segmented = false+ var nextBackground: NSColor? { didSet { needsDisplay = true } }+ var isSegmented: Bool { segmented && !segments.isEmpty }+ var firstBackground: NSColor? { segments.first?.background }+ var drawsSegments: Bool { isSegmented && bounds.width >= CGFloat(segments.count) * cellWidth * 4 }+ fileprivate var actionURL: String?+ private var textFont: NSFont { font ?? NSFont.monospacedSystemFont(ofSize: 13, weight: .regular) }+ private var cellWidth: CGFloat { ("m" as NSString).size(withAttributes: [.font: textFont]).width }+ private var naturalWidths: [CGFloat] {+ segments.map { ($0.text as NSString).size(withAttributes: [.font: textFont]).width }+ }+ var preferredWidth: CGFloat {+ ceil(naturalWidths.reduce(0, +) + (segmented ? CGFloat(segments.count) * cellWidth * 3 : 0))+ }++ func update(_ context: [String: Any]?, enabled: Bool) {+ text = context?["text"] as? String ?? ""+ segmented = context?["segmented"] as? Bool == true+ segments = (context?["segments"] as? [[String: Any]] ?? []).compactMap { part in+ guard let text = part["text"] as? String else { return nil }+ return SwarmStatusSegment(text: text,+ foreground: statusColor(part["foreground"], fallback: foreground),+ background: part["background"] == nil ? nil : statusColor(part["background"], fallback: foreground))+ }+ actionURL = context?["url"] as? String+ toolTip = context?["detail"] as? String+ isEnabled = enabled && context?["canSelectModel"] as? Bool == true+ setAccessibilityValue(text)+ setAccessibilityHelp(toolTip)+ needsDisplay = true+ }++ override var mouseDownCanMoveWindow: Bool { false }+ private func attributed(_ value: String, _ color: NSColor, alignment: NSTextAlignment = .left) -> NSAttributedString {+ let paragraph = NSMutableParagraphStyle()+ paragraph.lineBreakMode = .byTruncatingTail+ paragraph.alignment = alignment+ return NSAttributedString(string: value, attributes: [+ .font: textFont, .foregroundColor: color, .paragraphStyle: paragraph,+ ])+ }+ override func draw(_ dirtyRect: NSRect) {+ guard bounds.width > 0, !segments.isEmpty else { return }+ NSGraphicsContext.saveGraphicsState()+ defer { NSGraphicsContext.restoreGraphicsState() }+ bounds.clip()+ if !drawsSegments {+ let line = NSMutableAttributedString(string: "")+ if segmented {+ line.append(attributed(text, foreground, alignment: .right))+ } else {+ for segment in segments { line.append(attributed(segment.text, segment.foreground, alignment: .right)) }+ }+ line.draw(in: NSRect(x: 0, y: (bounds.height - line.size().height) / 2,+ width: bounds.width, height: line.size().height))+ return+ }+ let natural = naturalWidths+ let available = max(0, bounds.width - CGFloat(segments.count) * cellWidth * 3)+ var widths = natural+ if natural.reduce(0, +) > available {+ var low: CGFloat = 0, high = natural.max() ?? 0+ for _ in 0..<24 {+ let cap = (low + high) / 2+ if natural.reduce(0, { $0 + min($1, cap) }) > available { high = cap }+ else { low = cap }+ }+ widths = natural.map { min($0, low) }+ }+ let height = ceil(textFont.pointSize * 1.2)+ let bottom = (bounds.height - height) / 2+ var x = max(0, bounds.width - widths.reduce(0, +) - CGFloat(segments.count) * cellWidth * 3)+ for (index, segment) in segments.enumerated() {+ let inset = cellWidth * (index == 0 ? 1 : 2)+ let width = widths[index] + inset + cellWidth+ if index == segments.count - 1, let nextBackground {+ nextBackground.setFill()+ NSRect(x: x + width, y: bottom, width: cellWidth, height: height).fill()+ }+ let shape = NSBezierPath()+ shape.move(to: NSPoint(x: x, y: bottom))+ shape.line(to: NSPoint(x: x + width, y: bottom))+ shape.line(to: NSPoint(x: x + width + cellWidth, y: bottom + height / 2))+ shape.line(to: NSPoint(x: x + width, y: bottom + height))+ shape.line(to: NSPoint(x: x, y: bottom + height))+ shape.line(to: NSPoint(x: x + (index == 0 ? 0 : cellWidth), y: bottom + height / 2))+ shape.close()+ (segment.background ?? foreground).setFill()+ shape.fill()+ let line = attributed(segment.text, segment.foreground)+ line.draw(in: NSRect(x: x + inset, y: (bounds.height - line.size().height) / 2,+ width: widths[index], height: line.size().height))+ x += width+ }}+}+private final class SwarmTabStrip: NSView {private(set) var palette = SwarmNativePalette()var emit: ((String, Any?) -> Void)?private let scroll = SwarmStripScrollView()private let document = NSView()fileprivate let newButton = SwarmIconButton()- fileprivate let machinesButton = SwarmNoticeButton()- fileprivate let storeButton = SwarmStoreButton(title: "Harness Store", target: nil, action: nil)- fileprivate let modelsButton = SwarmNoticeButton()- fileprivate let sessionsButton = SwarmSessionsButton()+ fileprivate let contextButton = SwarmContextButton()+ fileprivate let pullRequestButton = SwarmContextButton()+ private var terminalFont = NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)+ private var terminalForeground = NSColor(white: 0.85, alpha: 1)+ private var terminalSelection = NSColor(white: 0.35, alpha: 1)private var tabs: [SwarmTabButton] = []- private let icons = SwarmHistoryIcons()private var activeId = ""private var revealActiveAfterLayout = falseprivate var tabOrderChanged = falseprivate var actionsEnabled = falseprivate var lastBackgroundClick: (time: TimeInterval, point: NSPoint)?- // Hold ⌘ and each of the first nine tabs shows the digit that reaches it- // (⌘1…⌘9, the app's own bindings) — the same discoverability Safari and- // the terminals give their tabs. Off again the moment ⌘ is released or the- // app goes to the background.- private var commandHeld = false- private var flagsMonitor: Any?- private var resignObserver: NSObjectProtocol?// Dragging is explicit below. AppKit must not also start a titlebar gesture.override var mouseDownCanMoveWindow: Bool { false }override init(frame: NSRect) {super.init(frame: frame)wantsLayer = true- flagsMonitor = NSEvent.addLocalMonitorForEvents(matching: .flagsChanged) { [weak self] event in- self?.setCommandHeld(event.modifierFlags.contains(.command))- return event- }- resignObserver = NotificationCenter.default.addObserver(- forName: NSApplication.didResignActiveNotification, object: nil, queue: .main- ) { [weak self] _ in self?.setCommandHeld(false) }scroll.drawsBackground = falsescroll.hasHorizontalScroller = falsescroll.hasVerticalScroller = false@@ -1057,7 +1057,7 @@ private final class SwarmTabStrip: NSView {button.isBordered = falsebutton.title = ""button.imagePosition = .imageOnly- button.contentTintColor = (button as? SwarmNoticeButton)?.iconTint ?? palette.accent+ button.contentTintColor = terminalForegroundbutton.target = selfbutton.action = actionbutton.setAccessibilityLabel(label)@@ -1066,33 +1066,23 @@ private final class SwarmTabStrip: NSView {button(newButton, "plus", "New Tab", #selector(newSwarm))newButton.setAccessibilityLabel("New Tab")newButton.isEnabled = false- button(machinesButton, "desktopcomputer", "Machines", #selector(openMachines))- machinesButton.image = icons.image(engine: "machines", asset: "assets/machines.svg", pointSize: 20)- machinesButton.symbolConfiguration = nil- machinesButton.isEnabled = false- machinesButton.toolTip = "Machines ⌘M"- button(sessionsButton, "terminal", "Harnesses", #selector(openSessions))- sessionsButton.image = icons.image(engine: "harnesses", asset: "assets/harnesses.svg", pointSize: 20)- sessionsButton.symbolConfiguration = nil- sessionsButton.isEnabled = false- sessionsButton.toolTip = "Harnesses"newButton.toolTip = "New Tab ⌘T"- storeButton.isBordered = false- storeButton.palette = palette- storeButton.image = icons.image(engine: "store", asset: "assets/store/polymath.png")- storeButton.font = SwarmTabStrip.uiFont(weight: .medium)- storeButton.target = self- storeButton.action = #selector(openStore)- storeButton.isEnabled = false- storeButton.toolTip = "Harness Store ⌘S"- storeButton.setAccessibilityLabel("Harness Store")- addSubview(storeButton)- button(modelsButton, "brain", "Models", #selector(openModels))- modelsButton.image = icons.image(engine: "models", asset: "assets/models.svg", pointSize: 20)- modelsButton.symbolConfiguration = nil- modelsButton.isEnabled = false- modelsButton.toolTip = "Models"- setAccessibilityChildren([scroll, newButton, machinesButton, modelsButton, sessionsButton, storeButton])+ newButton.image = nil+ newButton.title = "+"+ newButton.imagePosition = .noImage+ contextButton.isBordered = false+ contextButton.alignment = .right+ contextButton.target = self+ contextButton.action = #selector(openFocusedModel)+ contextButton.setAccessibilityLabel("Focused pane")+ addSubview(contextButton)+ pullRequestButton.isBordered = false+ pullRequestButton.target = self+ pullRequestButton.action = #selector(openFocusedPullRequest)+ pullRequestButton.setAccessibilityLabel("Open pull request on GitHub")+ pullRequestButton.isHidden = true+ addSubview(pullRequestButton)+ setAccessibilityChildren([scroll, newButton, contextButton, pullRequestButton])registerForDraggedTypes([swarmPasteboardType])}required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }@@ -1102,33 +1092,32 @@ private final class SwarmTabStrip: NSView {guard nextPalette != palette else { return }palette = nextPalettenewButton.contentTintColor = palette.accent- storeButton.palette = palettefor tab in tabs { tab.palette = palette }needsDisplay = true}- deinit {- if let flagsMonitor { NSEvent.removeMonitor(flagsMonitor) }- if let resignObserver { NotificationCenter.default.removeObserver(resignObserver) }- }-- private func setCommandHeld(_ held: Bool) {- guard commandHeld != held else { return }- commandHeld = held- applyShortcutBadges()- }-- fileprivate func applyShortcutBadges() {- for (index, tab) in tabs.enumerated() {- tab.shortcut = commandHeld && actionsEnabled && index < 9 ? index + 1 : nil- }- }-func update(_ state: [String: Any]) {// Workspace teardown clears its controls without changing appearance.if let palette = state["palette"] as? [String: Any] { updatePalette(palette) }actionsEnabled = state["enabled"] as? Bool == true+ if let style = state["terminalStyle"] 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] ?? [])+ terminalFont = families.lazy.compactMap { NSFont(name: $0, size: size) }.first+ ?? NSFont.monospacedSystemFont(ofSize: size, weight: .regular)+ terminalForeground = statusColor(style["foreground"], fallback: terminalForeground)+ terminalSelection = statusColor(style["selection"], fallback: terminalSelection)+ }+ newButton.font = terminalFont+ newButton.contentTintColor = terminalForeground+ contextButton.font = terminalFont+ contextButton.foreground = terminalForeground+ contextButton.update(state["focusedContext"] as? [String: Any], enabled: actionsEnabled)+ pullRequestButton.font = terminalFont+ pullRequestButton.foreground = terminalForeground+ pullRequestButton.update(state["pullRequest"] as? [String: Any], enabled: actionsEnabled)+ pullRequestButton.isHidden = state["pullRequest"] == nillet rows = state["tabs"] as? [[String: Any]] ?? []let nextActiveId = state["activeId"] as? String ?? ""revealActiveAfterLayout = revealActiveAfterLayout || nextActiveId != activeId@@ -1143,6 +1132,10 @@ private final class SwarmTabStrip: NSView {let tab = previous[id] ?? SwarmTabButton(id: id)tab.palette = palettetab.name = row["name"] as? String ?? "New Tab"+ tab.displayLabel = row["label"] as? String ?? tab.name+ tab.labelFont = terminalFont+ tab.foreground = terminalForeground+ tab.selection = terminalSelectiontab.selected = id == activeIdtab.actionsEnabled = actionsEnabledtab.attention = (row["attention"] as? Int ?? 0) > 0@@ -1157,54 +1150,9 @@ private final class SwarmTabStrip: NSView {return tab}updateDividers()- applyShortcutBadges()// Moving frames alone leaves AppKit's child traversal in insertion order.document.setAccessibilityChildren(tabs)newButton.isEnabled = actionsEnabled- machinesButton.isEnabled = actionsEnabled- machinesButton.state = state["machinesOpen"] as? Bool == true ? .on : .off- machinesButton.attention = max(0, state["machineNotices"] as? Int ?? 0)- let machineExpanded = machinesButton.state == .on ? "Expanded" : "Collapsed"- machinesButton.setAccessibilityValue(machinesButton.attention > 0- ? "\(machineExpanded), \(machinesButton.attention) new \(machinesButton.attention == 1 ? "computer" : "computers") ready to connect" : machineExpanded)- storeButton.isEnabled = actionsEnabled- modelsButton.isEnabled = actionsEnabled- modelsButton.state = state["modelsOpen"] as? Bool == true ? .on : .off- modelsButton.attention = max(0, state["modelNotices"] as? Int ?? 0)- let modelExpanded = modelsButton.state == .on ? "Expanded" : "Collapsed"- modelsButton.setAccessibilityValue(modelsButton.attention > 0- ? "\(modelExpanded), \(modelsButton.attention) \(modelsButton.attention == 1 ? "model" : "models") ready to use" : modelExpanded)- sessionsButton.isEnabled = actionsEnabled- sessionsButton.running = state["runningSessions"] as? Int ?? 0- sessionsButton.expanded = state["sessionsOpen"] as? Bool == true- let expandedState = sessionsButton.expanded ? "Expanded" : "Collapsed"- sessionsButton.toolTip = sessionsButton.running > 0 ? "Harnesses · \(sessionsButton.running) running" : "Harnesses"- let attention = state["attention"] as? Int ?? 0- // What the badge COUNTS is `unread` — harnesses carrying news nobody has looked at, which- // includes the ones that simply finished. `attention` is the narrower "blocked, waiting on a- // person" figure and still words the sentence below, because that is the half worth saying- // out loud. An older Flutter sends no `unread`, and then the badge is what it always was.- let unread = state["unread"] as? Int ?? attention- sessionsButton.attention = unread- let attentionState = "\(attention) \(attention == 1 ? "needs" : "need") input"- let unreadState = "\(unread) \(unread == 1 ? "harness has" : "harnesses have") news you have not seen"- sessionsButton.setAccessibilityValue(unread > 0 ? "\(expandedState), \(unreadState)" : expandedState)- if unread > 0 {- sessionsButton.toolTip = attention > 0- ? "Harnesses · \(unreadState) · \(attentionState)"- : "Harnesses · \(unreadState)"- }- let onboarding = state["onboarding"] as? String- for (button, step, action) in [- (machinesButton as SwarmNoticeButton, "machines", "Use your harnesses from another computer"),- (modelsButton as SwarmNoticeButton, "models", "Power a harness with local AI"),- (sessionsButton as SwarmNoticeButton, "harnesses", "Run your first harness"),- ] {- button.onboarding = onboarding == step- if button.onboarding {- button.setAccessibilityValue("\(button.accessibilityValue() as? String ?? ""), Suggested next step: \(action)")- }- }needsLayout = truelayoutSubtreeIfNeeded()if ids != previousOrder {@@ -1226,42 +1174,35 @@ private final class SwarmTabStrip: NSView {let activeWasVisible = active.map { scroll.documentVisibleRect.intersects($0.frame) } ?? falselet previousScrollSize = scroll.frame.sizelet previousDocumentSize = document.frame.size- let leading: CGFloat = 0- let spacious = bounds.width >= 480- let trailing: CGFloat = spacious ? 12 : 8- let storeWidth = storeButton.preferredWidth- let modelsWidth: CGFloat = 28- newButton.isHidden = false- // A reserve after the "+" that tabs never grow into — Chrome's gap. It is- // where a full strip can still be dragged and double-clicked to zoom- // (owner, 2026-09-15); tabs shrink and then scroll instead of taking it.- let grip: CGFloat = spacious ? 84 : 44- // Reserve three adjacent controls: Machines, Models, Harnesses.- // Air between Machines, Models, Harnesses and the Store pill. 16, not 8: the- // marks are ~17pt wide, and 8 left about one mark's width between them- // where the menu bar leaves about one and a half (measured, owner- // 2026-09-24) — they read as a clump rather than as three controls.- let actionGap: CGFloat = 16- let available = max(32, bounds.width - leading - trailing - (newButton.isHidden ? 0 : 36) - grip - storeWidth - modelsWidth- - 28 * 2 - actionGap * 3 - 8)- // As in Chrome, tabs keep shrinking until they are only their mark, so thirty tabs still sit in- // one strip with nothing hidden; only past that does the strip scroll (the wheel scrolls it).- let width = min(220, max(min(SwarmTabButton.minimumWidth, available), available / CGFloat(max(1, tabs.count))))- let occupied = min(available, CGFloat(tabs.count) * width)- scroll.frame = NSRect(x: leading, y: 0, width: occupied, height: bounds.height)- document.frame = NSRect(x: 0, y: 0, width: max(occupied, CGFloat(tabs.count) * width), height: bounds.height)- // Center tab contents on the same row as the traffic lights and toolbar- // actions; spacing below the strip belongs to the workspace.- for (index, tab) in tabs.enumerated() {- tab.frame = NSRect(x: CGFloat(index) * width, y: 0, width: width, height: bounds.height - 2)+ let cell = ceil(("m" as NSString).size(withAttributes: [.font: terminalFont]).width)+ let trailing = cell+ // Compact windows keep a scrolling tab list; context never overlaps it.+ let available = max(0, bounds.width - trailing - cell * 5)+ let widths = tabs.map { min($0.preferredWidth, available * 0.45) }+ let total = widths.reduce(0, +)+ let occupied = min(total, available * 0.45)+ let scrollX = cell+ scroll.frame = NSRect(x: scrollX, y: 0, width: occupied, height: bounds.height)+ document.frame = NSRect(x: 0, y: 0, width: max(occupied, total), height: bounds.height)+ var x: CGFloat = 0+ for (tab, width) in zip(tabs, widths) {+ tab.frame = NSRect(x: x, y: 0, width: width, height: bounds.height)tab.contentCenterY = bounds.midY+ x += width}- let buttonY = (bounds.height - 28) / 2- newButton.frame = NSRect(x: leading + occupied + 4, y: buttonY, width: 28, height: 28)- storeButton.frame = NSRect(x: bounds.width - trailing - storeWidth, y: buttonY, width: storeWidth, height: 28)- sessionsButton.frame = NSRect(x: storeButton.frame.minX - actionGap - 28, y: buttonY, width: 28, height: 28)- modelsButton.frame = NSRect(x: sessionsButton.frame.minX - actionGap - modelsWidth, y: buttonY, width: modelsWidth, height: 28)- machinesButton.frame = NSRect(x: modelsButton.frame.minX - actionGap - 28, y: buttonY, width: 28, height: 28)+ newButton.frame = NSRect(x: scroll.frame.maxX, y: (bounds.height - 28) / 2,+ width: cell * 3, height: 28)+ let statusWidth = max(0, bounds.width - trailing - newButton.frame.maxX - cell * 2)+ let prWidth = pullRequestButton.isHidden ? 0 : min(pullRequestButton.preferredWidth, statusWidth * 0.45)+ let joined = contextButton.isSegmented && pullRequestButton.isSegmented && prWidth > 0+ let prGap = prWidth > 0 && !joined ? cell : 0+ pullRequestButton.frame = NSRect(x: bounds.width - trailing - prWidth, y: 0,+ width: prWidth, height: bounds.height)+ let contextWidth = min(contextButton.preferredWidth, max(0, statusWidth - prWidth - prGap))+ contextButton.frame = NSRect(x: bounds.width - trailing - prWidth - prGap - contextWidth, y: 0,+ width: contextWidth, height: bounds.height)+ contextButton.nextBackground = joined && pullRequestButton.drawsSegments+ ? pullRequestButton.firstBackground : nillet geometryChanged = scroll.frame.size != previousScrollSize || document.frame.size != previousDocumentSizeif let active, revealActiveAfterLayout || (activeWasVisible && (geometryChanged || tabOrderChanged)) {document.scrollToVisible(active.frame)@@ -1296,22 +1237,17 @@ private final class SwarmTabStrip: NSView {hypot(event.locationInWindow.x - first.point.x,event.locationInWindow.y - first.point.y) <= 4}- @objc private func newSwarm() {- if actionsEnabled && newButton.isEnabled { emit?("new", nil) }- }- @objc private func openStore() {- if actionsEnabled { emit?("store", nil) }+ @objc private func openFocusedModel() {+ if actionsEnabled && contextButton.isEnabled { emit?("focusedModel", nil) }}- @objc private func openMachines() {- if actionsEnabled { emit?("machineList", nil) }- }- @objc private func openSessions() {- if actionsEnabled { emit?("sessions", nil) }+ @objc private func openFocusedPullRequest() {+ if actionsEnabled && pullRequestButton.isEnabled, let url = pullRequestButton.actionURL {+ emit?("focusedPullRequest", ["url": url])+ }}- @objc private func openModels() {- if actionsEnabled { emit?("models", nil) }+ @objc private func newSwarm() {+ if actionsEnabled && newButton.isEnabled { emit?("new", nil) }}-private func draggedTab(_ sender: NSDraggingInfo) -> SwarmTabButton? {guard actionsEnabled, sender.draggingSourceOperationMask.contains(.move),let source = sender.draggingSource as? SwarmTabButton,@@ -1338,34 +1274,28 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati}let swarmId: Stringvar name = "New Tab" { didSet { if name != oldValue { invalidateLabel(); updateAccessibility() } } }+ var displayLabel = "New Tab" { didSet { if displayLabel != oldValue { invalidateLabel() } } }+ var foreground = NSColor(white: 0.85, alpha: 1) { didSet { if foreground != oldValue { invalidateLabel() } } }+ var selection = NSColor(white: 0.35, alpha: 1) { didSet { if selection != oldValue { needsDisplay = true } } }+ private var cellWidth: CGFloat { ceil(("m" as NSString).size(withAttributes: [.font: labelFont]).width) }+ var preferredWidth: CGFloat { min(cellWidth * 24, ceil(label.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 showsDivider = false { didSet { if showsDivider != oldValue { needsDisplay = true } } }- /// The ⌘-digit that selects this tab, shown while ⌘ is held; nil otherwise.- var shortcut: Int? { didSet { if shortcut != oldValue { updateCloseVisibility(); needsDisplay = true } } }var contentCenterY: CGFloat = 20var emit: ((String, Any?) -> Void)?var hoverChanged: (() -> Void)?var isHovered: Bool { hovered && actionsEnabled }- private let closeButton = SwarmCloseButton()private let selectButton = SwarmSelectButton()/// Whether the middle button went down on THIS tab — see otherMouseUp.private var middleDown = false- /// A tab is named in the system face, like every other Mac window's tabs —- /// Safari's, Ghostty's, Finder's. The terminal's face belongs to the terminal- /// and to the chrome drawn around it inside the window (owner, 2026-09-23).- var labelFont = SwarmTabStrip.uiFont() {+ /// Status text and numbered tabs share the selected terminal face.+ var labelFont = NSFont.monospacedSystemFont(ofSize: 13, weight: .regular) {didSet { if oldValue != labelFont { invalidateLabel() } }}- /// The ⌘1 badge: monospaced digits, so 1 and 9 take the same room and the- /// badges down a strip of tabs line up.- private var badgeFont: NSFont {- NSFont.monospacedDigitSystemFont(ofSize: 11, weight: .medium)- }private var cachedLabel: NSAttributedString?var actionsEnabled = true {didSet {- closeButton.isEnabled = actionsEnabledselectButton.isEnabled = actionsEnabled}}@@ -1381,19 +1311,11 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidatisetAccessibilityElement(true)setAccessibilityRole(.group)selectButton.owner = self- closeButton.owner = selfselectButton.title = ""selectButton.isBordered = falseselectButton.target = selfselectButton.action = #selector(selectSwarm)addSubview(selectButton)- closeButton.image = NSImage(systemSymbolName: "xmark", accessibilityDescription: "Close Tab")- closeButton.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 10, weight: .semibold)- closeButton.contentTintColor = NSColor(white: 0.78, alpha: 1)- closeButton.isBordered = false- closeButton.target = self- closeButton.action = #selector(closeSwarm)- addSubview(closeButton)let menu = NSMenu()for (title, action) in [("Rename Tab…", #selector(renameSwarm)), ("Close Tab", #selector(closeSwarm))] {let item = NSMenuItem(title: title, action: action, keyEquivalent: "")@@ -1404,18 +1326,10 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidatiupdateAccessibility()}required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }- /// Narrowest a tab gets before the strip scrolls: its mark alone, like a Chrome tab among dozens.- static let minimumWidth: CGFloat = 44- /// Below this a tab shows only its mark: no name, no close button (⌘W and the tab's menu still close it).- static let compactWidth: CGFloat = 96- private var compact: Bool { bounds.width < SwarmTabButton.compactWidth }override func layout() {super.layout()- let compact = self.compact- closeButton.isHidden = compact- selectButton.frame = NSRect(x: 0, y: 0, width: max(0, compact ? bounds.width : bounds.width - 36), height: bounds.height)- closeButton.frame = NSRect(x: bounds.width - 36, y: contentCenterY - 12, width: 24, height: 24)- toolTip = compact ? name : nil+ selectButton.frame = bounds+ toolTip = name}override func updateTrackingAreas() {super.updateTrackingAreas()@@ -1430,15 +1344,9 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidatiprivate func setHovered(_ value: Bool) {guard hovered != value else { return }hovered = value- updateCloseVisibility()needsDisplay = truehoverChanged?()}- fileprivate func updateCloseVisibility() {- // The badge borrows the close glyph's slot; while ⌘ is held the digit wins.- closeButton.showsGlyph = shortcut == nil- && (hovered || selectButton.hasKeyboardFocus || closeButton.hasKeyboardFocus)- }private func invalidateLabel() {cachedLabel = nilneedsDisplay = true@@ -1447,91 +1355,32 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidatiif let cachedLabel { return cachedLabel }let paragraph = NSMutableParagraphStyle()paragraph.lineBreakMode = .byTruncatingTail+ paragraph.alignment = .center// One weight for every tab: the selected one is already told apart by its// fill and its brighter ink, and a bold name also changes width, so the// strip re-truncated whenever the selection moved (owner, 2026-09-24).- let label = NSAttributedString(string: name,+ let label = NSAttributedString(string: displayLabel,attributes: [.font: labelFont,- .foregroundColor: selected ? NSColor.white : NSColor(white: 0.76, alpha: 1), .paragraphStyle: paragraph])+ .foregroundColor: foreground, .paragraphStyle: paragraph])cachedLabel = labelreturn label}override func draw(_ dirtyRect: NSRect) {+ let text = label+ let height = ceil(labelFont.pointSize * 1.2)+ let row = NSRect(x: 0, y: contentCenterY - height / 2, width: bounds.width, height: height)if selected {- palette.workspace.setFill()- // Match TerminalTabBorder: small top corners and outward bottom joins,- // all at the same radius. AppKit's origin is at the bottom left.- let r = min(CGFloat(3), min(bounds.width, bounds.height) / 4)- let c = r * 0.5522847498- let left = bounds.minX + r, right = bounds.maxX - r- let top = bounds.maxY, bottom = bounds.minY- let path = NSBezierPath()- path.move(to: NSPoint(x: bounds.minX, y: bottom))- path.curve(to: NSPoint(x: left, y: bottom + r),- controlPoint1: NSPoint(x: bounds.minX + c, y: bottom),- controlPoint2: NSPoint(x: left, y: bottom + r - c))- path.line(to: NSPoint(x: left, y: top - r))- path.curve(to: NSPoint(x: left + r, y: top),- controlPoint1: NSPoint(x: left, y: top - r + c),- controlPoint2: NSPoint(x: left + r - c, y: top))- path.line(to: NSPoint(x: right - r, y: top))- path.curve(to: NSPoint(x: right, y: top - r),- controlPoint1: NSPoint(x: right - r + c, y: top),- controlPoint2: NSPoint(x: right, y: top - r + c))- path.line(to: NSPoint(x: right, y: bottom + r))- path.curve(to: NSPoint(x: bounds.maxX, y: bottom),- controlPoint1: NSPoint(x: right, y: bottom + r - c),- controlPoint2: NSPoint(x: bounds.maxX - c, y: bottom))- path.close()- path.fill()- } else if hovered && actionsEnabled {- NSColor(white: 1, alpha: 0.05).setFill()- let hoverRect = NSRect(x: 8, y: contentCenterY - 13, width: bounds.width - 16, height: 26)- NSBezierPath(roundedRect: hoverRect, xRadius: 3, yRadius: 3).fill()- }- if showsDivider && !hovered {- NSColor(white: 1, alpha: 0.16).setFill()- NSBezierPath(roundedRect: NSRect(x: bounds.width - 0.5, y: contentCenterY - 8, width: 1, height: 16),- xRadius: 0.5, yRadius: 0.5).fill()- }- let compact = self.compact- if !compact {- let label = self.label- let labelHeight = label.size().height- let trailing = shortcut.map { value in- max(42, ceil(("⌘\(value)" as NSString).size(withAttributes: [.font: badgeFont]).width) + 22)- } ?? 42- // A tab is its name: no mark, not even the engine's or the Store's —- // the pane header says what runs there (owner, 2026-09-24).- label.draw(in: NSRect(x: 22, y: contentCenterY - labelHeight / 2,- width: max(0, bounds.width - 22 - trailing), height: labelHeight))- }- // Too narrow for the name: its first letter, centred.- var initialFrame = NSRect(x: bounds.midX, y: contentCenterY, width: 0, height: 0)- if compact, label.length > 0 {- let initial = NSAttributedString(string: String(name.prefix(1)),- attributes: label.attributes(at: 0, effectiveRange: nil))- let size = initial.size()- initialFrame = NSRect(x: ((bounds.width - size.width) / 2).rounded(),- y: contentCenterY - size.height / 2, width: size.width, height: size.height)- initial.draw(at: initialFrame.origin)+ selection.setFill()+ row.fill()+ } else if (hovered || selectButton.hasKeyboardFocus) && actionsEnabled {+ foreground.withAlphaComponent(0.08).setFill()+ row.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 {- NSColor.systemOrange.setFill()- let dot = compact- ? NSRect(x: initialFrame.maxX + 1, y: initialFrame.maxY - 6, width: 5, height: 5)- : NSRect(x: 13, y: contentCenterY - 2, width: 4, height: 4)- NSBezierPath(ovalIn: dot).fill()- }- if let shortcut, !compact {- let paragraph = NSMutableParagraphStyle()- paragraph.alignment = .right- let badge = NSAttributedString(string: "⌘\(shortcut)",- attributes: [.font: badgeFont,- .foregroundColor: NSColor(white: 1, alpha: selected ? 0.7 : 0.5), .paragraphStyle: paragraph])- let badgeHeight = badge.size().height- let badgeWidth = max(32, ceil(badge.size().width))- badge.draw(in: NSRect(x: bounds.width - 14 - badgeWidth, y: contentCenterY - badgeHeight / 2, width: badgeWidth, height: badgeHeight))+ let marker = NSAttributedString(string: "!", attributes: [.font: labelFont, .foregroundColor: NSColor.systemOrange])+ marker.draw(at: NSPoint(x: 0, y: contentCenterY - marker.size().height / 2))}}// Overflowed tabs might not be drawn. Their names and selection still need@@ -1541,7 +1390,6 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidatiselectButton.setAccessibilityLabel("Select \(name)")selectButton.setAccessibilityValue(selected ? "Selected" : "")selectButton.setAccessibilityHelp(attention ? "Contains agents needing input" : nil)- closeButton.setAccessibilityLabel("Close \(name)")}func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { actionsEnabled }override func mouseDown(with event: NSEvent) {@@ -1581,40 +1429,30 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidatibeginDraggingSession(with: [dragging], event: event, source: self)}func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation { .move }- override func accessibilityChildren() -> [Any]? { [selectButton, closeButton] }+ override func accessibilityChildren() -> [Any]? { [selectButton] }@objc private func selectSwarm() { if actionsEnabled { emit?("select", ["id": swarmId]) } }@objc private func closeSwarm() { if actionsEnabled { emit?("close", ["id": swarmId]) } }@objc private func renameSwarm() { if actionsEnabled { emit?("rename", ["id": swarmId]) } }}-/// Selection and closing are sibling accessibility buttons, so VoiceOver and-/// UI automation can reach the close action without treating the tab as a leaf.+/// One keyboard-accessible selection target. Closing stays in the native menu+/// and Command-W, leaving the label centered across the whole tab.private class SwarmTabActionButton: SwarmIconButton {weak var owner: SwarmTabButton?override var showsHoverFill: Bool { false }override func becomeFirstResponder() -> Bool {guard super.becomeFirstResponder() else { return false }- owner?.updateCloseVisibility()+ owner?.needsDisplay = trueif let owner { owner.scrollToVisible(owner.bounds) }return true}override func resignFirstResponder() -> Bool {guard super.resignFirstResponder() else { return false }- owner?.updateCloseVisibility()+ owner?.needsDisplay = truereturn true}}-/// Keep the close action reachable by keyboard and VoiceOver while its glyph-/// rests quietly. Reserving its space avoids shifting labels on hover.-private final class SwarmCloseButton: SwarmTabActionButton {- override var showsHoverFill: Bool { true }- var showsGlyph = false { didSet { if showsGlyph != oldValue { needsDisplay = true } } }- override func draw(_ dirtyRect: NSRect) {- if showsGlyph { super.draw(dirtyRect) }- }-}-private final class SwarmSelectButton: SwarmTabActionButton {override func mouseDown(with event: NSEvent) {guard isEnabled else { return }diff --git a/desktop/test/clone_agent_test.dart b/desktop/test/clone_agent_test.dartindex 971d338ea..a620d78f7 100644--- a/desktop/test/clone_agent_test.dart+++ b/desktop/test/clone_agent_test.dart@@ -211,6 +211,8 @@ void main() {expect(app.swarms.length, tabs);expect(app.activeSwarmId, tab);expect(app.panes.map((pane) => pane.agentId), ['a0', 'made']);+ // The derived tab label can resize the terminal on the final layout frame.+ await tester.pump(const Duration(milliseconds: 50));await tester.pumpWidget(const SizedBox());});diff --git a/desktop/test/command_dock_interaction_test.dart b/desktop/test/command_dock_interaction_test.dartindex 659fe2b8a..54b193441 100644--- a/desktop/test/command_dock_interaction_test.dart+++ b/desktop/test/command_dock_interaction_test.dart@@ -6,7 +6,7 @@ import 'package:harness/core/models.dart';import 'package:harness/state/swarm_navigation.dart';import 'package:harness/state/swarm_search.dart';import 'package:harness/widgets/engine_identity.dart';-import 'package:harness/widgets/box_chrome.dart' show kBoxFaint;+import 'package:harness/widgets/search_result_text.dart';import 'package:harness/terminal/terminal_text.dart';import 'package:harness/widgets/new_harness_form.dart';import 'package:harness/widgets/swarm_switcher.dart';@@ -75,31 +75,38 @@ void main() {await configured.mount(tester, app, map);await key(tester, LogicalKeyboardKey.keyO, cmd: true);final row = find.byKey(ValueKey(agentDestinationId('m', 'a0')));- expect(tester.widget<ListTile>(row).leading, isA<EngineMark>());- for (final value in [- 'M2',- 'openharness',- 'feature/login-redirect',- '33m',- ]) {- expect(- find.descendant(of: row, matching: find.text(value)),- findsOneWidget,- );- }+ expect(+ find.descendant(of: row, matching: find.byType(EngineMark)),+ findsNothing,+ );+ expect(+ find.descendant(of: row, matching: find.text('33m')),+ findsOneWidget,+ );+ final detail = tester.widget<SearchResultText>(+ find.descendant(+ of: row,+ matching: find.byWidgetPredicate(+ (widget) =>+ widget is SearchResultText && widget.text.contains('git:'),+ ),+ ),+ );for (final label in ['M2', 'openharness', 'feature/login-redirect']) {- final text = tester.widget<Text>(- find.descendant(of: row, matching: find.text(label)),- );- expect(text.style!.fontFamily, terminalFontStore.value.fontFamily);- expect(text.style!.fontSize, terminalFontStore.size);- expect(text.style!.height, terminalFontStore.value.height);- expect(text.style!.color, kBoxFaint);+ expect(detail.text, contains(label));}- final create = tester.widget<ListTile>(- find.byKey(const ValueKey(kSwarmCreateRowId)),+ expect(detail.style.fontFamily, terminalFontStore.value.fontFamily);+ expect(detail.style.fontSize, terminalFontStore.size);+ expect(detail.style.height, terminalFontStore.value.height);+ final create = find.byKey(const ValueKey(kSwarmCreateRowId));+ expect(+ find.descendant(of: create, matching: find.text('New Harness')),+ findsOneWidget,+ );+ expect(+ find.descendant(of: create, matching: find.byType(Icon)),+ findsNothing,);- expect(create.leading, isA<Icon>());expect(find.text('Harness:'), findsNothing);expect(find.byKey(const ValueKey('swarm-search-hints')), findsNothing);expect(tester.takeException(), isNull);diff --git a/desktop/test/first_workspace_test.dart b/desktop/test/first_workspace_test.dartindex 759dc20ee..1a8f41280 100644--- a/desktop/test/first_workspace_test.dart+++ b/desktop/test/first_workspace_test.dart@@ -529,7 +529,7 @@ void main() {find.byKey(const ValueKey('swarm-new-pane-button')),findsNothing,);- expect(find.byTooltip('Harnesses'), findsOneWidget);+ expect(find.byTooltip('Harnesses'), findsNothing);expect(find.byKey(const ValueKey('swarm-new-harness-button')),findsNothing,diff --git a/desktop/test/grid_model_picker_test.dart b/desktop/test/grid_model_picker_test.dartindex ed5e6cb6d..eefd26983 100644--- a/desktop/test/grid_model_picker_test.dart+++ b/desktop/test/grid_model_picker_test.dart@@ -156,6 +156,45 @@ void main() {expect(find.textContaining('usage'), findsOneWidget);});+ testWidgets(+ 'workspace context opens the shared picker without a pane label',+ (tester) async {+ build(+ models: [+ {'id': 'local-model', 'node': 'M2'},+ ],+ );+ final controller = GridModelPickerController();+ addTearDown(controller.dispose);+ String? selected;+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: GridModelPicker(+ notifier: notifier,+ machineId: 'local',+ engineLabel: 'codex',+ controller: controller,+ menuOnly: true,+ onSelected: (model) => selected = model.id,+ ),+ ),+ ),+ );+ expect(find.text('OpenAI'), findsNothing);+ controller.open();+ await tester.pumpAndSettle();+ expect(find.text('local-model'), findsOneWidget);+ await tester.tap(find.text('local-model'));+ await tester.pumpAndSettle();+ expect(selected, 'local-model');+ await tester.pumpWidget(const SizedBox());+ controller.open();+ await tester.pump();+ expect(tester.takeException(), isNull);+ },+ );+testWidgets('compact model menu stays on screen, and Escape closes it', (tester,) async {diff --git a/desktop/test/harness_customize_test.dart b/desktop/test/harness_customize_test.dartindex 3b299f686..cfbdab554 100644--- a/desktop/test/harness_customize_test.dart+++ b/desktop/test/harness_customize_test.dart@@ -28,6 +28,8 @@ import 'support/real_fonts.dart';import 'package:harness/shared/theme/prompt_style.dart';import 'package:harness/widgets/prompt_context.dart';+import 'package:harness/shared/theme/status_line_style.dart';+import 'package:harness/widgets/status_line.dart';import 'swarm_interactions_test.dart' show chord;import 'swarm_screen_test.dart' show mount, terminal;@@ -144,20 +146,20 @@ void main() {expect(Focus.of(tester.element(label)).hasFocus, isTrue);}- await focus('prompt-style-powerline');+ await focus('prompt-style-robbyrussell');await tester.sendKeyEvent(LogicalKeyboardKey.enter);await tester.pumpAndSettle();- expect(store.value.prompt.style, PromptStyle.powerline);+ expect(store.value.prompt.statusStyle, StatusLineStyle.robbyrussell);await focus('prompt-branch');await tester.sendKeyEvent(LogicalKeyboardKey.space);await tester.pumpAndSettle();expect(store.value.prompt.branch, isFalse);expect(- find.descendant(- of: find.byKey(const ValueKey('prompt-preview')),- matching: find.text('main'),- ),- findsNothing,+ tester+ .widget<StatusLine>(find.byKey(const ValueKey('prompt-preview')))+ .parts+ .text,+ isNot(contains('main')),);final reopened = AppearancePrefsStore(storage: storage);addTearDown(reopened.dispose);@@ -213,7 +215,7 @@ void main() {await tester.pumpAndSettle();expect(find.byType(SettingsScreen), findsNothing);expect(find.byType(HarnessCustomizePane), findsOneWidget);- expect(find.byType(PromptContextView), findsWidgets);+ expect(find.byType(StatusLine), findsWidgets);expect(tester.getRect(find.byKey(pane.cellKey)), before);final panel = tester.getRect(find.byType(HarnessCustomizePane));expect(panel.right, 1280);@@ -300,19 +302,23 @@ void main() {// Publish the same preference notifications as the controls without// persisting this test's choices into the developer's saved preferences.appearancePrefsStore.value = appearancePrefsStore.value.copyWith(- prompt: const PromptPrefs(style: PromptStyle.powerline),+ prompt: const PromptPrefs(statusStyle: StatusLineStyle.pure),);await tester.pumpAndSettle();- for (final pane in panes) {- final header = find.descendant(- of: find.byKey(pane.cellKey),+ final status = tester.widget<StatusLine>(+ find.descendant(+ of: find.byKey(const ValueKey('workspace-pane-context')),+ matching: find.byType(StatusLine),+ ),+ );+ expect(status.parts.text, contains('Test host'));+ expect(+ find.descendant(+ of: find.byKey(panes.first.cellKey),matching: find.byType(PromptContextView),- );- expect(- find.descendant(of: header, matching: find.byType(ClipPath)),- findsWidgets,- );- }+ ),+ findsNothing,+ );await _capture(tester, boundary, 'live-panes-customization');await tester.tap(find.byKey(const ValueKey('customize-appearance')));await tester.pumpAndSettle();@@ -442,9 +448,9 @@ void main() {expect(find.byKey(const ValueKey('harness-start-results')), findsNothing);expect(tester.widget<TextField>(start).controller!.text, 'Keep my query');expect(tester.takeException(), isNull);- for (final style in PromptStyle.values) {+ for (final style in StatusLineStyle.values) {appearancePrefsStore.value = appearancePrefsStore.value.copyWith(- prompt: PromptPrefs(style: style),+ prompt: PromptPrefs(statusStyle: style),);await tester.pumpAndSettle();expect(tester.takeException(), isNull);diff --git a/desktop/test/harness_session_manager_test.dart b/desktop/test/harness_session_manager_test.dartindex ef492a6f3..bb61198e2 100644--- a/desktop/test/harness_session_manager_test.dart+++ b/desktop/test/harness_session_manager_test.dart@@ -1,3 +1,5 @@+import 'support/workspace_tools.dart';+import 'dart:async';import 'dart:io';import 'dart:ui' show SemanticsAction;@@ -69,7 +71,7 @@ void main() {find.byKey(ValueKey('session-toggle:${agentDestinationId('m', id)}'));Future<void> open(WidgetTester tester) async {await mount(tester, app);- await tester.tap(find.byTooltip('Harnesses'));+ await openWorkspaceTool(tester, 'harnesses');await tester.pumpAndSettle();}@@ -230,19 +232,12 @@ void main() {await app.addAgentToSwarm('m', 'a0');app.machineStates['m']!.blockedAgents['a0'] = question('a0');await mount(tester, app);- await tester.tap(find.byTooltip('Harnesses'));+ await openWorkspaceTool(tester, 'harnesses');await tester.pump(const Duration(milliseconds: 300));expect(find.byKey(const ValueKey('swarm-notifications-button')),findsNothing,);- final managerIcon = tester.getRect(find.byTooltip('Harnesses'));- expect(- managerIcon.right,- lessThan(- tester.getRect(find.byKey(const ValueKey('swarm-store-button'))).left,- ),- );await tester.tap(find.byKey(const ValueKey('session-filter:needsInput')));await tester.pump(const Duration(milliseconds: 300));expect(find.text('Use the shared cache?'), findsOneWidget);@@ -513,7 +508,7 @@ void main() {await tester.pump();connection.stopReplies.single.complete({'deleted': true});await tester.pump();- await tester.tap(find.byTooltip('Harnesses'));+ await openWorkspaceTool(tester, 'harnesses');await tester.pump();expect(toggle('a0'), findsNothing);expect(find.byTooltip('Pausing…'), findsOneWidget);@@ -904,7 +899,7 @@ void main() {expect(app.panes, [sibling]);expect(app.stateOf('m')!.agents.first.isStopped, isFalse);expect(connection.stops, isEmpty);- await tester.tap(find.byTooltip('Harnesses'));+ await openWorkspaceTool(tester, 'harnesses');await tester.pumpAndSettle();expect(find.text(_running.name), findsOneWidget);},diff --git a/desktop/test/harness_store_entry_test.dart b/desktop/test/harness_store_entry_test.dartindex 94bb51a85..654e6f56e 100644--- a/desktop/test/harness_store_entry_test.dart+++ b/desktop/test/harness_store_entry_test.dart@@ -40,9 +40,7 @@ void main() {if (native) {await configured.native(tester, 'store');} else {- final button = find.byKey(const ValueKey('swarm-store-button'));- expect(tester.getRect(button).bottom, lessThanOrEqualTo(40));- await tester.tap(button);+ await key(tester, LogicalKeyboardKey.keyS, cmd: true);}await tester.pump();}diff --git a/desktop/test/machines_manager_test.dart b/desktop/test/machines_manager_test.dartindex 2ef267d15..016584bf6 100644--- a/desktop/test/machines_manager_test.dart+++ b/desktop/test/machines_manager_test.dart@@ -1,3 +1,5 @@+import 'support/workspace_tools.dart';+import 'package:flutter/gestures.dart';import 'package:flutter/material.dart';import 'package:flutter/services.dart';@@ -87,18 +89,10 @@ void main() {..loaded = true;await mount(tester, app);await tester.pumpAndSettle();- Badge badge(String name) =>- tester.widget<Badge>(find.byKey(ValueKey('swarm-$name-badge')));- expect(badge('machines').isLabelVisible, isTrue);- expect((badge('machines').label as Text).data, '1');- expect(badge('models').isLabelVisible, isTrue);- await tester.tap(find.byKey(const ValueKey('swarm-machines-button')));- await tester.pumpAndSettle();- expect(badge('machines').isLabelVisible, isFalse);- expect(badge('models').isLabelVisible, isTrue);- await tester.tap(find.byKey(const ValueKey('swarm-models-button')));- await tester.pumpAndSettle();- expect(badge('models').isLabelVisible, isFalse);+ expect(find.byKey(const ValueKey('swarm-machines-badge')), findsNothing);+ expect(find.byKey(const ValueKey('swarm-models-badge')), findsNothing);+ await openWorkspaceTool(tester, 'machines');+ await openWorkspaceTool(tester, 'models');expect(find.text('Models'), findsOneWidget);await key(tester, LogicalKeyboardKey.escape);await tester.pumpAndSettle();@@ -110,8 +104,7 @@ void main() {};await app.modelManager.refresh();await tester.pumpAndSettle();- expect(badge('models').isLabelVisible, isFalse);- await tester.tap(find.byKey(const ValueKey('swarm-models-button')));+ await openWorkspaceTool(tester, 'models');await tester.pumpAndSettle();await tester.tap(find.textContaining('Local').first);await tester.pumpAndSettle();@@ -122,18 +115,13 @@ void main() {for (final nativeTabs in [false, true]) {testWidgets(- 'toolbar panels switch in one click without stacking (native=$nativeTabs)',+ 'workspace tools switch without stacking (native=$nativeTabs)',(tester) async {final app = createApp();app.stateOf('m')!.nodeOnline = true;final input = <TerminalBinaryFrame>[];app.adoptSessionForTest(terminal('a0', input));await mount(tester, app, nativeTabs: nativeTabs);- final buttons = {- 'machineList': find.byKey(const ValueKey('swarm-machines-button')),- 'models': find.byKey(const ValueKey('swarm-models-button')),- 'sessions': find.byTooltip('Harnesses'),- };final panels = {'machineList': find.byKey(const ValueKey('machines-panel')),'models': find.byType(ModelsPanel),@@ -145,13 +133,22 @@ void main() {await tester.pumpAndSettle();await action;} else {- await tester.tap(buttons[command]!);+ await openWorkspaceTool(+ tester,+ {+ 'machineList': 'machines',+ 'models': 'models',+ 'sessions': 'harnesses',+ }[command]!,+ );await tester.pumpAndSettle();}}for (final from in panels.keys) {for (final to in panels.keys) {+ // Opening command search dismisses the old panel first.+ if (!nativeTabs && from == 'sessions' && to == 'sessions') continue;await open(from);await open(to);for (final entry in panels.entries) {@@ -238,41 +235,30 @@ void main() {app.dispose();});- testWidgets(- 'Cmd M and the toolbar open Machines and restore terminal input',- (tester) async {- final app = createApp();- app.stateOf('m')!.nodeOnline = true;- final input = <TerminalBinaryFrame>[];- app.adoptSessionForTest(terminal('a0', input));- await mount(tester, app);- await key(tester, LogicalKeyboardKey.keyM, cmd: true);- await tester.pumpAndSettle();- expect(find.text('Machines'), findsOneWidget);- await key(tester, LogicalKeyboardKey.escape);- await tester.pumpAndSettle();- final machines = find.byKey(const ValueKey('swarm-machines-button'));- final models = find.byKey(const ValueKey('swarm-models-button'));- expect(- tester.getCenter(machines).dx,- lessThan(tester.getCenter(models).dx),- );- expect(- tester.getCenter(models).dx,- lessThan(tester.getCenter(find.byTooltip('Harnesses')).dx),- );- await tester.tap(machines);- await tester.pumpAndSettle();- expect(find.text('Machines'), findsOneWidget);- await key(tester, LogicalKeyboardKey.escape);- await tester.pumpAndSettle();- tester.testTextInput.enterText('x');- await tester.idle();- expect(String.fromCharCodes(input.single.bytes), 'x');- await tester.pumpWidget(const SizedBox());- app.dispose();- },- );+ testWidgets('Cmd M opens Machines and restore terminal input', (+ tester,+ ) async {+ final app = createApp();+ app.stateOf('m')!.nodeOnline = true;+ final input = <TerminalBinaryFrame>[];+ app.adoptSessionForTest(terminal('a0', input));+ await mount(tester, app);+ await key(tester, LogicalKeyboardKey.keyM, cmd: true);+ await tester.pumpAndSettle();+ expect(find.text('Machines'), findsOneWidget);+ await key(tester, LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ await openWorkspaceTool(tester, 'machines');+ await tester.pumpAndSettle();+ expect(find.text('Machines'), findsOneWidget);+ await key(tester, LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ tester.testTextInput.enterText('x');+ await tester.idle();+ expect(String.fromCharCodes(input.single.bytes), 'x');+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ });testWidgets('clicking a linked machine scopes work by ID even when names match',@@ -297,7 +283,7 @@ void main() {];app.adoptSessionForTest(terminal('a0', []));await mount(tester, app);- await tester.tap(find.byKey(const ValueKey('swarm-machines-button')));+ await openWorkspaceTool(tester, 'machines');await tester.pumpAndSettle();await tester.tap(find.byKey(const ValueKey('machine-m')));await tester.pumpAndSettle();@@ -374,7 +360,7 @@ void main() {..connectionStatus = ConnectionStatus.connected;app.adoptSessionForTest(terminal('a0', []));await mount(tester, app);- await tester.tap(find.byKey(const ValueKey('swarm-machines-button')));+ await openWorkspaceTool(tester, 'machines');await tester.pumpAndSettle();await tester.tap(find.byKey(const ValueKey('machine-fresh')));await tester.pumpAndSettle();diff --git a/desktop/test/machines_panel_test.dart b/desktop/test/machines_panel_test.dartindex 91aec31d6..dd9476ad2 100644--- a/desktop/test/machines_panel_test.dart+++ b/desktop/test/machines_panel_test.dart@@ -1,3 +1,5 @@+import 'support/workspace_tools.dart';+import 'dart:async';import 'dart:io';import 'dart:ui' as ui;@@ -224,11 +226,11 @@ void main() {);await tester.pumpAndSettle();}- await tester.tap(- workspace- ? find.byKey(const ValueKey('swarm-machines-button'))- : find.text('open machines'),- );+ if (workspace) {+ await openWorkspaceTool(tester, 'machines');+ } else {+ await tester.tap(find.text('open machines'));+ }await tester.pumpAndSettle();}@@ -389,7 +391,6 @@ void main() {app.add('server', 'Build server', online: false);await mount(tester, size: const Size(1280, 800), workspace: true);final panel = find.byKey(const ValueKey('machines-panel'));- final icon = find.byKey(const ValueKey('swarm-machines-button'));expect(find.byType(Dialog), findsNothing);for (final barrier in tester.widgetList<ModalBarrier>(find.byType(ModalBarrier),@@ -400,12 +401,8 @@ void main() {reason: 'The workspace stays undimmed',);}- expect(- tester.getRect(panel).top,- greaterThan(tester.getRect(icon).bottom),- );+ expect(tester.getRect(panel).top, greaterThan(40));expect(tester.getRect(panel).right, closeTo(1270, 2));- expect(tester.widget<IconButton>(icon).isSelected, isTrue);expect(remoteInput, findsNothing);expect(localInput, findsNothing);expect(find.text('Set password'), findsOneWidget);@@ -457,7 +454,7 @@ void main() {await capture(tester, 'machines-toolbar-set-password');await key(tester, LogicalKeyboardKey.escape);await tester.pumpAndSettle();- await tap(tester, icon);+ await openWorkspaceTool(tester, 'machines');expect(localInput, findsNothing);await tap(tester, find.byKey(const ValueKey('connect-machine-remote')));expect(tester.widget<TextField>(remoteInput).focusNode!.hasFocus, isTrue);@@ -470,12 +467,14 @@ void main() {await tester.tapAt(const Offset(30, 200));await tester.pumpAndSettle();expect(panel, findsNothing);- expect(tester.widget<IconButton>(icon).isSelected, isFalse);await mount(tester, workspace: true, brightness: Brightness.light);- expect(find.byType(ToolbarIcon), findsNWidgets(3));+ expect(find.byType(ToolbarIcon), findsNothing);expect(panel, findsOneWidget);await tap(tester, find.byTooltip('Close Machines'));- expect(icon.hitTestable(), findsOneWidget);+ expect(+ find.byKey(const ValueKey('swarm-new-tab-button')).hitTestable(),+ findsOneWidget,+ );await tester.pumpWidget(const SizedBox());},);@@ -1216,7 +1215,7 @@ void main() {expect(find.byKey(const ValueKey('machines-panel')), findsOneWidget);await tap(tester, find.byTooltip('Close Machines'));expect(- find.byKey(const ValueKey('swarm-machines-button')).hitTestable(),+ find.byKey(const ValueKey('swarm-new-tab-button')).hitTestable(),findsOneWidget,);await tester.pumpWidget(const SizedBox());diff --git a/desktop/test/models_panel_test.dart b/desktop/test/models_panel_test.dartindex 1a78eafa0..cbc5539dc 100644--- a/desktop/test/models_panel_test.dart+++ b/desktop/test/models_panel_test.dart@@ -1,3 +1,5 @@+import 'support/workspace_tools.dart';+import 'dart:async';import 'dart:io';import 'dart:ui' as ui;@@ -684,12 +686,11 @@ void main() {);final tab = app.activeSwarmId;final panes = app.panes.map((pane) => pane.id).toList();- final button = find.byKey(const ValueKey('swarm-models-button'));app.modelManager.start();await app.modelManager.refresh();await tester.pump();expect(find.text('Explore models'), findsNothing);- await tester.tap(button);+ await openWorkspaceTool(tester, 'models');await tester.pump();await tester.tap(find.textContaining('Local').first);await tester.pump();@@ -706,7 +707,7 @@ void main() {await tester.pump();await tester.sendKeyEvent(LogicalKeyboardKey.escape);await tester.pump();- await tester.tap(button);+ await openWorkspaceTool(tester, 'models');await tester.pump();await tester.runAsync(() async {for (final asset in [@@ -727,12 +728,8 @@ void main() {await tester.pump(const Duration(milliseconds: 300));final panel = tester.getRect(find.byType(ModelsPanel));expect(panel.right, 1190);- expect(panel.top, greaterThan(tester.getRect(button).bottom));+ expect(panel.top, greaterThan(40));expect(panel.width, 640);- expect(- tester.getRect(button).right,- lessThan(tester.getRect(find.byTooltip('Harnesses')).left),- );expect(find.byType(Dialog), findsNothing);expect(find.text('Search models…'), findsOneWidget);expect(find.text('All 14'), findsOneWidget);@@ -759,7 +756,7 @@ void main() {await tester.sendKeyEvent(LogicalKeyboardKey.escape);await tester.pump();expect(find.byType(ModelsPanel), findsNothing);- await tester.tap(button);+ await openWorkspaceTool(tester, 'models');await tester.pump();await tester.tapAt(const Offset(50, 400));await tester.pump();diff --git a/desktop/test/new_harness_entry_rules_test.dart b/desktop/test/new_harness_entry_rules_test.dartindex 709281eca..9f9961671 100644--- a/desktop/test/new_harness_entry_rules_test.dart+++ b/desktop/test/new_harness_entry_rules_test.dart@@ -331,17 +331,14 @@ void main() {);}- testWidgets('Store Open restores its harness after switching to Coding', (+ testWidgets('Store Open restores its harness after switching to Code', (tester,) async {await mount(tester);await product(tester, 'autonomous/blender');box(tester).focusField(NewHarnessField.harness);box(tester).accept(- const NewHarnessOption(- id: NewHarnessController.codingId,- title: 'Coding',- ),+ const NewHarnessOption(id: NewHarnessController.codingId, title: 'Code'),);box(tester).focusField(NewHarnessField.agent);box(tester).accept(const NewHarnessOption(id: 'codex', title: 'Codex'));diff --git a/desktop/test/new_harness_form_test.dart b/desktop/test/new_harness_form_test.dartindex b6838823e..2a4a4bddf 100644--- a/desktop/test/new_harness_form_test.dart+++ b/desktop/test/new_harness_form_test.dart@@ -1,8 +1,10 @@import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;import 'package:harness/state/new_harness.dart';-import 'package:harness/widgets/box_chrome.dart';+import 'package:harness/terminal/terminal_theme.dart';+import 'package:harness/terminal/terminal_theme_store.dart';import 'package:harness/widgets/new_harness_form.dart';import 'package:harness/ws/ws_conn.dart';@@ -535,7 +537,10 @@ void main() {testWidgets('the selection bar marks which column has the keys', (tester,) async {- final bright = Colors.white.withValues(alpha: .12);+ final bright = terminalThemeFor(+ grid.AppTheme.palette.value,+ terminalThemeStore.value,+ ).selection;int barsOn() => tester.widgetList<Container>(find.byType(Container)).where((box) => box.color == bright)@@ -570,7 +575,12 @@ void main() {testWidgets('the list dims while the items hold the keys', (tester) async {final box = await mount(tester);- // An unselected option stays quieter than the active choice.+ final foreground = terminalThemeFor(+ grid.AppTheme.palette.value,+ terminalThemeStore.value,+ ).foreground;+ final faint = foreground.withValues(alpha: .54);+ // The inactive column stays quieter than the one receiving input.final other = box.options.firstWhere((row) => !row.synthetic && !identical(row, box.selected)).title;@@ -579,17 +589,17 @@ void main() {expect(inkOf(other),- kBoxFaint,+ faint,reason: 'The column the arrows are not in is grey.',);await press(tester, LogicalKeyboardKey.enter);expect(inkOf(other),- Colors.white70,+ foreground,reason: 'Handing the arrows over brings the column up.',);await press(tester, LogicalKeyboardKey.escape);- expect(inkOf(other), kBoxFaint);+ expect(inkOf(other), faint);});testWidgets('the right column follows the focused row', (tester) async {diff --git a/desktop/test/new_harness_install_pane_test.dart b/desktop/test/new_harness_install_pane_test.dartindex e5995a9d5..fb3fee5cb 100644--- a/desktop/test/new_harness_install_pane_test.dart+++ b/desktop/test/new_harness_install_pane_test.dart@@ -1,5 +1,5 @@// New Harness lists every harness the machine's catalog has — recent ones,-// then Coding, then installed, then the rest of the Store — opens on the last+// then Code, then installed, then the rest of the Store — opens on the last// harness and agent used, and installs a missing harness on the way to// starting, narrating that install in the right pane on the form's grid.import 'dart:async';@@ -236,7 +236,7 @@ void main() {group('the harness list', () {test(- 'recent harnesses, then Coding, then installed, then the Store',+ 'recent harnesses, then Code, then installed, then the Store',() async {final notifier = await app(remember: (n) async {@@ -255,7 +255,7 @@ void main() {},);- test('with no history, Coding leads and every harness is listed', () async {+ test('with no history, Code leads and every harness is listed', () async {final ids = harnessList(controller(await app()));expect(ids.first, NewHarnessController.codingId);expect(@@ -285,11 +285,11 @@ void main() {});group('what the form opens on', () {- test('Coding and Claude Code when nothing was used before', () async {+ test('Code and Claude Code when nothing was used before', () async {final box = controller(await app());await Future<void>.delayed(Duration.zero);expect(box.harnessId, isNull);- expect(box.harnessLabel, 'Coding');+ expect(box.harnessLabel, 'Code');expect(box.engine, 'claude');});@@ -316,23 +316,23 @@ void main() {installed: true,);- test('a remembered harness the Store dropped opens as Coding', () async {+ test('a remembered harness the Store dropped opens as Code', () async {final notifier = await app(remember: (n) => n.agentPreference.remember('codex', harnessId: gone),);final box = controller(notifier);await Future<void>.delayed(Duration.zero);expect(box.harnessId, isNull);- expect(box.harnessLabel, 'Coding');+ expect(box.harnessLabel, 'Code');expect(box.engine,'codex',- reason: 'Coding keeps the agent last used, which Coding can run',+ reason: 'Code keeps the agent last used, which Code can run',);expect(harnessList(box), isNot(contains(gone)));});- test('a remembered viewer package opens as Coding too', () async {+ test('a remembered viewer package opens as Code too', () async {final notifier = await app(catalog: [_blender, viewer],remember: (n) =>diff --git a/desktop/test/new_harness_scenarios_test.dart b/desktop/test/new_harness_scenarios_test.dartindex a490d4861..064304e71 100644--- a/desktop/test/new_harness_scenarios_test.dart+++ b/desktop/test/new_harness_scenarios_test.dart@@ -4,6 +4,9 @@ import 'dart:ui' show SemanticsAction;import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/terminal/terminal_theme.dart';+import 'package:harness/terminal/terminal_theme_store.dart';import 'package:harness/state/app_state.dart';import 'package:harness/state/new_harness.dart';import 'package:harness/widgets/new_harness_form.dart';@@ -306,7 +309,13 @@ void main() {.first,);// Dark grey: darker than an idle row's faint, so it recedes.- expect(studio.style!.color, Colors.white.withValues(alpha: .28));+ expect(+ studio.style!.color,+ terminalThemeFor(+ grid.AppTheme.palette.value,+ terminalThemeStore.value,+ ).foreground.withValues(alpha: .28),+ );final handle = tester.ensureSemantics();expect(tester.getSemantics(_option('studio')).hint, 'Link required');handle.dispose();diff --git a/desktop/test/open_picker_rendering_test.dart b/desktop/test/open_picker_rendering_test.dartindex 9d12337db..14c901890 100644--- a/desktop/test/open_picker_rendering_test.dart+++ b/desktop/test/open_picker_rendering_test.dart@@ -1,14 +1,257 @@import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';+import 'package:harness/screens/swarm_screen.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/shared/theme/color_palette.dart';+import 'package:harness/shortcuts/app_keymap.dart';+import 'package:harness/state/new_harness.dart';+import 'package:harness/state/swarm_catalog.dart';+import 'package:harness/terminal/terminal_text.dart';+import 'package:harness/terminal/terminal_theme_store.dart';+import 'package:harness/widgets/search_result_text.dart';+import 'package:harness/widgets/new_harness_form.dart';import 'package:harness/widgets/swarm_switcher.dart';+import 'package:harness/widgets/engine_identity.dart';+import 'package:harness/widgets/prompt_context.dart';+import 'package:xterm/xterm.dart';import 'keymap_host_test.dart' show MemoryKeymap, key;import 'keymap_runtime_test.dart' show mount;+import 'support/launch_menu.dart' show openLaunchRow;import 'swarm_screen_test.dart' show terminal;+import 'swarm_search_preview_test.dart' show seedPreviews;import 'swarm_state_test.dart' show createApp;void main() {+ testWidgets(+ 'terminal dialogs follow the live pane theme without losing focus',+ (tester) async {+ final originalPalette = grid.AppTheme.palette.value;+ final originalTheme = terminalThemeStore.value;+ final originalFont = terminalFontStore.value;+ final originalEntry = newHarnessOpensInBox;+ newHarnessOpensInBox = true;+ addTearDown(() {+ grid.AppTheme.palette.value = originalPalette;+ terminalThemeStore.value = originalTheme;+ terminalFontStore.value = originalFont;+ newHarnessOpensInBox = originalEntry;+ });+ final app = createApp();+ final map = MemoryKeymap();+ final projects = SwarmProjectStore();+ addTearDown(map.dispose);+ addTearDown(projects.dispose);+ await seedPreviews(app);+ app.adoptSessionForTest(terminal('a69', []));+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = const Size(1280, 800);+ addTearDown(tester.view.resetPhysicalSize);+ addTearDown(tester.view.resetDevicePixelRatio);+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ builder: (_, child) => grid.BrightnessScope(+ child: KeymapProvider(keymap: map, child: child!),+ ),+ home: SwarmScreen(+ notifier: app,+ nativeTabs: false,+ projectStore: projects,+ ),+ ),+ );+ await tester.pump(const Duration(milliseconds: 100));+ await key(tester, LogicalKeyboardKey.keyO, cmd: true);+ final input = find.byKey(const ValueKey('swarm-search-input'));+ await tester.enterText(input, 'Test host');+ await tester.pumpAndSettle();+ final search = tester+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))+ .search;+ final selectedId = search.selected!.id;+ final controller = tester.widget<TextField>(input).controller!;+ final editing = controller.value;+ final terminalBuffer = tester+ .widget<TerminalView>(find.byType(TerminalView))+ .terminal;++ void checkAppearance() {+ final pane = tester.widget<TerminalView>(find.byType(TerminalView));+ final field = tester.widget<TextField>(input);+ final editor = tester.widget<EditableText>(+ find.descendant(of: input, matching: find.byType(EditableText)),+ );+ final panel = tester.widget<Material>(+ find.byKey(const ValueKey('swarm-search-results')),+ );+ expect(panel.color, pane.theme.background);+ expect(field.style!.color, pane.theme.foreground);+ expect(field.cursorColor, pane.theme.cursor);+ expect(editor.selectionColor, pane.theme.selection);+ final row = find.byKey(+ ValueKey('swarm-search-line:${search.selected!.id}'),+ );+ expect(tester.widget<Container>(row).color, pane.theme.selection);+ final cell = terminalCellSizeOf(tester.element(input));+ expect(tester.getSize(row).height, closeTo(cell.height, .01));+ expect(field.cursorWidth, closeTo(cell.width, .01));+ final rowTitles = tester.widgetList<SearchResultText>(+ find.byWidgetPredicate(+ (widget) =>+ widget is SearchResultText &&+ search.rows.any((row) => row.title == widget.text),+ ),+ );+ expect(rowTitles, isNotEmpty);+ for (final title in rowTitles) {+ expect(title.style.color, pane.theme.foreground);+ }+ final previewText = tester.widgetList<Text>(+ find.descendant(+ of: find.byKey(const ValueKey('swarm-search-preview')),+ matching: find.byType(Text),+ ),+ );+ expect(previewText, isNotEmpty);+ for (final style in [+ field.style!,+ ...rowTitles.map((text) => text.style),+ ...previewText.map((text) => text.style!),+ ]) {+ expect(style.fontFamily, pane.textStyle.fontFamily);+ expect(style.fontFamilyFallback, pane.textStyle.fontFamilyFallback);+ expect(style.fontSize, pane.textStyle.fontSize);+ expect(style.height, pane.textStyle.height);+ expect(style.letterSpacing, 0);+ expect(style.wordSpacing, 0);+ }+ expect(search.selected!.id, selectedId);+ expect(field.controller, same(controller));+ expect(controller.value, editing);+ expect(field.focusNode!.hasFocus, isTrue);+ expect(pane.terminal, same(terminalBuffer));+ expect(tester.takeException(), isNull);+ }++ // All app palettes, then an independent terminal scheme and a live zoom.+ // Each change happens with the same input, cached rows and preview open.+ terminalThemeStore.value = TerminalThemeChoice.matchApp;+ for (final palette in HarnessPalette.values) {+ grid.AppTheme.palette.value = palette;+ await tester.pumpAndSettle();+ checkAppearance();+ }+ terminalThemeStore.value = TerminalThemeChoice.tango;+ terminalFontStore.value = const TerminalStyle(+ fontSize: 18,+ fontFamily: 'Menlo',+ fontFamilyFallback: ['monospace'],+ height: 1.4,+ );+ await tester.pumpAndSettle();+ checkAppearance();+ await tester.enterText(input, 'Workspace sync');+ await tester.pumpAndSettle();+ final waiting = tester.widget<Text>(find.text('Needs your input'));+ expect(waiting.style!.fontSize, 18);+ expect(waiting.style!.height, 1.4);+ expect(+ waiting.style!.color,+ tester.widget<TerminalView>(find.byType(TerminalView)).theme.yellow,+ );+ await key(tester, LogicalKeyboardKey.escape);+ expect(find.byKey(const ValueKey('swarm-search-results')), findsNothing);++ await key(tester, LogicalKeyboardKey.keyN, cmd: true);+ await openLaunchRow(tester, 'project');+ final setup = find.byType(NewHarnessForm);+ final box = tester.widget<NewHarnessForm>(setup).controller;+ final setupInput = find.byKey(const ValueKey('new-harness-query'));+ await tester.enterText(setupInput, 'store');+ await tester.pumpAndSettle();+ final setupController = tester.widget<TextField>(setupInput).controller!;+ final setupEditing = setupController.value;+ final selectedOption = box.selected?.id;++ void checkSetupAppearance() {+ final pane = tester.widget<TerminalView>(find.byType(TerminalView));+ final field = tester.widget<TextField>(setupInput);+ final editor = tester.widget<EditableText>(+ find.descendant(of: setupInput, matching: find.byType(EditableText)),+ );+ expect(+ tester+ .widget<Material>(+ find.byKey(const ValueKey('new-harness-surface')),+ )+ .color,+ pane.theme.background,+ );+ expect(field.style!.color, pane.theme.foreground);+ expect(field.cursorColor, pane.theme.cursor);+ expect(editor.selectionColor, pane.theme.selection);+ expect(+ tester+ .widgetList<Container>(+ find.descendant(of: setup, matching: find.byType(Container)),+ )+ .where((container) => container.color == pane.theme.selection),+ hasLength(1),+ );+ for (final style in [+ field.style!,+ ...tester+ .widgetList<Text>(+ find.descendant(of: setup, matching: find.byType(Text)),+ )+ .map((text) => text.style!),+ ]) {+ expect(style.fontFamily, pane.textStyle.fontFamily);+ expect(style.fontFamilyFallback, pane.textStyle.fontFamilyFallback);+ expect(style.fontSize, pane.textStyle.fontSize);+ expect(style.height, pane.textStyle.height);+ expect(style.letterSpacing, 0);+ expect(style.wordSpacing, 0);+ }+ expect(box.selected?.id, selectedOption);+ expect(field.controller, same(setupController));+ expect(setupController.value, setupEditing);+ expect(field.focusNode!.hasFocus, isTrue);+ expect(pane.terminal, same(terminalBuffer));+ expect(tester.takeException(), isNull);+ }++ terminalThemeStore.value = TerminalThemeChoice.matchApp;+ for (final palette in HarnessPalette.values) {+ grid.AppTheme.palette.value = palette;+ await tester.pumpAndSettle();+ checkSetupAppearance();+ }+ terminalThemeStore.value = TerminalThemeChoice.tango;+ terminalFontStore.value = const TerminalStyle(+ fontSize: 14,+ fontFamily: 'Monaco',+ fontFamilyFallback: ['Menlo'],+ height: 1.3,+ );+ await tester.pumpAndSettle();+ checkSetupAppearance();+ box.warn('The selected machine is offline.');+ await tester.pumpAndSettle();+ expect(+ tester+ .widget<Text>(find.byKey(const ValueKey('new-harness-status')))+ .style!+ .color,+ tester.widget<TerminalView>(find.byType(TerminalView)).theme.red,+ );+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ },+ );+testWidgets('Open Harness builds a small window and Tab reaches later rows', (tester,) async {@@ -20,14 +263,38 @@ void main() {await key(tester, LogicalKeyboardKey.keyO, cmd: true);final results = find.byType(SwarmSearchResults);final search = tester.widget<SwarmSearchResults>(results).search;- final rows = find.descendant(of: results, matching: find.byType(ListTile));- final prompt = find.byKey(const ValueKey('swarm-search-prompt'));- final visibleTiles = tester.widgetList<ListTile>(rows);- for (final tile in visibleTiles.where((tile) => tile.leading != null)) {+ final rowIds = search.rows.map((row) => row.id).toSet();+ final rows = find.descendant(+ of: results,+ matching: find.byWidgetPredicate(+ (widget) =>+ widget is InkWell &&+ widget.key is ValueKey<String> &&+ rowIds.contains((widget.key! as ValueKey<String>).value),+ ),+ );+ final input = find.byKey(const ValueKey('swarm-search-input'));+ final cell = terminalCellSizeOf(tester.element(input));+ for (final row in rows.evaluate()) {+ final id = (row.widget.key! as ValueKey<String>).value;+ final line = find.byKey(ValueKey('swarm-search-line:$id'));+ expect(+ tester.getSize(line).height,+ closeTo(cell.height, .01),+ reason: 'Selection occupies exactly one terminal line.',+ );+ final title = find+ .descendant(of: line, matching: find.byType(Text))+ .first;+ expect(+ tester.getTopLeft(title).dx,+ closeTo(tester.getTopLeft(input).dx, .01),+ );+ }+ for (final type in [ListTile, Icon, Image, EngineMark, PromptContextView]) {expect(- tester.getCenter(prompt).dx,- closeTo(tester.getCenter(find.byWidget(tile.leading!)).dx, .1),- reason: 'The prompt, create action and engine marks share one column.',+ find.descendant(of: results, matching: find.byType(type)),+ findsNothing,);}expect(search.rows.length, greaterThan(50));diff --git a/desktop/test/pane_file_menu_test.dart b/desktop/test/pane_file_menu_test.dartnew file mode 100644index 000000000..b62a0536f--- /dev/null+++ b/desktop/test/pane_file_menu_test.dart@@ -0,0 +1,140 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/sharing/share_harness_dialog.dart';+import 'package:harness/widgets/terminal_composer.dart';+import 'package:harness/ws/ws_conn.dart';++import 'swarm_screen_test.dart' show mount, terminal;+import 'swarm_state_test.dart' show createApp;++class _Connection extends WsConn {+ _Connection()+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: 'm',+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );+ final calls = <(String, Map<String, dynamic>)>[];+ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async {+ calls.add((type, payload));+ return {'shares': []};+ }+}++void main() {+ const channel = MethodChannel('harness/swarm_tabs');+ Future<void> send(WidgetTester tester, String action) async {+ tester.binding.defaultBinaryMessenger.handlePlatformMessage(+ channel.name,+ const StandardMethodCodec().encodeMethodCall(MethodCall(action)),+ (_) {},+ );+ await tester.pumpAndSettle();+ }++ testWidgets(+ 'File Share targets the focused harness and disables in an empty tab',+ (tester) async {+ final updates = <Map>[];+ 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 connection = _Connection();+ final app = createApp(connectionForTest: (_) => connection);+ app.stateOf('m')!.nodeOnline = true;+ final first = app.adoptSessionForTest(terminal('a0', []));+ app.adoptSessionForTest(terminal('a1', []));+ await mount(tester, app, nativeTabs: true);+ app.focusPane(first.id);+ await tester.pump();+ expect((updates.last['paneActions'] as Map)['shareAgent'], isTrue);+ await send(tester, 'shareAgent');+ expect(find.byType(ShareHarnessDialog), findsOneWidget);+ expect(+ connection.calls+ .where((call) => call.$1 == 'harness_share_list')+ .single+ .$2,+ {'agentId': 'a0'},+ );+ expect(+ (updates.last['paneActions'] as Map)['shareAgent'],+ isFalse,+ reason: 'A modal cannot open another share dialog.',+ );+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ app.newSwarm();+ await tester.pumpAndSettle();+ expect((updates.last['paneActions'] as Map)['shareAgent'], isFalse);+ await send(tester, 'shareAgent');+ expect(find.byType(ShareHarnessDialog), findsNothing);+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ },+ );++ testWidgets(+ 'View menu toggles the focused composer and the viewer of its owner',+ (tester) async {+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(+ channel,+ (_) async => true,+ );+ addTearDown(+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(+ channel,+ null,+ ),+ );+ final app = createApp();+ app.stateOf('m')!.nodeOnline = true;+ app.stateOf('m')!.agents = [+ const Agent(+ id: 'a0',+ name: 'Preview',+ engine: 'codex',+ terminalAvailable: true,+ viewerUrl: 'http://fixture.invalid/viewer',+ ),+ ];+ final pane = app.adoptSessionForTest(terminal('a0', []));+ await mount(tester, app, nativeTabs: true);+ await send(tester, 'toggleComposer');+ expect(pane.composerVisible, isTrue);+ expect(find.byType(TerminalComposer), findsOneWidget);+ await send(tester, 'toggleComposer');+ expect(pane.composerVisible, isFalse);+ await send(tester, 'toggleViewer');+ final viewer = app.panes.singleWhere((pane) => pane.isWeb);+ expect(viewer.ownerAgentId, 'a0');+ app.focusPane(viewer.id);+ await tester.pump();+ await send(tester, 'toggleViewer');+ expect(app.panes.where((pane) => pane.isWeb), isEmpty);+ expect(app.panes, contains(pane));+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ },+ );+}diff --git a/desktop/test/pane_restart_test.dart b/desktop/test/pane_restart_test.dartindex b9309fa3d..54a792c34 100644--- a/desktop/test/pane_restart_test.dart+++ b/desktop/test/pane_restart_test.dart@@ -1,7 +1,6 @@-import 'package:flutter/gestures.dart';+import 'package:flutter/services.dart';import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';-import 'package:harness/widgets/pane_header_actions.dart';import 'package:harness/ws/ws_conn.dart';import 'swarm_screen_test.dart' show mount, terminal;@@ -44,7 +43,7 @@ void main() {'The engine could not restart.',),]) {- testWidgets('pane restarts its own harness and reports $reply', (+ testWidgets('File restart targets the focused harness and reports $reply', (tester,) async {final connection = _RestartConnection(reply);@@ -53,23 +52,37 @@ void main() {final first = app.adoptSessionForTest(terminal('a0', []));final session = first.session;final second = app.adoptSessionForTest(terminal('a1', []));- await mount(tester, app);+ const channel = MethodChannel('harness/swarm_tabs');+ final updates = <Map>[];+ 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,+ ),+ );+ await mount(tester, app, nativeTabs: true);expect(app.focusedPane, same(second));- final controls = find.byType(PaneHeaderActions).first;- final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);- await mouse.addPointer(location: tester.getCenter(controls));- await tester.pump(const Duration(milliseconds: 120));- await tester.tap(- find.descendant(- of: controls,- matching: find.byTooltip('Restart Harness'),+ app.focusPane(first.id);+ await tester.pump();+ expect((updates.last['paneActions'] as Map)['restartAgent'], isTrue);+ tester.binding.defaultBinaryMessenger.handlePlatformMessage(+ channel.name,+ const StandardMethodCodec().encodeMethodCall(+ const MethodCall('restartAgent'),),+ (_) {},);await tester.pumpAndSettle();// Each pane header's model picker also asks for grid_models_list as it mounts; the restart is// the one request that is not that.final sent = connection.calls- .where((call) => call.$1 != 'grid_models_list')+ .where((call) => call.$1 == 'agent_restart').toList();expect(sent, hasLength(1));expect(sent.single.$1, 'agent_restart');@@ -85,17 +98,7 @@ void main() {app.machineStates['m']!.nodeOnline = false;app.notifyListeners();await tester.pump();- final restart = tester.widget<IconButton>(- find.descendant(- of: controls,- matching: find.byWidgetPredicate(- (widget) =>- widget is IconButton && widget.tooltip == 'Restart Harness',- ),- ),- );- expect(restart.onPressed, isNull);- await mouse.removePointer();+ expect((updates.last['paneActions'] as Map)['restartAgent'], isFalse);await tester.pumpWidget(const SizedBox());app.dispose();});diff --git a/desktop/test/pull_request_badge_test.dart b/desktop/test/pull_request_badge_test.dartindex b4591a874..144e8f7a5 100644--- a/desktop/test/pull_request_badge_test.dart+++ b/desktop/test/pull_request_badge_test.dart@@ -18,7 +18,7 @@ void main() {body: PullRequestBadge(identity: id, read: read, open: open),),);- testWidgets('PR and branch hide together while hovering reveals controls', (+ testWidgets('PR and branch stay visible beside the quiet pane controls', (tester,) async {await tester.pumpWidget(@@ -26,20 +26,18 @@ void main() {home: Scaffold(body: SizedBox(width: 500,- child: PaneHeaderHover(- child: PaneHeaderActions(- zoomed: false,- onZoom: () {},- details: const Text('branch-name'),- trailing: PullRequestBadge(- identity: 'branch',- read: () async => {- 'status': 'found',- 'number': 12,- 'state': 'Open',- 'url': 'https://github.com/acme/repo/pull/12',- },- ),+ child: PaneHeaderActions(+ zoomed: false,+ onZoom: () {},+ details: const Text('branch-name'),+ trailing: PullRequestBadge(+ identity: 'branch',+ read: () async => {+ 'status': 'found',+ 'number': 12,+ 'state': 'Open',+ 'url': 'https://github.com/acme/repo/pull/12',+ },),),),@@ -51,22 +49,9 @@ void main() {await mouse.addPointer(location: Offset.zero);await mouse.moveTo(tester.getCenter(find.text('PR #12 · Open')));await tester.pumpAndSettle();- final details = find.byKey(const ValueKey('pane-header-details'));- expect(tester.widget<AnimatedOpacity>(details).opacity, 0);- expect(- find.descendant(of: details, matching: find.text('branch-name')),- findsOneWidget,- );- expect(- find.descendant(of: details, matching: find.text('PR #12 · Open')),- findsOneWidget,- );- expect(find.text('PR #12 · Open').hitTestable(), findsNothing);- expect(find.byTooltip('Zoom Pane').hitTestable(), findsOneWidget);- await mouse.moveTo(const Offset(700, 500));- await tester.pumpAndSettle();- expect(tester.widget<AnimatedOpacity>(details).opacity, 1);+ expect(find.text('branch-name').hitTestable(), findsOneWidget);expect(find.text('PR #12 · Open').hitTestable(), findsOneWidget);+ expect(find.byTooltip('Zoom Pane').hitTestable(), findsOneWidget);await mouse.removePointer();await tester.pumpWidget(const SizedBox());});diff --git a/desktop/test/settings_screen_test.dart b/desktop/test/settings_screen_test.dartindex 7de2c7720..65c5ffca8 100644--- a/desktop/test/settings_screen_test.dart+++ b/desktop/test/settings_screen_test.dart@@ -92,7 +92,7 @@ void main() {expect(find.byType(SettingsScreen), findsNothing);expect(find.byType(Placeholder), findsOneWidget);expect(find.byType(HarnessCustomizePane), findsOneWidget);- for (final label in ['Pane', 'Appearance', 'Terminal']) {+ for (final label in ['Status', 'Appearance', 'Terminal']) {expect(find.text(label), findsOneWidget);}await tester.tap(find.byKey(const ValueKey('customize-appearance')));diff --git a/desktop/test/status_line_test.dart b/desktop/test/status_line_test.dartnew file mode 100644index 000000000..ae820eaea--- /dev/null+++ b/desktop/test/status_line_test.dart@@ -0,0 +1,199 @@+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/shared/theme/status_line_style.dart';+import 'package:harness/terminal/terminal_text.dart';+import 'package:harness/terminal/terminal_theme.dart';+import 'package:harness/terminal/terminal_theme_store.dart';+import 'package:harness/widgets/status_line.dart';++import 'support/real_fonts.dart';++void main() {+ setUpAll(loadRealFonts);+ test(+ 'themes have distinct resolved colors and segments, including PR states',+ () {+ for (final theme in [darkTerminalTheme, tangoTerminalTheme]) {+ final designs = <String>{};+ for (final style in StatusLineStyle.values) {+ final parts = statusLineParts(+ provider: 'OpenAI',+ machine: 'M2',+ project: 'app',+ branch: 'main',+ style: style,+ );+ final paint = statusLinePaintSegments(parts, theme);+ designs.add(paint.map((p) => p.toJson()).toString());+ expect(paint.any((p) => p.background != null), style.segmented);+ expect(+ statusLinePaintSegments(+ parts,+ theme,+ color: false,+ ).map((p) => p.foreground),+ everyElement(theme.foreground),+ );+ for (final state in ['Draft', 'Open', 'Merged', 'Closed']) {+ final pr = pullRequestStatusLineParts(+ number: 298,+ state: state,+ style: style,+ );+ expect(pr.text, 'PR #298 · $state');+ expect(+ statusLinePaintSegments(+ pr,+ theme,+ ).any((p) => p.background != null),+ style.segmented,+ );+ }+ expect(+ statusLineParts(+ provider: '',+ machine: '',+ project: '',+ style: style,+ ).text,+ isEmpty,+ );+ }+ expect(designs, hasLength(5));+ }+ expect(StatusLineStyle.fromId('starship'), StatusLineStyle.standard);+ expect(fitStatusLineWidths([10, 80, 40], 90), [+ 10,+ closeTo(40, .01),+ closeTo(40, .01),+ ]);+ },+ );++ testWidgets(+ 'every theme and PR fit one terminal row at narrow widths and large text',+ (tester) async {+ final previousTheme = terminalThemeStore.value;+ addTearDown(() => terminalThemeStore.value = previousTheme);+ tester.view.physicalSize = const Size(1000, 750);+ tester.view.devicePixelRatio = 1;+ addTearDown(tester.view.reset);+ final boundary = GlobalKey();+ for (final choice in TerminalThemeChoice.values) {+ terminalThemeStore.value = choice;+ for (final scale in [1.0, 1.8]) {+ for (final width in [160.0, 840.0]) {+ await tester.pumpWidget(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: MediaQuery(+ data: MediaQueryData(textScaler: TextScaler.linear(scale)),+ child: TerminalFontScope(+ child: Builder(+ builder: (context) {+ final cell = terminalCellSizeOf(context);+ return Scaffold(+ backgroundColor: terminalThemeFor(+ grid.AppTheme.palette.value,+ choice,+ ).background,+ body: Align(+ alignment: Alignment.topLeft,+ child: RepaintBoundary(+ key: boundary,+ child: SizedBox(+ width: width,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment:+ CrossAxisAlignment.stretch,+ children: [+ for (final style+ in StatusLineStyle.values) ...[+ Text(+ style.label,+ style: terminalContentStyle(+ color: Colors.grey,+ ),+ ),+ SizedBox(+ height: cell.height,+ child: StatusLine(+ key: ValueKey(+ 'context-${style.name}',+ ),+ textAlign: TextAlign.left,+ parts: statusLineParts(+ provider: 'OpenAI',+ machine: 'M2',+ project: 'openharness',+ branch: 'feature/日本語',+ style: style,+ ),+ ),+ ),+ SizedBox(+ height: cell.height,+ child: StatusLine(+ textAlign: TextAlign.left,+ parts: pullRequestStatusLineParts(+ number: 298,+ state: 'Merged',+ style: style,+ ),+ ),+ ),+ SizedBox(height: cell.height),+ ],+ ],+ ),+ ),+ ),+ ),+ );+ },+ ),+ ),+ ),+ ),+ );+ await tester.pump();+ expect(tester.takeException(), isNull);+ for (final style in StatusLineStyle.values) {+ expect(+ tester+ .getSize(find.byKey(ValueKey('context-${style.name}')))+ .width,+ width,+ );+ }+ final directory =+ Platform.environment['HARNESS_STATUS_CAPTURE_DIR'];+ if (directory != null && scale == 1 && width == 840) {+ await tester.runAsync(() async {+ final render =+ boundary.currentContext!.findRenderObject()!+ as RenderRepaintBoundary;+ final image = await render.toImage();+ final bytes = await image.toByteData(+ format: ui.ImageByteFormat.png,+ );+ await Directory(directory).create(recursive: true);+ await File('$directory/${choice.name}.png')+ .writeAsBytes(bytes!.buffer.asUint8List());+ image.dispose();+ });+ }+ }+ }+ }+ await tester.pumpWidget(const SizedBox());+ },+ );+}diff --git a/desktop/test/support/workspace_tools.dart b/desktop/test/support/workspace_tools.dartnew file mode 100644index 000000000..dd38aef0d--- /dev/null+++ b/desktop/test/support/workspace_tools.dart@@ -0,0 +1,27 @@+import 'package:flutter/services.dart';+import 'package:flutter/widgets.dart';+import 'package:flutter_test/flutter_test.dart';++import '../keymap_host_test.dart' show key;++/// Workspace tools remain available after the status bar replaces their icons.+Future<void> openWorkspaceTool(WidgetTester tester, String tool) async {+ final shortcut = switch (tool) {+ 'machines' => LogicalKeyboardKey.keyM,+ 'models' => LogicalKeyboardKey.keyI,+ 'store' => LogicalKeyboardKey.keyS,+ _ => null,+ };+ if (shortcut != null) {+ await key(tester, shortcut, cmd: true);+ } else {+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);+ await tester.enterText(+ find.byKey(const ValueKey('swarm-search-input')),+ '> Harnesses',+ );+ await tester.pump();+ await tester.tap(find.byKey(const ValueKey('command:harnesses.list')));+ }+ await tester.pump(const Duration(milliseconds: 350));+}diff --git a/desktop/test/swarm_arrange_keyboard_test.dart b/desktop/test/swarm_arrange_keyboard_test.dartindex dcab3a881..eb54594fc 100644--- a/desktop/test/swarm_arrange_keyboard_test.dart+++ b/desktop/test/swarm_arrange_keyboard_test.dart@@ -36,7 +36,9 @@ void main() {await tester.pump();final label = find.descendant(of: strip,- matching: find.text(app.activeSwarm.name),+ matching: find.text(+ '${app.swarms.indexOf(app.activeSwarm) + 1}:${app.activeSwarm.name}',+ ),);expect(label, findsOneWidget);final viewport = tester.getRect(strip);diff --git a/desktop/test/swarm_interactions_test.dart b/desktop/test/swarm_interactions_test.dartindex 762880116..de3ca2081 100644--- a/desktop/test/swarm_interactions_test.dart+++ b/desktop/test/swarm_interactions_test.dart@@ -196,7 +196,7 @@ void main() {await tester.sendKeyUpEvent(LogicalKeyboardKey.control);await tester.pump();final selected = find.byWidgetPredicate(- (w) => w is ListTile && w.selected,+ (w) => w is Semantics && w.properties.selected == true,);expect(find.descendant(of: selected, matching: find.text('Agent 10')),@@ -251,21 +251,13 @@ void main() {final controls = find.byType(PaneHeaderActions).first;expect(tester- .widgetList<IconButton>(- find.descendant(of: controls, matching: find.byType(IconButton)),+ .widgetList<Text>(+ find.descendant(of: controls, matching: find.byType(Text)),)- .map((button) => button.tooltip),- orderedEquals([- 'Share harness',- 'Show message composer',- 'Zoom Pane',- 'Restart Harness',- 'Fork Harness',- 'Stop Harness',- 'Close Pane',- ]),+ .map((text) => text.data),+ ['-', '[]', 'x'],);- expect(find.byTooltip('Stop Harness').first.hitTestable(), findsNothing);+ expect(find.byTooltip('Stop Harness').first.hitTestable(), findsOneWidget);final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);await mouse.addPointer(location: const Offset(1, 1));Future<void> hover() async {@@ -273,20 +265,12 @@ void main() {await tester.pump(const Duration(milliseconds: 120));}- await hover();- await tester.tap(find.byTooltip('Show message composer').first);- await tester.pump();- expect(pane.composerVisible, isTrue);- await hover();- await tester.tap(find.byTooltip('Hide message composer').first);- await tester.pump();- expect(pane.composerVisible, isFalse);await hover();await tester.tap(find.byTooltip('Zoom Pane').first);await tester.pump();expect(app.zoomedPaneId, pane.id);await hover();- await tester.tap(find.byTooltip('Zoom Pane'));+ await tester.tap(find.byTooltip('Restore Pane'));await tester.pump();expect(app.zoomedPaneId, isNull);await hover();diff --git a/desktop/test/swarm_picker_activation_test.dart b/desktop/test/swarm_picker_activation_test.dartindex 5f6baf263..27bb4ab22 100644--- a/desktop/test/swarm_picker_activation_test.dart+++ b/desktop/test/swarm_picker_activation_test.dart@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/terminal/terminal_binary.dart';+import 'package:harness/terminal/terminal_text.dart';import 'package:harness/state/swarm_navigation.dart';import 'swarm_screen_test.dart' show mount, terminal;@@ -24,7 +25,8 @@ void main() {expect(find.byKey(const ValueKey('swarm-search-new-agent')), findsNothing);final panelRect = tester.getRect(results);final fieldRect = tester.getRect(field);- expect(fieldRect.left, panelRect.left);+ final cell = terminalCellSizeOf(tester.element(field));+ expect(fieldRect.left - panelRect.left, closeTo(cell.width * 4, .01));expect(fieldRect.right, lessThanOrEqualTo(panelRect.right));expect(fieldRect.width, greaterThan(panelRect.width / 2));await chord(tester, LogicalKeyboardKey.keyN);diff --git a/desktop/test/swarm_screen_test.dart b/desktop/test/swarm_screen_test.dartindex 474df2f84..6ad4b4a69 100644--- a/desktop/test/swarm_screen_test.dart+++ b/desktop/test/swarm_screen_test.dart@@ -4,7 +4,6 @@ import 'dart:convert';import 'dart:io';import 'package:flutter/material.dart';-import 'package:flutter/gestures.dart';import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/core/models.dart';@@ -17,7 +16,6 @@ import 'package:harness/state/terminal_pane.dart';import 'package:harness/store/store_mark.dart';import 'package:harness/terminal/terminal_binary.dart';import 'package:harness/terminal/terminal_session.dart';-import 'package:harness/widgets/engine_identity.dart';import 'package:harness/widgets/pane_grid.dart';import 'package:harness/widgets/terminal_panel.dart';import 'package:harness/ws/local_cli_discovery.dart';@@ -85,45 +83,32 @@ TerminalSession terminal(String id, List<TerminalBinaryFrame> input) =>..streamId = 'stream-$id';void main() {- testWidgets('tab close marks follow hover and keyboard focus', (- tester,- ) async {- final app = createApp();- final first = app.activeSwarm;- app.renameSwarm(first.id, 'First tab');- app.newSwarm();- final second = app.activeSwarm;- app.renameSwarm(second.id, 'Second tab');- await mount(tester, app);- Finder close(String id) => find.byKey(ValueKey('tab-close:$id'));- double opacity(String id) => tester.widget<Opacity>(close(id)).opacity;- expect(opacity(first.id), 0);- expect(opacity(second.id), 0);- final pointer = await tester.createGesture(kind: PointerDeviceKind.mouse);- await pointer.addPointer(location: const Offset(900, 500));- await pointer.moveTo(tester.getCenter(find.text('First tab')));- await tester.pump();- expect(opacity(first.id), 1);- expect(opacity(second.id), 0);- await pointer.moveTo(const Offset(900, 500));- await tester.pump();- expect(opacity(first.id), 0);- Focus.of(tester.element(find.text('First tab'))).requestFocus();- await tester.pumpAndSettle();- expect(opacity(first.id), 1);- final closeIcon = find.descendant(- of: close(first.id),- matching: find.byType(Icon),- );- Focus.of(tester.element(closeIcon)).requestFocus();- await tester.pumpAndSettle();- await tester.sendKeyEvent(LogicalKeyboardKey.space);- await tester.pump();- expect(app.swarms.map((swarm) => swarm.id), [second.id]);- await pointer.removePointer();- await tester.pumpWidget(const SizedBox());- app.dispose();- });+ testWidgets(+ 'tabs omit close buttons and Command-W still closes the active tab',+ (tester) async {+ final app = createApp();+ final first = app.activeSwarm;+ app.renameSwarm(first.id, 'First tab');+ app.newSwarm(name: 'Second tab');+ final second = app.activeSwarm;+ await mount(tester, app);+ expect(find.byKey(ValueKey('tab-close:${first.id}')), findsNothing);+ expect(find.byKey(ValueKey('tab-close:${second.id}')), findsNothing);+ final label = find.text('2:Second tab');+ final tab = find.byKey(ValueKey(second.id));+ expect(+ tester.getCenter(label).dx,+ closeTo(tester.getCenter(tab).dx, .01),+ );+ Focus.of(tester.element(label)).requestFocus();+ await tester.pumpAndSettle();+ await chord(tester, LogicalKeyboardKey.keyW);+ await tester.pumpAndSettle();+ expect(app.swarms.map((swarm) => swarm.id), [first.id]);+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ },+ );for (final native in [false, true]) {testWidgets(@@ -180,7 +165,7 @@ void main() {}for (final native in [false, true]) {- testWidgets('the store tab uses the Store mark (native=$native)', (+ testWidgets('the store tab has a compact text label (native=$native)', (tester,) async {const channel = MethodChannel('harness/swarm_tabs');@@ -223,23 +208,12 @@ void main() {isFalse,);} else {- final mark = find.byKey(ValueKey('tab-store:${tab.id}'));- expect(mark, findsOneWidget);- final image = tester.widget<Image>(- find.descendant(- of: mark,- matching: find.byType(Image),- matchRoot: true,- ),- );- expect((image.image as AssetImage).assetName, kStoreMarkAsset);- expect(image.width, 16);- expect(image.height, 16);+ expect(find.text('1:store'), findsOneWidget);}});testWidgets(- 'a harness tab — its agent and that agent\'s viewer — wears the harness mark (native=$native)',+ 'a harness tab — its agent and that agent\'s viewer — uses the harness type (native=$native)',(tester) async {const channel = MethodChannel('harness/swarm_tabs');final updates = <Map>[];@@ -295,9 +269,7 @@ void main() {);expect(row['iconAsset'], 'assets/engine-icons/marp.png');} else {- final mark = find.byKey(ValueKey('tab-engine:${tab.id}'));- expect(tester.widget<EngineMark>(mark).engine, 'autonomous/marp');- expect(find.byKey(ValueKey('tab-group:${tab.id}')), findsNothing);+ expect(find.text('1:Quarterly deck'), findsOneWidget);}// An agent the machine no longer lists is drawn as its session's engine,@@ -315,14 +287,7 @@ void main() {expect(row['engine'], isNull);expect(row['iconAsset'], isNull);} else {- expect(- tester- .widget<EngineMark>(- find.byKey(ValueKey('tab-engine:${leftovers.id}')),- )- .engine,- isNull,- );+ expect(find.text('2:Leftovers'), findsOneWidget);}final session = terminal('gone', []);other.session = session;@@ -333,14 +298,7 @@ void main() {expect(row['engine'], 'codex');expect(row['iconAsset'], 'assets/engine-icons/codex.png');} else {- expect(- tester- .widget<EngineMark>(- find.byKey(ValueKey('tab-engine:${leftovers.id}')),- )- .engine,- 'codex',- );+ expect(find.text('2:Leftovers again'), findsOneWidget);}tab.panes.removeWhere((pane) => pane.id == 900);leftovers.panes.clear();@@ -402,7 +360,7 @@ void main() {final position = tester.state<ScrollableState>(strip).position;position.jumpTo(position.maxScrollExtent);await tester.pump();- expect(find.byKey(ValueKey('tab-store:${store.id}')), findsOneWidget);+ expect(find.text('42:store'), findsOneWidget);}await tester.pumpWidget(const SizedBox());app.dispose();@@ -443,7 +401,7 @@ void main() {expect(row['engine'], 'codex');expect(row['iconAsset'], 'assets/engine-icons/codex.png');} else {- expect(find.byKey(ValueKey('tab-engine:${tab.id}')), findsOneWidget);+ expect(find.text('1:code'), findsOneWidget);}// A harness's viewer beside its agent is the same agent: still its mark, not a group.@@ -463,7 +421,7 @@ void main() {expect(row['agentCount'], 1);expect(row['engine'], 'codex');} else {- expect(find.byKey(ValueKey('tab-engine:${tab.id}')), findsOneWidget);+ expect(find.text('1:New Tab'), findsOneWidget);expect(find.byKey(ValueKey('tab-group:${tab.id}')), findsNothing);}tab.panes.removeWhere((pane) => pane.id == 900);@@ -475,7 +433,7 @@ void main() {expect(row['agentCount'], 2);expect(row['engine'], isNull);} else {- expect(find.byKey(ValueKey('tab-group:${tab.id}')), findsOneWidget);+ expect(find.text('1:New Tab'), findsOneWidget);}await app.closePane(app.panes.last.id);@@ -486,7 +444,7 @@ void main() {'codex',);} else {- expect(find.byKey(ValueKey('tab-engine:${tab.id}')), findsOneWidget);+ expect(find.text('1:New Tab'), findsOneWidget);expect(find.byKey(ValueKey('tab-group:${tab.id}')), findsNothing);}expect(app.activeSwarm, same(tab));@@ -552,7 +510,7 @@ void main() {find.byKey(const ValueKey('harness-start-search')),findsOneWidget,);- expect(find.byKey(const ValueKey('swarm-models-button')), findsOneWidget);+ expect(find.byKey(const ValueKey('swarm-models-button')), findsNothing);expect(find.text('Machines'), findsNothing);await chord(tester, LogicalKeyboardKey.keyO);await tester.pump();diff --git a/desktop/test/swarm_search_identity_test.dart b/desktop/test/swarm_search_identity_test.dartindex 586557461..4f5f48190 100644--- a/desktop/test/swarm_search_identity_test.dart+++ b/desktop/test/swarm_search_identity_test.dart@@ -8,6 +8,7 @@ import 'package:harness/state/swarm_catalog.dart';import 'package:harness/state/swarm_navigation.dart';import 'package:harness/state/swarm_search.dart';import 'package:harness/state/terminal_pane.dart';+import 'package:harness/widgets/swarm_switcher.dart';import 'swarm_interactions_test.dart' show chord;import 'swarm_screen_test.dart' show mount, terminal;@@ -394,7 +395,13 @@ void main() {await tester.enterText(input, 'extensibility');await tester.pump();// One harness, then the row that makes what was typed instead.- expect(find.byType(ListTile), findsNWidgets(2));+ expect(+ tester+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))+ .search+ .rows,+ hasLength(2),+ );expect(find.byKey(const ValueKey(kSwarmCreateRowId)), findsOneWidget);// Minimal rows keep the full metadata accessible and searchable.for (final value in [@@ -415,7 +422,13 @@ void main() {expect(find.byKey(const ValueKey('swarm-search-hints')), findsNothing);await tester.enterText(input, 'Architecture review');await tester.pump();- expect(find.byType(ListTile), findsNWidgets(2));+ expect(+ tester+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))+ .search+ .rows,+ hasLength(2),+ );await tester.sendKeyEvent(LogicalKeyboardKey.enter);await tester.pump();expect(app.activeSwarm, same(target));diff --git a/desktop/test/swarm_search_render_test.dart b/desktop/test/swarm_search_render_test.dartindex 50518fdf6..930826ef3 100644--- a/desktop/test/swarm_search_render_test.dart+++ b/desktop/test/swarm_search_render_test.dart@@ -250,12 +250,12 @@ void main() {).search!;final previous = search.selected!.id;- final visibleRows = find.byType(ListTile).evaluate().toSet();+ final visibleRows = find.byType(InkWell).evaluate().toSet();var fields = 0;var rows = 0;debugOnRebuildDirtyWidget = (element, _) {if (element.widget is TextField) fields++;- if (element.widget is ListTile && visibleRows.contains(element)) rows++;+ if (element.widget is InkWell && visibleRows.contains(element)) rows++;};try {await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);@@ -270,10 +270,10 @@ void main() {reason: 'Moving the highlight does not change the editor',);expect(rows, 2, reason: 'Only the old and new existing highlights changed');- final selected = tester.widget<ListTile>(- find.byKey(ValueKey(search.selected!.id)),- );- expect(selected.selected, isTrue);+ final selected = tester+ .element(find.byKey(ValueKey(search.selected!.id)))+ .findAncestorWidgetOfExactType<Semantics>()!;+ expect(selected.properties.selected, isTrue);expect(find.byKey(const ValueKey('swarm-search-count')), findsNothing);expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);expect(input, isEmpty);@@ -292,14 +292,14 @@ void main() {final field = find.byKey(const ValueKey('swarm-search-input'));await tester.enterText(field, 'Agent');await tester.pump(const Duration(milliseconds: 200));- final visibleRows = find.byType(ListTile).evaluate().where((element) {+ final visibleRows = find.byType(InkWell).evaluate().where((element) {final key = element.widget.key;return key is ValueKey<String> && key.value.startsWith('agent:');}).toSet();expect(visibleRows, isNotEmpty);var rowBuilds = 0;debugOnRebuildDirtyWidget = (element, _) {- if (element.widget is ListTile && visibleRows.contains(element)) {+ if (element.widget is InkWell && visibleRows.contains(element)) {rowBuilds++;}};@@ -359,17 +359,38 @@ void main() {.search!;final row = find.byKey(ValueKey(search.selected!.id));expect(find.byType(Checkbox), findsNothing);- expect(tester.widget<ListTile>(row).selected, isTrue);+ expect(+ tester+ .element(row)+ .findAncestorWidgetOfExactType<Semantics>()!+ .properties+ .selected,+ isTrue,+ );final height = tester.getSize(row).height;grid.AppTheme.palette.value = HarnessPalette.ember;await tester.pump();- expect(tester.widget<ListTile>(row).selected, isTrue);+ expect(+ tester+ .element(row)+ .findAncestorWidgetOfExactType<Semantics>()!+ .properties+ .selected,+ isTrue,+ );tester.platformDispatcher.textScaleFactorTestValue = 2;await tester.pump();expect(tester.getSize(row).height, greaterThan(height));expect(tester.widget<TextField>(field).controller!.text, 'Agent');expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);- expect(tester.widget<ListTile>(row).selected, isTrue);+ expect(+ tester+ .element(row)+ .findAncestorWidgetOfExactType<Semantics>()!+ .properties+ .selected,+ isTrue,+ );expect(tester.takeException(), isNull);await tester.pumpWidget(const SizedBox());app.dispose();@@ -394,7 +415,14 @@ void main() {app.dismissError(); // Publish the sessions assembled through the test seam.await tester.pump();final row = find.byKey(ValueKey(agentDestinationId('m', 'a0')));- expect(tester.widget<ListTile>(row).enabled, isTrue);+ expect(+ tester+ .element(row)+ .findAncestorWidgetOfExactType<Semantics>()!+ .properties+ .enabled,+ isTrue,+ );expect(find.descendant(of: row, matching: find.text('Already added')),findsNothing,diff --git a/desktop/test/terminal_panel_presentation_test.dart b/desktop/test/terminal_panel_presentation_test.dartindex 89325ad61..d074545f8 100644--- a/desktop/test/terminal_panel_presentation_test.dart+++ b/desktop/test/terminal_panel_presentation_test.dart@@ -1,6 +1,5 @@import 'package:flutter/material.dart';import 'package:flutter/services.dart';-import 'package:harness/widgets/transient_menus.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/core/models.dart';import 'package:harness/terminal/terminal_session.dart';@@ -9,10 +8,12 @@ import 'package:harness/widgets/terminal_panel.dart';import 'package:harness/widgets/pane_header_actions.dart';import 'package:xterm/xterm.dart';+import 'support/real_fonts.dart';import 'swarm_screen_test.dart' show terminal;import 'swarm_state_test.dart' show createApp;void main() {+ setUpAll(loadRealFonts);testWidgets('retained header uses current callbacks, names, projects and status',(tester) async {@@ -21,9 +22,7 @@ void main() {final revision = ValueNotifier(0);final closed = <int>[];final deleted = <int>[];- final restarted = <int>[];final zoomed = <int>[];- final composed = <int>[];tester.view.devicePixelRatio = 1;tester.view.physicalSize = const Size(1100, 700);addTearDown(tester.view.reset);@@ -38,10 +37,8 @@ void main() {compactHeader: true,onClose: () => closed.add(version),onDelete: () => deleted.add(version),- onRestart: () => restarted.add(version),onToggleZoom: () => zoomed.add(version),zoomed: version >= 2,- onToggleComposer: () => composed.add(version),),),),@@ -49,24 +46,16 @@ void main() {await tester.pump();revision.value = 1;await tester.pump();- // Every pane action is one ⋮ menu away.- for (final label in [- 'Show message composer',- 'Zoom Pane',- 'Restart Harness',- 'Stop Harness',- 'Close Pane',- ]) {- await tester.tap(find.byTooltip('Pane actions'));- await tester.pumpAndSettle();- await tester.tap(find.text(label));+ for (final label in ['Close Pane', 'Zoom Pane', 'Stop Harness']) {+ await tester.tap(find.byTooltip(label));await tester.pumpAndSettle();}expect(closed, [1]);expect(deleted, [1]);- expect(restarted, [1]);expect(zoomed, [1]);- expect(composed, [1]);+ expect(find.byTooltip('Pane actions'), findsNothing);+ expect(find.byTooltip('Restart Harness'), findsNothing);+ expect(find.byTooltip('Share harness'), findsNothing);session.agentName = 'Renamed terminal';app.machineStates['m']!.agents = [const Agent(@@ -85,11 +74,11 @@ void main() {revision.value = 2;await tester.pump();expect(find.text('Renamed terminal'), findsOneWidget);- expect(find.text('harness/codex-0922-1136'), findsOneWidget);+ expect(find.text('harness/codex-0922-1136'), findsNothing);expect(find.text('desktop'),- findsOneWidget,- reason: 'A subfolder shows as itself, beside its repository branch.',+ findsNothing,+ reason: 'Project context belongs to the shared workspace status line.',);expect(find.text('codex-0922-1136'), findsNothing);app.machineStates['m']!.agents = [@@ -111,8 +100,8 @@ void main() {await tester.pump();expect(find.text('harness'),- findsOneWidget,- reason: 'A worktree root shows as its repository, never its folder.',+ findsNothing,+ reason: 'Compact pane headers do not repeat project context.',);expect(find.text('codex-0922-1136'),@@ -137,7 +126,7 @@ void main() {];revision.value = 4;await tester.pump();- expect(find.text('harness'), findsOneWidget);+ expect(find.text('harness'), findsNothing);expect(find.text('tester/brave-otter'),findsNothing,@@ -159,7 +148,7 @@ void main() {];revision.value = 5;await tester.pump();- expect(find.text('harness'), findsOneWidget);+ expect(find.text('harness'), findsNothing);expect(find.textContaining('Detached'),findsNothing,@@ -175,7 +164,7 @@ void main() {);revision.value = 2;await tester.pump();- expect(find.byTooltip('Pane actions'), findsOneWidget);+ expect(find.byTooltip('Restore Pane'), findsOneWidget);session.status = TerminalSessionStatus.takenOver;revision.value = 3;await tester.pump();@@ -207,7 +196,7 @@ void main() {);for (final local in [true, false]) {testWidgets(- '${local ? 'local' : 'remote'} header keeps its details in view and its actions in the ⋮ menu',+ '${local ? 'local' : 'remote'} compact header keeps three ASCII controls without repeating context or moving its title',(tester) async {final app = createApp();app.stateOf('m')!.localOnly = local;@@ -250,50 +239,38 @@ void main() {find.byType(TerminalView),);final titleBounds = tester.getRect(title);- expect(find.text('harness'), findsOneWidget);- expect(find.text('main'), findsOneWidget);- if (local) {- // This computer goes without saying.- expect(find.text('Test host'), findsNothing);- expect(- tester.getRect(find.text('harness')).left,- greaterThan(titleBounds.right),- );- } else {- expect(- tester.getRect(find.text('Test host')).left,- greaterThan(titleBounds.right),- );- expect(- tester.getRect(find.text('harness')).left,- greaterThan(tester.getRect(find.text('Test host')).right),- );- }+ expect(find.text('harness'), findsNothing);+ expect(find.text('main'), findsNothing);+ expect(find.text('Test host'), findsNothing);expect(- tester.getRect(find.text('main')).left,- greaterThan(tester.getRect(find.text('harness')).right),+ find.descendant(of: controls, matching: find.byType(IconButton)),+ findsNothing,);- // One ⋮ menu, always in view, instead of a row of icons that took the details' place- // on hover.expect(- find.descendant(of: controls, matching: find.byType(IconButton)),- findsOneWidget,+ tester+ .widgetList<TextButton>(+ find.descendant(+ of: controls,+ matching: find.byType(TextButton),+ ),+ )+ .length,+ 3,);- expect(find.byTooltip('Pane actions').hitTestable(), findsOneWidget);- await tester.tap(find.byTooltip('Pane actions'));- await tester.pumpAndSettle();- expect(find.text('Stop Harness'), findsOneWidget);- expect(find.text('Share harness'), findsOneWidget);- // The details stay in view, and neither the title nor the terminal moves.- expect(find.text('main').hitTestable(), findsOneWidget);+ for (final label in ['Close Pane', 'Zoom Pane', 'Stop Harness']) {+ expect(find.byTooltip(label).hitTestable(), findsOneWidget);+ }+ expect(find.byTooltip('Share harness'), findsNothing);+ expect(find.text('main'), findsNothing);expect(tester.getRect(title), titleBounds);expect(tester.widget<TerminalView>(find.byType(TerminalView)),same(terminalWidget),);- await tester.sendKeyEvent(LogicalKeyboardKey.escape);- await tester.pumpAndSettle();- expect(find.text('Stop Harness'), findsNothing);+ final titleStyle = tester.widget<Text>(title).style!;+ expect(titleStyle.fontFamily, terminalFontStore.value.fontFamily);+ expect(titleStyle.fontSize, terminalFontStore.size);+ expect(titleStyle.fontWeight, FontWeight.normal);await tester.pumpWidget(const SizedBox());session.dispose();app.dispose();@@ -321,7 +298,6 @@ void main() {),];var zooms = 0;- var forks = 0;final revision = ValueNotifier(0);tester.view.devicePixelRatio = 1;tester.platformDispatcher.textScaleFactorTestValue = 1.7;@@ -339,8 +315,6 @@ void main() {focused: false,compactHeader: true,onToggleZoom: () => zooms++,- onFork: () => forks++,- onRestart: () {},onClose: () {},onDelete: () {},onToggleComposer: () {},@@ -353,34 +327,16 @@ void main() {expect(tester.getSize(title).width, greaterThan(64));expect(tester.takeException(), isNull);final titleBefore = tester.getRect(title);- final menu = find.widgetWithIcon(IconButton, Icons.more_vert);- await tester.tap(menu);- await tester.pumpAndSettle();- expect(find.text('Zoom Pane'), findsOneWidget);- expect(find.text('Show viewer'), findsOneWidget);- expect(find.text('Fork Harness'), findsOneWidget);- expect(find.text('Stop Harness'), findsOneWidget);+ final zoom = find.byTooltip('Zoom Pane');+ expect(zoom.hitTestable(), findsOneWidget);+ expect(find.byTooltip('Fork Harness'), findsNothing);+ expect(find.byTooltip('Stop Harness').hitTestable(), findsOneWidget);expect(tester.getRect(title), titleBefore);- await tester.tap(find.text('Zoom Pane'));+ Focus.of(tester.element(find.text('[]'))).requestFocus();+ await tester.pump();+ await tester.sendKeyEvent(LogicalKeyboardKey.space);await tester.pumpAndSettle();expect(zooms, [240.0, 280.0, 420.0].indexOf(width) + 1);- expect(find.text('Zoom Pane'), findsNothing);- await tester.tap(menu);- await tester.pumpAndSettle();- await tester.tap(find.text('Fork Harness'));- await tester.pumpAndSettle();- expect(forks, zooms);- // Escape and a click elsewhere both close it without choosing anything.- await tester.tap(menu);- await tester.pumpAndSettle();- await tester.sendKeyEvent(LogicalKeyboardKey.escape);- await tester.pumpAndSettle();- expect(find.text('Zoom Pane'), findsNothing);- await tester.tap(menu);- await tester.pumpAndSettle();- dismissTransientMenus();- await tester.pumpAndSettle();- expect(find.text('Zoom Pane'), findsNothing);expect(tester.takeException(), isNull);for (final status in [TerminalSessionStatus.opening,diff --git a/desktop/test/terminal_ui_typography_test.dart b/desktop/test/terminal_ui_typography_test.dartindex 6f931d0eb..56dc4ce41 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/swarm_catalog.dart';import 'package:harness/terminal/terminal_text.dart';import 'package:harness/widgets/delete_agent_dialog.dart';import 'package:harness/widgets/new_harness_form.dart';+import 'package:harness/widgets/pane_header_actions.dart';import 'package:harness/widgets/swarm_dialogs.dart';import 'package:harness/widgets/swarm_search_preview.dart';import 'package:harness/widgets/search_result_text.dart';@@ -62,13 +63,12 @@ void main() {grid.AppType.captionSize,};- /// Every visible text is on the fixed scale, in the system face or the- /// terminal's — and never at the terminal's own size unless it is one of the- /// scale's steps. Returns each text's size so a caller can compare them- /// across a terminal zoom.+ /// General UI keeps its fixed scale; workspace chrome follows the terminal.+ /// Return general UI sizes for comparisons across a terminal zoom.Map<String, double> checkText(WidgetTester tester, {int atLeast = 4}) {final sizes = <String, double>{};- void check(InlineSpan span, TextStyle inherited) {+ var checked = 0;+ void check(InlineSpan span, TextStyle inherited, {bool terminal = false}) {final style = inherited.merge(span.style);if (span is TextSpan) {final text = span.text?.trim();@@ -78,16 +78,26 @@ void main() {'lucide','LucideIcons',].any((icon) => style.fontFamily?.contains(icon) == true)) {- expect(ramp, contains(style.fontSize), reason: text);- expect(- [grid.AppType.sansFamily, grid.AppType.monoFamily],- contains(style.fontFamily),- reason: text,- );- sizes[text!] = style.fontSize!;+ checked++;+ if (terminal) {+ expect(style.fontSize, terminalFontStore.size, reason: text);+ expect(+ style.fontFamily,+ terminalFontStore.value.fontFamily,+ reason: text,+ );+ } else {+ expect(ramp, contains(style.fontSize), reason: text);+ expect(+ [grid.AppType.sansFamily, grid.AppType.monoFamily],+ contains(style.fontFamily),+ reason: text,+ );+ sizes[text!] = style.fontSize!;+ }}for (final child in span.children ?? <InlineSpan>[]) {- check(child, style);+ check(child, style, terminal: terminal);}}}@@ -111,7 +121,23 @@ void main() {.isNotEmpty) {continue;}- check((element.widget as RichText).text, const TextStyle());+ check(+ (element.widget as RichText).text,+ const TextStyle(),+ terminal: find+ .descendant(+ of: find.byWidgetPredicate(+ (widget) =>+ widget.key == const ValueKey('workspace-status-bar') ||+ widget.key == const ValueKey('terminal-pane-title') ||+ widget.key == const ValueKey('viewer-pane-title') ||+ widget is PaneHeaderActions,+ ),+ matching: find.byWidget(element.widget),+ )+ .evaluate()+ .isNotEmpty,+ );}for (final widget in tester.widgetList<EditableText>(find.byType(EditableText),@@ -122,7 +148,7 @@ void main() {terminalFontStore.size,}, contains(widget.style.fontSize));}- expect(sizes.length, greaterThanOrEqualTo(atLeast));+ expect(checked, greaterThanOrEqualTo(atLeast));expect(tester.takeException(), isNull);return sizes;}@@ -230,7 +256,7 @@ void main() {});testWidgets(- 'tabs keep the UI scale while welcome and setup screens follow terminal zoom',+ 'tabs, welcome, and setup screens follow terminal zoom while general UI keeps its scale',(tester) async {final app = createApp();final map = MemoryKeymap();@@ -351,35 +377,42 @@ void main() {await tester.pumpWidget(const SizedBox());});- testWidgets('the native tabs are told nothing about the terminal font', (- tester,- ) async {- final updates = <Map<dynamic, dynamic>>[];- 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();- final map = MemoryKeymap();- addTearDown(app.dispose);- addTearDown(map.dispose);- app.adoptSessionForTest(terminal('a0', []));- await mount(tester, app, map, native: true);- selectFont(22, TerminalFontChoice.monaco);- await tester.pumpAndSettle();- // They are named in the system face, so the payload carries no font at all.- expect(updates.last.containsKey('fontFamily'), isFalse);- expect(updates.last.containsKey('fontSize'), isFalse);- expect(updates.last.containsKey('fontFallbacks'), isFalse);- await tester.pumpWidget(const SizedBox());- });+ testWidgets(+ 'native tabs receive the same live font and size as the terminal',+ (tester) async {+ final updates = <Map<dynamic, dynamic>>[];+ 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();+ final map = MemoryKeymap();+ addTearDown(app.dispose);+ addTearDown(map.dispose);+ app.adoptSessionForTest(terminal('a0', []));+ await mount(tester, app, map, native: true);+ selectFont(22, TerminalFontChoice.monaco);+ await tester.pumpAndSettle();+ expect(updates.last['terminalStyle'], containsPair('family', 'Monaco'));+ expect(updates.last['terminalStyle'], containsPair('size', 22.0));+ selectFont(14, TerminalFontChoice.sfMono);+ await tester.pumpAndSettle();+ expect(+ updates.last['terminalStyle'],+ containsPair('family', terminalFontStore.value.fontFamily),+ );+ expect(updates.last['terminalStyle'], containsPair('size', 14.0));+ expect(updates.last.containsKey('fontFallbacks'), isFalse);+ await tester.pumpWidget(const SizedBox());+ },+ );}diff --git a/desktop/test/toolbar_onboarding_test.dart b/desktop/test/toolbar_onboarding_test.dartindex 3a5db6a28..a595b5705 100644--- a/desktop/test/toolbar_onboarding_test.dart+++ b/desktop/test/toolbar_onboarding_test.dart@@ -1,3 +1,5 @@+import 'support/workspace_tools.dart';+import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';@@ -252,7 +254,7 @@ void main() {expect(models, findsNothing);if (!native) {- await tap(tester, find.byTooltip('Harnesses'));+ await openWorkspaceTool(tester, 'harnesses');expect(find.byKey(const ValueKey('session-manager')), findsOneWidget);await key(tester, LogicalKeyboardKey.keyI, cmd: true);await tester.pumpAndSettle();@@ -292,19 +294,19 @@ void main() {);}- testWidgets('Models shortcut, welcome hint and toolbar follow a live remap', (+ testWidgets('Models shortcut and welcome hint follow a live remap', (tester,) async {final map = MemoryKeymap();addTearDown(map.dispose);await mount(tester, keymap: map);- expect(find.byTooltip('Models ⌘I'), findsOneWidget);+ expect(find.byTooltip('Models ⌘I'), findsNothing);map.apply('''{"bindings":[{"keys":"cmd+i","command":null},{"keys":"cmd+u","command":"models.list"}]}''');await tester.pumpAndSettle();- expect(find.byTooltip('Models ⌘U'), findsOneWidget);+ expect(find.byTooltip('Models ⌘U'), findsNothing);expect(find.text('⌘U'), findsOneWidget);await key(tester, LogicalKeyboardKey.keyI, cmd: true);expect(find.byType(ModelsPanel), findsNothing);@@ -369,9 +371,9 @@ void main() {await mount(tester);expect(find.byKey(const ValueKey('onboarding-harnesses-dot')),- findsOneWidget,+ findsNothing,);- await tap(tester, find.byTooltip('Harnesses'));+ await openWorkspaceTool(tester, 'harnesses');expect(find.text('Run your first harness'), findsOneWidget);expect(journey.completed(OnboardingStep.harnesses), isFalse);expect(@@ -380,7 +382,7 @@ void main() {);await key(tester, LogicalKeyboardKey.escape);await tester.pumpAndSettle();- await tap(tester, find.byTooltip('Harnesses'));+ await openWorkspaceTool(tester, 'harnesses');await tap(tester, find.text('New harness'));expect(find.byKey(const ValueKey('session-manager')), findsNothing);expect(find.byType(NewHarnessForm), findsOneWidget);@@ -397,7 +399,7 @@ void main() {if (hasPassword) app.password = '123456';await mount(tester);expect(journey.next, OnboardingStep.machines);- await tap(tester, find.byKey(const ValueKey('swarm-machines-button')));+ await openWorkspaceTool(tester, 'machines');await tap(tester, find.text('Set up access'));expect(find.text('On your other computer'), findsOneWidget);expect(find.textContaining('Connect to This Mac.'), findsOneWidget);@@ -444,7 +446,7 @@ void main() {];await mount(tester);expect(journey.next, OnboardingStep.machines);- await tap(tester, find.byKey(const ValueKey('swarm-machines-button')));+ await openWorkspaceTool(tester, 'machines');await tap(tester, find.text('Connect to M2'));final field = find.descendant(of: find.byKey(const ValueKey('machines-panel')),@@ -479,7 +481,7 @@ void main() {app.machines = [...app.machines, source];await mount(tester);expect(journey.next, OnboardingStep.machines);- await tap(tester, find.byKey(const ValueKey('swarm-machines-button')));+ await openWorkspaceTool(tester, 'machines');expect(find.text('Open Harness on M2, then check again.'),findsOneWidget,@@ -508,14 +510,11 @@ void main() {localHarness();await app.modelManager.refresh();await mount(tester);- await tap(tester, find.byKey(const ValueKey('swarm-machines-button')));+ await openWorkspaceTool(tester, 'machines');await tap(tester, find.byTooltip('Dismiss suggestion'));expect(journey.next, OnboardingStep.models);- expect(- find.byKey(const ValueKey('onboarding-models-dot')),- findsOneWidget,- );- await tap(tester, find.byKey(const ValueKey('swarm-models-button')));+ expect(find.byKey(const ValueKey('onboarding-models-dot')), findsNothing);+ await openWorkspaceTool(tester, 'models');expect(find.byType(ModelsPanel), findsOneWidget);expect(find.byType(OnboardingCard), findsOneWidget);expect(find.text('Power a harness with local AI'), findsOneWidget);diff --git a/desktop/test/web_pane_test.dart b/desktop/test/web_pane_test.dartindex 221367a96..5e9bedd68 100644--- a/desktop/test/web_pane_test.dart+++ b/desktop/test/web_pane_test.dart@@ -3,7 +3,6 @@// once the person closes it, and taken down with the agent.import 'package:flutter/material.dart';-import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/state/app_state.dart';@@ -328,21 +327,16 @@ void main() {expect(find.text('http://127.0.0.1:4179/'), findsOneWidget);// Its own close control, and no way to end an agent from it.expect(find.byTooltip('Close viewer'), findsOneWidget);- // This split is narrow: the terminal keeps its actions in the menu.- final actions = tester.widget<IconButton>(- find.widgetWithIcon(IconButton, Icons.more_horiz),+ // The ASCII stop control belongs only to the harness. Viewer visibility+ // is also available through View and command search.+ expect(find.byTooltip('Stop Harness'), findsOneWidget);+ expect(+ find.descendant(+ of: find.byType(WebPanePanel),+ matching: find.byTooltip('Stop Harness'),+ ),+ findsNothing,);- actions.focusNode!.requestFocus();- await tester.pump();- await tester.sendKeyEvent(LogicalKeyboardKey.enter);- await tester.pumpAndSettle();- expect(find.text('Stop Harness'), findsOneWidget);- expect(find.text('Hide viewer'), findsOneWidget);- await tester.sendKeyEvent(LogicalKeyboardKey.escape);- await tester.pumpAndSettle();- // The verdict is the viewer's to show — chip and strip in its header,- // nothing on the terminal's — and the terminal's header carries the- // control that hides and shows the viewer.expect(find.byKey(const ValueKey('pane-status')), findsNothing);await _synced(app,diff --git a/desktop/test/workspace_pull_request_test.dart b/desktop/test/workspace_pull_request_test.dartnew file mode 100644index 000000000..d2c28d5c8--- /dev/null+++ b/desktop/test/workspace_pull_request_test.dart@@ -0,0 +1,156 @@+import 'dart:async';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/core/pull_request_status.dart';+import 'package:harness/state/terminal_pane.dart';+import 'package:harness/state/workspace_pull_request.dart';++import 'swarm_state_test.dart' show createApp;++Map<String, dynamic> found(int number, [String state = 'Open']) => {+ 'status': 'found',+ 'number': number,+ 'state': state,+ 'url': 'https://github.com/acme/repo/pull/$number',+};++void main() {+ test('only valid PR states and GitHub links are actionable', () {+ for (final state in ['Draft', 'Open', 'Merged', 'Closed']) {+ expect(+ PullRequestStatus.fromResult(found(298, state))!.label,+ 'PR #298 · $state',+ );+ }+ for (final invalid in [+ {...found(1), 'state': 'Unknown'},+ {...found(1), 'number': -1},+ {...found(1), 'url': 'https://github.com/acme/repo/pull/2'},+ {...found(1), 'url': 'http://github.com/acme/repo/pull/1'},+ {...found(1), 'url': 'https://github.com.evil.test/acme/repo/pull/1'},+ {...found(1), 'url': 'https://[email protected]/acme/repo/pull/1'},+ {'status': 'none'},+ {'status': 'unavailable'},+ ]) {+ expect(PullRequestStatus.fromResult(invalid), isNull);+ }+ });++ testWidgets(+ 'focused PR follows the viewer owner, caches switches, refreshes, and clears',+ (tester) async {+ final app = createApp();+ app.stateOf('m')!.agents = const [+ Agent(+ id: 'a',+ name: 'A',+ engine: 'codex',+ project: AgentProject(+ name: 'repo',+ cwd: '/repo',+ root: '/repo',+ branch: 'feature',+ ),+ ),+ Agent(+ id: 'b',+ name: 'B',+ engine: 'claude',+ project: AgentProject(name: 'notes', cwd: '/notes'),+ ),+ ];+ app.activeSwarm.panes.addAll([+ TerminalPane(id: 1, machineId: 'm', agentId: 'a'),+ TerminalPane(id: 2, machineId: 'm', agentId: 'b'),+ TerminalPane(+ id: 3,+ machineId: 'm',+ kind: PaneKind.web,+ ownerAgentId: 'a',+ ),+ ]);+ app.activeSwarm.focusedPaneId = 1;+ final reads = <(String, String)>[];+ final controller = WorkspacePullRequest(+ app,+ read: (machine, agent) async {+ reads.add((machine, agent));+ return found(298, reads.length == 1 ? 'Open' : 'Merged');+ },+ );+ await tester.pump();+ expect(controller.value!.state, 'Open');+ app.focusPane(3);+ await tester.pump();+ expect(reads, [('m', 'a')]);+ expect(controller.value!.number, 298);+ app.focusPane(2);+ expect(controller.value, isNull);+ app.focusPane(1);+ expect(controller.value!.number, 298);+ expect(reads, hasLength(1));+ await tester.pump(const Duration(seconds: 60));+ expect(controller.value!.state, 'Merged');+ expect(reads, hasLength(2));+ app.newSwarm();+ expect(controller.value, isNull);+ controller.dispose();+ app.dispose();+ await tester.pump(const Duration(seconds: 60));+ expect(reads, hasLength(2));+ },+ );++ testWidgets('branch changes and disposal reject old PR replies', (+ tester,+ ) async {+ final app = createApp();+ void branch(String name) {+ app.stateOf('m')!.agents = [+ Agent(+ id: 'a',+ name: 'A',+ engine: 'codex',+ project: AgentProject(+ name: 'repo',+ cwd: '/repo',+ root: '/repo',+ branch: name,+ ),+ ),+ ];+ }++ branch('old');+ app.activeSwarm.panes.add(+ TerminalPane(id: 1, machineId: 'm', agentId: 'a'),+ );+ app.activeSwarm.focusedPaneId = 1;+ final replies = <Completer<Map<String, dynamic>>>[];+ final controller = WorkspacePullRequest(+ app,+ read: (_, _) {+ final reply = Completer<Map<String, dynamic>>();+ replies.add(reply);+ return reply.future;+ },+ );+ branch('new');+ app.focusPane(1, reveal: true);+ replies[1].complete(found(2));+ await tester.pump();+ replies[0].complete(found(1, 'Merged'));+ await tester.pump();+ expect(controller.value!.number, 2);+ branch('third');+ app.focusPane(1, reveal: true);+ expect(controller.value, isNull);+ controller.dispose();+ replies[2].complete(found(3));+ await tester.pump();+ app.dispose();+ await tester.pump(const Duration(seconds: 60));+ expect(replies, hasLength(3));+ });+}diff --git a/desktop/test/workspace_status_test.dart b/desktop/test/workspace_status_test.dartnew file mode 100644index 000000000..8604876df--- /dev/null+++ b/desktop/test/workspace_status_test.dart@@ -0,0 +1,572 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/shared/theme/appearance_prefs_store.dart';+import 'package:harness/shared/theme/prompt_style.dart';+import 'package:harness/shared/theme/status_line_style.dart';+import 'package:harness/state/swarm.dart';+import 'package:harness/state/terminal_pane.dart';+import 'package:harness/state/workspace_status.dart';+import 'package:harness/widgets/grid_model_picker.dart';+import 'package:harness/widgets/terminal_panel.dart';+import 'package:harness/widgets/status_line.dart';+import 'package:harness/widgets/pull_request_badge.dart';+import 'package:harness/ws/ws_conn.dart';++import 'swarm_state_test.dart' show createApp, MemoryStore;+import 'swarm_screen_test.dart' show mount, terminal;++class _PRConnection extends WsConn {+ _PRConnection()+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: 'm',+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );+ int reads = 0;+ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async {+ if (type != 'git_pull_request') return {};+ reads++;+ return {+ 'status': 'found',+ 'number': 298,+ 'state': 'Merged',+ 'url': 'https://github.com/acme/repo/pull/298',+ };+ }+}++void main() {+ for (final native in [false, true]) {+ testWidgets(+ 'focused PR uses every selected theme without duplicate pane lookups (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 null;+ },+ );+ addTearDown(+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(+ channel,+ null,+ ),+ );+ final original = appearancePrefsStore.value;+ addTearDown(() => appearancePrefsStore.value = original);+ final connection = _PRConnection();+ final app = createApp(connectionForTest: (_) => connection);+ addTearDown(app.dispose);+ app.stateOf('m')!.agents = const [+ Agent(+ id: 'a0',+ name: 'Feature',+ engine: 'codex',+ project: AgentProject(+ name: 'repo',+ cwd: '/repo',+ root: '/repo',+ branch: 'feature',+ ),+ ),+ ];+ final pane = app.adoptSessionForTest(terminal('a0', []));+ await mount(tester, app, nativeTabs: native);+ await tester.pump();+ expect(find.byType(PullRequestBadge), findsNothing);+ for (final style in StatusLineStyle.values) {+ appearancePrefsStore.value = original.copyWith(+ prompt: PromptPrefs(statusStyle: style),+ );+ await tester.pump();+ if (native) {+ final pr = updates.last['pullRequest'] as Map;+ expect(pr['text'], 'PR #298 · Merged');+ expect(pr['url'], 'https://github.com/acme/repo/pull/298');+ expect(pr['segmented'], style.segmented);+ expect(+ (pr['segments'] as List).any(+ (s) => (s as Map)['background'] != null,+ ),+ style.segmented,+ );+ } else {+ final badge = find.byKey(const ValueKey('workspace-pull-request'));+ final rendered = tester.widget<StatusLine>(+ find.descendant(of: badge, matching: find.byType(StatusLine)),+ );+ expect(rendered.parts.style, style);+ expect(rendered.parts.text, 'PR #298 · Merged');+ for (final width in [520.0, 1280.0]) {+ tester.view.physicalSize = Size(width, 800);+ await tester.pump(const Duration(milliseconds: 100));+ expect(tester.takeException(), isNull);+ final contextRight = tester+ .getRect(find.byKey(const ValueKey('workspace-pane-context')))+ .right;+ expect(+ tester.getRect(badge).left,+ style.segmented+ ? closeTo(contextRight, .01)+ : greaterThan(contextRight),+ );+ }+ }+ }+ expect(connection.reads, 1);+ app.renameSwarm(app.activeSwarmId, 'Release');+ // Let the terminal finish its resize debounce after the last layout.+ await tester.pump(const Duration(milliseconds: 100));+ if (native) {+ expect(+ ((updates.last['tabs'] as List).single as Map)['label'],+ '1:Release',+ );+ } else {+ expect(find.text('1:Release'), findsOneWidget);+ }+ app.newSwarm();+ await tester.pump();+ if (native) {+ expect(updates.last['pullRequest'], isNull);+ } else {+ expect(+ find.byKey(const ValueKey('workspace-pull-request')),+ findsNothing,+ );+ }+ expect(app.allPanes, contains(pane));+ await tester.pumpWidget(const SizedBox());+ },+ );+ }++ test(+ 'custom tab labels survive pane changes, closing, and saved layout restore',+ () async {+ final storage = MemoryStore();+ final app = createApp(store: storage);+ await app.addAgentToSwarm('m', 'a0');+ final id = app.activeSwarmId;+ app.renameSwarm(id, 'My release');+ await app.addAgentToSwarm('m', 'a1');+ expect(workspaceTabNames(app)[id], 'My release');+ await app.closeSwarm(id);+ app.reopenClosedSwarm();+ expect(workspaceTabNames(app)[id], 'My release');+ await app.flushPaneLayout();+ app.dispose();+ final restored = createApp(store: storage);+ addTearDown(restored.dispose);+ await restored.restorePaneLayoutForTest();+ expect(workspaceTabNames(restored)[id], 'My release');+ expect(+ restored.swarms.singleWhere((s) => s.id == id).nameIsCustom,+ isTrue,+ );+ },+ );++ test(+ 'status project names follow remote, subfolder, and ordinary folder rules',+ () {+ const root = AgentProject(+ name: 'local-clone',+ cwd: '/work/local-clone',+ root: '/work/local-clone',+ remote: 'github.com/team/api',+ branch: 'main',+ );+ const linked = AgentProject(+ name: 'local-clone',+ cwd: '/worktrees/random-name',+ root: '/worktrees/random-name',+ remote: 'github.com/team/api',+ branch: 'fix',+ worktree: true,+ );+ const subfolder = AgentProject(+ name: 'local-clone',+ cwd: '/work/local-clone/desktop/',+ root: '/work/local-clone',+ remote: 'github.com/team/api',+ );+ const local = AgentProject(+ name: 'local-repo',+ cwd: '/local-repo',+ root: '/local-repo',+ );+ const folder = AgentProject(name: 'notes', cwd: '/work/notes');+ expect(+ [root.label, linked.label, subfolder.label, local.label, folder.label],+ ['api', 'api', 'desktop', 'local-repo', 'notes'],+ );+ final app = createApp();+ addTearDown(app.dispose);+ app.stateOf('m')!.agents = const [+ Agent(id: 'a', name: 'Fix', engine: 'codex', project: linked),+ ];+ app.activeSwarm.panes.add(+ TerminalPane(id: 1, machineId: 'm', agentId: 'a'),+ );+ app.activeSwarm.focusedPaneId = 1;+ final context = WorkspacePaneContext.focused(app)!;+ expect(context.text, 'OpenAI Test host:api (fix)');+ expect(context.detail, contains('/worktrees/random-name'));+ for (final style in StatusLineStyle.values) {+ final text = context.format(PromptPrefs(statusStyle: style)).text;+ expect(text, isNot(contains('random-name')));+ expect(text, isNot(contains('[worktree]')));+ }+ },+ );++ test('project names distinguish code tabs while a distinct harness keeps its type', () {+ final app = createApp();+ addTearDown(app.dispose);+ app.stateOf('m')!.agents = const [+ Agent(+ id: 'a',+ name: 'a',+ engine: 'codex',+ project: AgentProject(name: 'api', cwd: '/api'),+ ),+ Agent(+ id: 'b',+ name: 'b',+ engine: 'claude',+ project: AgentProject(name: 'web', cwd: '/web'),+ ),+ Agent(+ id: 'c',+ name: 'c',+ engine: 'claude',+ dsh: 'autonomous/blender',+ project: AgentProject(name: 'scene', cwd: '/scene'),+ ),+ ];+ app.swarms.clear();+ for (final id in ['a', 'b', 'c']) {+ app.swarms.add(+ Swarm(id: id)+ ..panes.add(+ TerminalPane(id: id.codeUnitAt(0), machineId: 'm', agentId: id),+ ),+ );+ }+ expect(workspaceTabNames(app), {'a': 'api', 'b': 'web', 'c': 'blender'});+ final scene = app.swarms.last;+ for (var id = 0; id < 4; id++) {+ scene.panes.add(+ TerminalPane(+ id: id,+ machineId: 'm',+ kind: PaneKind.web,+ ownerAgentId: 'a',+ ),+ );+ scene.focusedPaneId = id;+ expect(workspaceTabNames(app)['c'], 'blender');+ }+ app.renameSwarm('a', 'My workspace');+ expect(workspaceTabNames(app)['a'], 'My workspace');+ expect(app.swarms.first.name, 'My workspace');+ });++ test('machine names distinguish the same project on different machines', () {+ final app = createApp();+ addTearDown(app.dispose);+ app.swarms.clear();+ for (final id in ['laptop', 'server']) {+ final machine = Machine(+ machineId: id,+ name: id,+ authMode: MachineAuthMode.remote,+ );+ app.machineStates[id] = MachineState(machine)+ ..agents = const [+ Agent(+ id: 'a',+ name: 'a',+ engine: 'codex',+ project: AgentProject(name: 'api', cwd: '/api'),+ ),+ ];+ app.swarms.add(+ Swarm(id: id)+ ..panes.add(TerminalPane(id: 1, machineId: id, agentId: 'a')),+ );+ }+ expect(workspaceTabNames(app), {'laptop': 'laptop', 'server': 'server'});+ });++ test('a shared machine wins over a minority project or harness type', () {+ final app = createApp();+ addTearDown(app.dispose);+ app.stateOf('m')!.agents = const [+ Agent(+ id: 'a',+ name: 'a',+ engine: 'codex',+ project: AgentProject(name: 'api', cwd: '/api'),+ ),+ Agent(+ id: 'b',+ name: 'b',+ engine: 'claude',+ project: AgentProject(name: 'web', cwd: '/web'),+ ),+ Agent(id: 'c', name: 'c', engine: 'claude', dsh: 'autonomous/blender'),+ ];+ app.activeSwarm.panes.addAll([+ for (final id in ['a', 'b', 'c'])+ TerminalPane(id: id.codeUnitAt(0), machineId: 'm', agentId: id),+ ]);+ expect(workspaceTabNames(app).values.single, 'Test host');+ });++ test('status presets retain real metadata and omit missing Git context', () {+ const expected = {+ StatusLineStyle.standard: 'OpenAI M2:app (main)',+ StatusLineStyle.robbyrussell: 'OpenAI M2 ➜ app git:(main)',+ StatusLineStyle.pure: 'OpenAI M2 app main ❯',+ StatusLineStyle.agnoster: 'OpenAI M2 app main',+ StatusLineStyle.powerlevel10k: 'OpenAI M2 app main',+ };+ for (final format in StatusLineStyle.values) {+ expect(+ statusLineParts(+ provider: 'OpenAI',+ machine: 'M2',+ project: 'app',+ branch: 'main',+ style: format,+ ).text,+ expected[format],+ );+ expect(+ statusLineParts(+ provider: 'OpenAI',+ machine: '',+ project: 'notes',+ style: format,+ ).text,+ isNot(anyOf(contains('git'), contains('()'), contains('[worktree]'))),+ );+ final prefs = PromptPrefs(+ statusStyle: format,+ machine: false,+ color: false,+ );+ expect(PromptPrefs.fromJson(prefs.toJson()), prefs);+ }+ expect(+ PromptPrefs.fromJson({'statusStyle': 'future'}).statusStyle,+ StatusLineStyle.standard,+ );+ expect(+ PromptPrefs.fromJson({'style': 'powerline'}).statusStyle,+ StatusLineStyle.standard,+ );+ });++ test('dominant type groups code engines, excludes viewers, and breaks ties by pane order', () {+ final app = createApp();+ addTearDown(app.dispose);+ app.stateOf('m')!.agents = const [+ Agent(id: 'a', name: 'Code', engine: 'codex'),+ Agent(id: 'b', name: 'Code', engine: 'claude'),+ Agent(+ id: 'c',+ name: 'Scene',+ engine: 'claude',+ dsh: 'autonomous/blender',+ ),+ Agent(id: 'd', name: 'Scene', engine: 'codex', dsh: 'autonomous/blender'),+ ];+ final tab = app.activeSwarm;+ tab.panes.addAll([+ TerminalPane(id: 1, machineId: 'm', agentId: 'a'),+ TerminalPane(id: 2, machineId: 'm', agentId: 'b'),+ TerminalPane(id: 3, machineId: 'm', agentId: 'c'),+ for (var index = 4; index < 8; index++)+ TerminalPane(+ id: index,+ machineId: 'm',+ kind: PaneKind.web,+ ownerAgentId: 'c',+ ),+ ]);+ expect(tabHarnessType(app, tab), 'code');+ tab.panes.add(TerminalPane(id: 8, machineId: 'm', agentId: 'd'));+ for (final pane in tab.panes) {+ tab.focusedPaneId = pane.id;+ expect(tabHarnessType(app, tab), 'code');+ }+ tab.panes.removeAt(0);+ expect(tabHarnessType(app, tab), 'blender');+ tab.panes.removeWhere((pane) => !pane.isWeb);+ expect(tabHarnessType(app, tab), 'new');+ expect(tabHarnessType(app, Swarm(id: 'store', kind: 'store')), 'store');+ });++ test('focused viewers inherit owner context, using the compact project name and full path tooltip', () {+ final app = createApp();+ addTearDown(app.dispose);+ app.stateOf('m')!.agents = const [+ Agent(+ id: 'a',+ name: 'Scene',+ engine: 'claude',+ dsh: 'autonomous/blender',+ project: AgentProject(+ name: 'scene',+ cwd: '/worktrees/scene-light',+ root: '/worktrees/scene-light',+ branch: 'lighting',+ ),+ ),+ Agent(+ id: 'b',+ name: 'Notes',+ engine: 'codex',+ project: AgentProject(name: 'notes', cwd: '/work/notes'),+ ),+ ];+ final tab = app.activeSwarm;+ tab.panes.addAll([+ TerminalPane(id: 1, machineId: 'm', agentId: 'a'),+ TerminalPane(+ id: 2,+ machineId: 'm',+ kind: PaneKind.web,+ ownerAgentId: 'a',+ ),+ TerminalPane(id: 3, machineId: 'm', agentId: 'b'),+ ]);+ tab.focusedPaneId = 1;+ final owner = WorkspacePaneContext.focused(app)!;+ expect(owner.text, 'Anthropic Test host:scene (lighting)');+ tab.focusedPaneId = 2;+ expect(WorkspacePaneContext.focused(app)!.text, owner.text);+ expect(WorkspacePaneContext.focused(app)!.agentId, 'a');+ tab.focusedPaneId = 3;+ expect(WorkspacePaneContext.focused(app)!.text, 'OpenAI Test host:notes');+ tab.panes.clear();+ expect(WorkspacePaneContext.focused(app), isNull);+ });++ testWidgets(+ 'compact tabs sit to the left of one focused context and switch workspaces',+ (tester) async {+ final app = createApp();+ addTearDown(app.dispose);+ app.adoptSessionForTest(terminal('a0', []));+ final first = app.activeSwarm;+ app.newSwarm();+ app.adoptSessionForTest(terminal('a1', []));+ await mount(tester, app);+ expect(find.text('1:code'), findsOneWidget);+ expect(find.text('2:code'), findsOneWidget);+ final context = find.byKey(const ValueKey('workspace-pane-context'));+ expect(+ tester.getRect(context).left,+ greaterThan(tester.getRect(find.text('2:code')).right),+ );+ final secondTab = find.byKey(ValueKey(app.activeSwarmId));+ expect(tester.getSize(secondTab).width, lessThan(150));+ expect(find.byKey(const ValueKey('swarm-models-button')), findsNothing);+ expect(find.byKey(const ValueKey('swarm-machines-button')), findsNothing);+ expect(find.byKey(const ValueKey('swarm-store-button')), findsNothing);+ expect(+ find.descendant(+ of: find.byType(TerminalPanel),+ matching: find.byType(GridModelPicker),+ ),+ findsNothing,+ );+ await tester.tap(find.text('1:code'));+ await tester.pump(const Duration(milliseconds: 350));+ expect(app.activeSwarm, same(first));+ for (final width in [520.0, 1280.0]) {+ tester.view.physicalSize = Size(width, 800);+ await tester.pump(const Duration(milliseconds: 100));+ expect(tester.takeException(), isNull);+ }+ await tester.pump(const Duration(milliseconds: 100));+ await tester.pumpWidget(const SizedBox());+ },+ );++ testWidgets(+ 'native status payload follows focus and keeps the type label short',+ (tester) async {+ final updates = <Map<String, dynamic>>[];+ const channel = MethodChannel('harness/swarm_tabs');+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(channel, (call) async {+ if (call.method == 'update') {+ updates.add(Map<String, dynamic>.from(call.arguments as Map));+ }+ return null;+ });+ addTearDown(+ () => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .setMockMethodCallHandler(channel, null),+ );+ final app = createApp();+ addTearDown(app.dispose);+ app.adoptSessionForTest(terminal('a0', []));+ app.adoptSessionForTest(terminal('a1', []));+ await mount(tester, app, nativeTabs: true);+ final tab = (updates.last['tabs'] as List).single as Map;+ expect(tab['label'], '1:code');+ expect(+ (updates.last['focusedContext'] as Map)['text'],+ 'OpenAI Test host',+ );+ expect(+ updates.last['terminalStyle'],+ containsPair('family', isA<String>()),+ );+ final originalPrefs = appearancePrefsStore.value;+ addTearDown(() => appearancePrefsStore.value = originalPrefs);+ appearancePrefsStore.value = originalPrefs.copyWith(+ prompt: originalPrefs.prompt.copyWith(+ statusStyle: StatusLineStyle.pure,+ machine: false,+ color: false,+ ),+ );+ await tester.pump();+ expect((updates.last['focusedContext'] as Map)['text'], 'OpenAI');+ final colors = updates.last['terminalStyle'] as Map;+ final segments =+ (updates.last['focusedContext'] as Map)['segments'] as List;+ expect(+ segments.map((part) => (part as Map)['foreground']),+ everyElement(colors['foreground']),+ );+ app.newSwarm();+ await tester.pump();+ expect(updates.last['focusedContext'], isNull);+ expect(((updates.last['tabs'] as List).last as Map)['label'], '2:new');+ await tester.pumpWidget(const SizedBox());+ },+ );+}diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swiftindex c62a20b55..671390cda 100644--- a/desktop/tool/swarm_titlebar_checks.swift+++ b/desktop/tool/swarm_titlebar_checks.swift@@ -63,39 +63,35 @@ private extension SwarmTabButton {try checkTitlebar(actions == ["select", "rename"], "A tab double-click selects and renames exactly once")try checkTitlebar(probe.mouseUps == 0,"Tab mouse-up events cannot reach the window's titlebar double-click handler")- try checkTitlebar(!selectButton.mouseDownCanMoveWindow && !closeButton.mouseDownCanMoveWindow,+ try checkTitlebar(!selectButton.mouseDownCanMoveWindow,"Tab action buttons opt out of automatic window movement")}func checkAccessibility(expectedName: String, active: Bool) throws {try checkTitlebar(accessibilityLabel() == expectedName, "Tab group name is available before paint")let children = accessibilityChildren()?.compactMap { $0 as? NSButton } ?? []- try checkTitlebar(children.count == 2, "Selection and close are separate accessible buttons")+ try checkTitlebar(children.count == 1, "A tab exposes one full-width selection button")try checkTitlebar(children[0].accessibilityLabel() == "Select \(expectedName)", "Selection button has current name")try checkTitlebar(children[0].accessibilityValue() as? String == (active ? "Selected" : ""), "Selection value is current")- try checkTitlebar(children[1].accessibilityLabel() == "Close \(expectedName)", "Close button has current name")}func checkEnabled(_ enabled: Bool) throws {try checkTitlebar(selectButton.isEnabled == enabled, "Select button obeys modal state")- try checkTitlebar(closeButton.isEnabled == enabled, "Close button obeys modal state")for item in menu?.items ?? [] {try checkTitlebar(validateMenuItem(item) == enabled, "Tab context menu obeys modal state")}}- func checkCloseVisibility(_ visible: Bool) throws {- try checkTitlebar(closeButton.showsGlyph == visible,- "A tab reveals its close mark only for hover or keyboard focus")- try checkTitlebar(closeButton.isHidden == compact,- "Only compact icon-only tabs hide the close control")- try checkTitlebar(closeButton.accessibilityLabel() == "Close \(name)",- "The close action retains its accessible label")+ func checkCenteredLabel() throws {+ let paragraph = label.attribute(.paragraphStyle, at: 0, effectiveRange: nil) as? NSParagraphStyle+ try checkTitlebar(paragraph?.alignment == .center, "The tab label is centered")+ try checkTitlebar(selectButton.frame == bounds, "Selection spans the whole tab without a close slot")+ try checkTitlebar(subviews.count == 1, "Hover and keyboard focus never add a close button")}func clickBothActions() {selectButton.performClick(nil)- closeButton.performClick(nil)+ closeSwarm()}}@@ -118,37 +114,25 @@ private extension SwarmTabStrip {func checkSharedTypography() throws {let menuFont = NSFont.menuFont(ofSize: 0)- let system = NSFont.systemFont(ofSize: NSFont.systemFontSize)- update(["tabs": [["id": "font-tab", "name": "Typography"]], "activeId": "font-tab", "enabled": true])- let tab = tabs[0]- try checkTitlebar(tab.labelFont.pointSize == system.pointSize && tab.labelFont.familyName == system.familyName,- "A tab is named in the system face, like every other Mac window's tabs")- update(["tabs": [["id": "font-tab", "name": "Typography"], ["id": "other-tab", "name": "Other"]],- "activeId": "font-tab", "enabled": true])- let selectedFont = tabs[0].drawnFont- let restingFont = tabs[1].drawnFont- try checkTitlebar(selectedFont != nil && selectedFont == restingFont,- "The selected tab keeps the same weight; its fill and ink mark it")- try checkTitlebar(storeButton.font?.pointSize == system.pointSize && storeButton.font?.familyName == system.familyName,- "The Store action beside the tabs takes the same face")- try checkTitlebar(tab.menu?.font.familyName == menuFont.familyName && tab.menu?.font.pointSize == menuFont.pointSize,- "Native tab menu keeps the system menu font")- let history = SwarmHistoryEntry(["id": "font", "title": "Project", "machineName": "Machine"])!- let font = history.menuTitle().attribute(.font, at: 0, effectiveRange: nil) as! NSFont- try checkTitlebar(font == menuFont, "Native history keeps the system menu font")- let item = NSMenuItem()- let row = SwarmHistoryMenuRow(item: item, entry: history, width: 400)- try checkTitlebar(row.machineFrame.minY >= 0 && row.machineFrame.maxY <= row.bounds.height,- "Native history text fits its row")+ update(["tabs": [["id": "font-tab", "name": "Typography", "label": "1:code"],+ ["id": "other", "name": "Other", "label": "2:blender"]],+ "activeId": "font-tab", "enabled": true,+ "terminalStyle": ["family": "Menlo", "size": 16.0,+ "foreground": Int64(0xffd0d0d0), "selection": Int64(0xff444444)]])+ try checkTitlebar(tabs[0].labelFont.pointSize == 16 && tabs[0].labelFont.familyName == "Menlo",+ "Numbered tabs follow the selected terminal font and size")+ try checkTitlebar(tabs[0].drawnFont == tabs[1].drawnFont && contextButton.font == tabs[0].labelFont,+ "Active tabs, inactive tabs, and pane context share one font")+ try checkTitlebar(tabs[0].frame.width < tabs[1].frame.width,+ "Each tab occupies its own text width and fixed cell gutters")+ try checkTitlebar(tabs[0].menu?.font == menuFont, "Native context menus retain the system menu font")}func checkStartupPalette(_ expected: SwarmNativePalette) throws {- try checkTitlebar(palette == expected && newButton.contentTintColor == expected.accent && sessionsButton.contentTintColor == sessionsButton.iconTint,- "Initial search and new-swarm colors use the saved palette")- try checkTitlebar(tabs.isEmpty && !actionsEnabled && !newButton.isEnabled && !sessionsButton.isEnabled,- "Initial palette setup does not create or enable workspace controls")+ try checkTitlebar(palette == expected, "Startup uses the saved workspace palette")+ try checkTitlebar(tabs.isEmpty && !actionsEnabled && !newButton.isEnabled,+ "Palette setup does not create or enable workspace controls")}-func checkWindowGeometry(_ window: NSWindow) throws {let stripFrame = convert(bounds, to: nil)let close = window.standardWindowButton(.closeButton)!@@ -157,11 +141,6 @@ private extension SwarmTabStrip {let zoomFrame = zoom.convert(zoom.bounds, to: nil)let newFrame = newButton.convert(newButton.bounds, to: nil)try checkTitlebar(bounds.height >= 40, "Native title bar leaves room around the pill actions")- for button in [storeButton] {- let labelWidth = (button.title as NSString).size(withAttributes: [.font: button.font!]).width- try checkTitlebar(button.frame.minY >= 6 && bounds.height - button.frame.maxY >= 6 && button.frame.width - labelWidth >= 32,- "\(button.title) has vertical breathing room and readable horizontal padding")- }// 10, which is where a Mac app starts its first control after the buttons: Safari's sidebar// toggle and Chrome's first tab both sit about there. It was 12 while the notifications bell// still led the strip.@@ -182,151 +161,119 @@ private extension SwarmTabStrip {}func runChecks() throws {- let rows = (0..<24).map { ["id": "swarm-\($0)", "name": "Swarm \($0)"] }+ let rows = (0..<24).map { ["id": "swarm-\($0)", "name": "Swarm \($0)", "label": "\($0 + 1):code"] }var events: [String] = []emit = { method, _ in events.append(method) }func state(_ rows: [[String: String]], active: String, enabled: Bool = true) -> [String: Any] {- ["tabs": rows, "activeId": active, "enabled": enabled, "attention": 2]+ ["tabs": rows, "activeId": active, "enabled": enabled,+ "focusedContext": ["text": "OpenAI M2:~/code/harness (main)",+ "segments": [["text": "OpenAI M2:~/code/harness (main)", "foreground": Int64(0xffdddddd)]],+ "detail": "Full project context", "canSelectModel": true]]}+ var prState = state(rows, active: "swarm-11")+ prState["pullRequest"] = ["text": "PR #298 · Merged", "segmented": true,+ "segments": [["text": "PR #298 · Merged", "foreground": Int64(0xffeeeeee), "background": Int64(0xffbc3fbc)]],+ "url": "https://github.com/acme/repo/pull/298", "canSelectModel": true]+ update(prState)+ try checkTitlebar(!pullRequestButton.isHidden && pullRequestButton.isEnabled,+ "A focused PR has a separate enabled action")+ try checkTitlebar(contextButton.frame.maxX < pullRequestButton.frame.minX &&+ pullRequestButton.frame.maxX <= bounds.width, "Plain context keeps a space before its PR action")+ prState["focusedContext"] = ["text": "OpenAI M2 app main", "segmented": true,+ "segments": [+ ["text": "OpenAI M2", "foreground": Int64(0xffeeeeee), "background": Int64(0xff000000)],+ ["text": "app", "foreground": Int64(0xffeeeeee), "background": Int64(0xff3465a4)],+ ["text": "main", "foreground": Int64(0xff000000), "background": Int64(0xff4e9a06)],+ ], "canSelectModel": true]+ let originalSize = frame.size+ for width in [CGFloat(520), CGFloat(1280)] {+ setFrameSize(NSSize(width: width, height: originalSize.height))+ update(prState)+ try checkTitlebar(abs(contextButton.frame.maxX - pullRequestButton.frame.minX) < 0.01,+ "Powerline context and PR are adjacent at width \(width)")+ try checkTitlebar(contextButton.nextBackground == pullRequestButton.firstBackground,+ "The closing arrow joins into the PR background")+ try checkTitlebar(newButton.frame.maxX < contextButton.frame.minX &&+ pullRequestButton.frame.maxX <= bounds.width, "Joined status stays clear of tabs and window edges")+ }+ setFrameSize(originalSize)+ update(prState)+ let mergedPixels = pullRequestButton.renderedPixels()+ try checkTitlebar(!mergedPixels.isEmpty && pullRequestButton.accessibilityValue() as? String == "PR #298 · Merged",+ "Segmented PR renders and exposes its full state")+ pullRequestButton.performClick(nil)+ try checkTitlebar(events.last == "focusedPullRequest", "PR opens its own action rather than the model picker")+ prState["enabled"] = false+ update(prState)+ try checkTitlebar(!pullRequestButton.isEnabled, "A modal disables the PR action")update(state(rows, active: "swarm-11"))+ try checkTitlebar(pullRequestButton.actionURL == nil && pullRequestButton.accessibilityValue() as? String == "",+ "Changing to a pane without a PR clears the old link and state")+ try checkTitlebar(contextButton.nextBackground == nil, "A missing PR clears the joined background")try tabs[0].checkDoubleClickIsolation()- let hover = NSEvent.mouseEvent(with: .mouseMoved, location: .zero, modifierFlags: [],- timestamp: 0, windowNumber: 0, context: nil, eventNumber: 0, clickCount: 0, pressure: 0)!- func click(_ count: Int, at point: NSPoint, time: TimeInterval) -> NSEvent {- NSEvent.mouseEvent(with: .leftMouseDown, location: point, modifierFlags: [],- timestamp: time, windowNumber: 0, context: nil, eventNumber: count,- clickCount: count, pressure: 1)!- }- try checkTitlebar(!ownsBackgroundDoubleClick(click(2, at: NSPoint(x: 40, y: 20), time: 1)),- "A second click displaced from a closed tab cannot zoom the window")- try checkTitlebar(!ownsBackgroundDoubleClick(click(1, at: NSPoint(x: 40, y: 20), time: 2)),- "The first titlebar-background click starts a local sequence")- try checkTitlebar(ownsBackgroundDoubleClick(click(2, at: NSPoint(x: 40, y: 20), time: 2.1)),- "A double-click wholly on titlebar background still zooms the window")- try checkTitlebar(tabs[0].showsDivider && tabs[1].showsDivider, "Idle neighboring tabs have separators")- try tabs[1].checkCloseVisibility(false)- tabs[1].mouseEntered(with: hover)- try tabs[1].checkCloseVisibility(true)- try tabs[0].checkCloseVisibility(false)- try checkTitlebar(!tabs[0].showsDivider && !tabs[1].showsDivider, "Hover clears separators on both sides of the tab")- tabs[1].mouseExited(with: hover)- try tabs[1].checkCloseVisibility(false)- try checkTitlebar(tabs[0].showsDivider && tabs[1].showsDivider, "Separators return when the pointer leaves")- try checkTitlebar(!tabs[10].showsDivider && !tabs[11].showsDivider, "Selected tab remains joined without neighboring separators")- try checkTitlebar(tabs.count == 24, "All overflow tabs exist")- try checkTitlebar(newButton.isEnabled, "New Tab remains available with overflow tabs")+ try checkTitlebar(tabs.count == 24 && newButton.isEnabled, "All overflow tabs and New Tab remain available")+ try checkTitlebar(scroll.frame.maxX <= newButton.frame.minX &&+ 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 == 4 && pullRequestButton.isHidden, "The PR control stays hidden until a PR is available")+ try checkTitlebar(contextButton.accessibilityValue() as? String == "OpenAI M2:~/code/harness (main)",+ "The full focused context is accessible")for (index, tab) in tabs.enumerated() {try tab.checkAccessibility(expectedName: "Swarm \(index)", active: index == 11)}try checkActiveVisible()+ let hover = NSEvent.mouseEvent(with: .mouseMoved, location: .zero, modifierFlags: [],+ timestamp: 0, windowNumber: 0, context: nil, eventNumber: 0, clickCount: 0, pressure: 0)!+ tabs[1].mouseEntered(with: hover)+ try tabs[1].checkCenteredLabel()+ tabs[1].mouseExited(with: hover)+ try tabs[1].checkCenteredLabel()scroll.contentView.scroll(to: .zero)scroll.reflectScrolledClipView(scroll.contentView)let browsingOrigin = scroll.documentVisibleRect.origin- var refreshed = state(rows, active: "swarm-11")- var renamedRows = rows- renamedRows[0]["name"] = "Background task renamed"- refreshed["tabs"] = renamedRows- update(refreshed)- try checkTitlebar(scroll.documentVisibleRect.origin == browsingOrigin,- "A background title update preserves the tabs the user scrolled to")- refreshed["palette"] = ["workspace": Int64(0xff252d43)]- update(refreshed)+ update(state(rows, active: "swarm-11"))try checkTitlebar(scroll.documentVisibleRect.origin == browsingOrigin,- "A palette update does not undo manual tab scrolling")+ "Background updates preserve deliberate tab scrolling")update(state(rows, active: "swarm-23"))try checkActiveVisible()setFrameSize(NSSize(width: 320, height: 52))needsLayout = truelayoutSubtreeIfNeeded()try checkActiveVisible()-+ try checkTitlebar(newButton.frame.maxX < contextButton.frame.minX &&+ contextButton.frame.maxX <= bounds.width, "Narrow windows have no overlapping controls")let original = tabs[0]let reversed = Array(rows.reversed())update(state(reversed, active: "swarm-0"))- try checkTitlebar(tabs.last === original, "Reordering retains existing tab controls")- try checkTitlebar(tabs.map(\.swarmId) == reversed.map { $0["id"]! }, "Tab order follows the saved Swarm order")+ try checkTitlebar(tabs.last === original, "Reordering keeps existing native tab controls")let accessibleTabs = document.accessibilityChildren()?.compactMap { $0 as? SwarmTabButton } ?? []- try checkTitlebar(accessibleTabs.map(\.swarmId) == tabs.map(\.swarmId), "Accessible tab order follows visual order after reordering")+ try checkTitlebar(accessibleTabs.map(\.swarmId) == tabs.map(\.swarmId), "Accessible order follows visual order")try checkActiveVisible()-- update(state([["id": "swarm-0", "name": "Renamed tab"]], active: "swarm-0"))- try checkTitlebar(tabs.count == 1 && tabs[0] === original, "Closing tabs retains the surviving control")- try original.checkAccessibility(expectedName: "Renamed tab", active: true)- try checkTitlebar(newButton.isEnabled, "New Harness returns below capacity")- var fullWithStarter = state(rows, active: "swarm-0")- fullWithStarter["canOpenNewTab"] = true- update(fullWithStarter)- try checkTitlebar(newButton.isEnabled,- "New Tab can reveal an existing starter at the tab limit")- fullWithStarter["canOpenNewTab"] = false- update(fullWithStarter)- try checkTitlebar(newButton.isEnabled,- "The retired canOpenNewTab capacity flag no longer disables New Tab")- update(state([["id": "swarm-0", "name": "Renamed tab"]], active: "swarm-0"))- try checkTitlebar(newButton.toolTip == "New Tab ⌘T" && storeButton.toolTip == "Harness Store ⌘S",- "Titlebar actions expose their keyboard alternatives")- try checkTitlebar(scroll.frame.minX == 0,- "The tabs start beside the traffic lights without a separate bell")- try checkTitlebar(scroll.frame.maxX <= newButton.frame.minX && newButton.frame.maxX <= storeButton.frame.minX,- "New Tab follows the tabs while the Store stays on the right")- try checkTitlebar(storeButton.title == "Harness Store" && storeButton.accessibilityLabel() == "Harness Store",- "The Store action has a visible and accessible name")- try checkTitlebar(newButton.frame.maxX < sessionsButton.frame.minX && sessionsButton.frame.maxX < storeButton.frame.minX && storeButton.frame.maxX <= bounds.width,- "Harnesses sits to the left of the Store without overlapping its hit target")- try checkTitlebar(sessionsButton.accessibilityLabel() == "Harnesses", "Harnesses has an accessible name")- try checkTitlebar(!subviews.contains(where: { $0 is NSTextField }), "The titlebar has no competing text editor")+ update(state([["id": "swarm-0", "name": "Custom name", "label": "1:blender"]], active: "swarm-0"))+ try checkTitlebar(tabs[0] === original && original.displayLabel == "1:blender",+ "Type changes update the existing tab without renaming its saved workspace")+ try original.checkAccessibility(expectedName: "Custom name", active: true)+ try checkTitlebar(newButton.toolTip == "New Tab ⌘T", "New Tab retains its keyboard hint")events.removeAll()+ contextButton.performClick(nil)newButton.performClick(nil)- sessionsButton.performClick(nil)- storeButton.performClick(nil)- try checkTitlebar(events == ["new", "sessions", "store"],- "The tab, Harnesses and Store buttons dispatch once")- try checkTitlebar(sessionsButton.attention > 0 && sessionsButton.toolTip?.contains("input") == true, "Harnesses represents pending agent attention")- let originalAttention = sessionsButton.attention- sessionsButton.attention = 0- let quietPixels = sessionsButton.renderedPixels()- try checkTitlebar(sessionsButton.attentionLabel == nil,- "Running harnesses without questions have no notification badge")- for count in [1, 6, 42, 100] {- sessionsButton.attention = count- let label = sessionsButton.attentionLabel!- let width = (label as NSString).size(withAttributes: [.font: NSFont.monospacedDigitSystemFont(ofSize: 9, weight: .semibold)]).width- let badge = sessionsButton.badgeFrame(textWidth: width)- try checkTitlebar(sessionsButton.bounds.contains(badge) && badge.maxX == sessionsButton.bounds.maxX &&- (sessionsButton.isFlipped ? badge.minY == sessionsButton.bounds.minY : badge.maxY == sessionsButton.bounds.maxY),- "The attention badge stays in the top-right corner and fits at count \(count)")- try checkTitlebar(sessionsButton.renderedPixels() != quietPixels,- "Pending questions visibly add a count badge at \(count)")- }- try checkTitlebar(sessionsButton.attentionLabel == "99+", "Large attention counts stay compact")- sessionsButton.attention = originalAttention- let oldButton = newButton- var themedState = state([["id": "swarm-0", "name": "Renamed tab"]], active: "swarm-0")- themedState["palette"] = ["workspace": Int64(0xff252d43), "search": Int64(0xff262f46)]- update(themedState)- try checkTitlebar(newButton === oldButton && tabs[0] === original,- "Palette changes retain native control identity")- try checkTitlebar(newButton.contentTintColor == palette.accent && sessionsButton.contentTintColor == sessionsButton.iconTint,- "Toolbar tools stay monochrome when the workspace palette changes")- events.removeAll()- try original.checkEnabled(true)original.clickBothActions()- try checkTitlebar(events == ["select", "close"], "Native selection and close dispatch once each")-- let actionPixels = storeButton.renderedPixels()+ try checkTitlebar(events == ["focusedModel", "new", "select", "close"], "Visible controls dispatch their actions once")events.removeAll()- update(state([["id": "swarm-0", "name": "Renamed tab"]], active: "swarm-0", enabled: false))+ update(state(rows, active: "swarm-0", enabled: false))+ try checkTitlebar(!contextButton.isEnabled && !newButton.isEnabled, "Modal state disables status-bar actions")try original.checkEnabled(false)- try checkTitlebar(!newButton.isEnabled && !sessionsButton.isEnabled && !storeButton.isEnabled, "Titlebar actions disable with a modal")- try checkTitlebar(actionPixels != storeButton.renderedPixels(),- "The Store visibly dims when a workspace modal disables it")- original.clickBothActions()+ contextButton.performClick(nil)newButton.performClick(nil)- sessionsButton.performClick(nil)- storeButton.performClick(nil)- try checkTitlebar(events.isEmpty, "Disabled controls emit no actions")+ original.clickBothActions()+ try checkTitlebar(events.isEmpty, "Disabled controls cannot act behind a modal")+ update(["tabs": rows, "activeId": "swarm-0", "enabled": true])+ try checkTitlebar(contextButton.accessibilityValue() as? String == "" && !contextButton.isEnabled,+ "An empty tab clears the previous pane's context and model action")try checkDragOperations()}+}private extension SwarmTabStrip {@@ -337,9 +284,9 @@ private extension SwarmTabStrip {let buttons = tab.accessibilityChildren()!.compactMap { $0 as? NSButton }for button in buttons {try checkTitlebar(window.makeFirstResponder(button), "An enabled tab action accepts keyboard focus")- try tab.checkCloseVisibility(true)+ try tab.checkCenteredLabel()try checkTitlebar(scroll.documentVisibleRect.contains(tab.frame),- "Keyboard focus reveals the entire overflowed tab and close control")+ "Keyboard focus reveals the entire overflowed tab")try checkTitlebar(activeId == "keyboard-23", "Focusing a tab control does not activate its swarm")let before = messenger.calls.countmessenger.holdReplies = true@@ -350,7 +297,7 @@ private extension SwarmTabStrip {try checkTitlebar(window.firstResponder === window.contentInput,"Activating a tab action returns the next key to Flutter content")try window.checkContentCommand()- try tab.checkCloseVisibility(false)+ try tab.checkCenteredLabel()try checkTitlebar(messenger.calls.count == before + 1, "Each native tab activation sends one action")}tab.attention = true@@ -396,18 +343,6 @@ private extension SwarmTabStrip {messenger.finishNextReply()try checkTitlebar(window.firstResponder === window.contentInput,"The latest acknowledged tab action restores content focus")- for (button, method) in [(sessionsButton, "sessions"), (machinesButton, "machineList")] {- window.makeFirstResponder(button)- let before = messenger.calls.count- button.performClick(nil)- try checkTitlebar(messenger.calls.count == before + 1 && messenger.calls.last?.method == method,- "The toolbar action dispatches once")- try checkTitlebar(window.firstResponder === button,- "The toolbar waits for Flutter's destination focus tree")- messenger.finishNextReply()- try checkTitlebar(window.firstResponder === window.contentInput,- "Harnesses returns keyboard ownership to Flutter")- }messenger.holdReplies = false}}@@ -548,8 +483,8 @@ private extension SwarmTitlebar {HarnessNativeKeymap.contexts.map { ($0, [["keys": ["cmd+u"], "command": "models.list","hint": "⌘U", "repeatable": false, "menuAction": "models"]]) })])!setKeymap(remappedModels)- try checkTitlebar(models.keyEquivalent == "u" && strip.modelsButton.toolTip == "Models ⌘U",- "Remapping Models updates both the View menu and the brain icon hint")+ try checkTitlebar(models.keyEquivalent == "u",+ "Remapping Models updates the View menu")setKeymap(changed)try checkTitlebar(NSApp.mainMenu === main && newSwarm.keyEquivalent == "o","Hot reload updates the existing menu to the remapped key")@@ -591,8 +526,6 @@ private extension SwarmTitlebar {try checkTitlebar(main.defersToInput(event("p", 35, .command)), "Command-P reaches commands")try checkTitlebar(!main.defersToInput(event("p", 35, [.command, .shift])), "Command-Shift-P is unbound")try checkTitlebar(main.defersToInput(event("o", 31, .command)), "Command-O reaches Open Harness")- try checkTitlebar(strip.machinesButton.toolTip == "Machines ⌘M", "Machines advertises its effective shortcut")- try checkTitlebar(strip.modelsButton.toolTip == "Models ⌘I", "Models advertises its effective shortcut")try checkTitlebar(main.defersToInput(event("i", 34, .command)) &&!main.performKeyEquivalent(with: event("i", 34, .command)),"Command-I reaches Flutter exactly once")@@ -732,7 +665,25 @@ private extension SwarmTitlebar {"New Terminal stays off the File menu; its chord lives in the keymap")let historyMenu = main.item(withTitle: "History")!.submenu!try checkTitlebar(agent.items.contains { $0.title == "Clone Harness" && $0.representedObject as? String == "cloneAgent" }, "Clone Harness preserves its action")- try checkTitlebar(agent.items.map { $0.isSeparatorItem ? "separator" : ($0.representedObject as? String ?? "") } == ["newAgent", "addAgent", "cloneAgent", "restartAgent", "separator", "new", "renameActive", "closeActive", "separator", "splitRight", "splitDown", "zoomPane", "movePaneToTab", "closePane"], "File groups harness, tab and pane actions, harnesses first")+ try checkTitlebar(agent.items.map { $0.isSeparatorItem ? "separator" : ($0.representedObject as? String ?? "") } == ["newAgent", "addAgent", "cloneAgent", "restartAgent", "shareAgent", "separator", "new", "renameActive", "closeActive", "separator", "splitRight", "splitDown", "zoomPane", "movePaneToTab", "closePane"], "File groups harness, tab and pane actions, harnesses first")+ for (action, title, menu) in [+ ("restartAgent", "Restart Harness", agent),+ ("shareAgent", "Share Harness", agent),+ ("toggleViewer", "Toggle Viewer", main.item(withTitle: "View")!.submenu!),+ ("toggleComposer", "Toggle Message Composer", main.item(withTitle: "View")!.submenu!),+ ] {+ let item = menu.items.first { $0.representedObject as? String == action }!+ try checkTitlebar(item.title == title, "\(title) has the right destination")+ actionsEnabled = true+ paneActions[action] = false+ try checkTitlebar(!validateMenuItem(item), "\(title) is unavailable without an eligible focused pane")+ paneActions[action] = true+ try checkTitlebar(validateMenuItem(item), "\(title) is enabled for the focused pane")+ menuAction(item)+ try checkTitlebar(messenger.calls.last?.method == action, "\(title) dispatches to Flutter")+ actionsEnabled = false+ try checkTitlebar(!validateMenuItem(item), "\(title) respects modal state")+ }try checkTitlebar(agent.items.first?.title == "New Harness" && agent.items.first?.keyEquivalent == "n" && agent.items.first?.keyEquivalentModifierMask == [.command],"New Harness leads File on Command-N")for (action, title, key) in [("splitRight", "Split Right", "r"), ("splitDown", "Split Down", "d")] {@@ -793,68 +744,7 @@ private extension SwarmTitlebar {try checkTitlebar(messenger.calls.last?.method == "manageMachines", "Machine Monitor remains available in View")menuAction(manager)try checkTitlebar(messenger.calls.last?.method == "machineList", "Machines opens the Flutter panel")- _ = try messenger.receive("update", arguments: [- "tabs": [["id": "navigation-check", "name": "Another tab"]],- "activeId": "navigation-check", "enabled": true, "machinesOpen": true,- ])- try checkTitlebar(strip.machinesButton.state == .on && strip.machinesButton.isEnabled,- "The Machines toolbar reflects the open panel")- try checkTitlebar(strip.machinesButton.frame.maxX < strip.modelsButton.frame.minX &&- strip.modelsButton.frame.maxX < strip.sessionsButton.frame.minX,- "Machines, Models, and Harnesses occupy adjacent ordered slots")- let beforeMachine = messenger.calls.count- strip.machinesButton.performClick(nil)- try checkTitlebar(messenger.calls.count == beforeMachine + 1 && messenger.calls.last?.method == "machineList",- "The Machines toolbar toggles the same panel as the menu")- _ = try messenger.receive("update", arguments: ["enabled": false, "machinesOpen": false])- try checkTitlebar(!strip.machinesButton.isEnabled && strip.machinesButton.state == .off,- "Modal state disables Machines and a closed panel clears the selection")- strip.machinesButton.performClick(nil)- menuAction(manager)- try checkTitlebar(messenger.calls.count == beforeMachine + 1 && !validateMenuItem(manager),- "Neither entry point dispatches behind a modal")actionsEnabled = true- _ = try messenger.receive("machinesState", arguments: ["machines": []])- _ = try messenger.receive("update", arguments: [- "enabled": true, "machineNotices": 2, "modelNotices": 101, "unread": 3,- ])- try checkTitlebar(strip.machinesButton.attentionLabel == "2" &&- strip.modelsButton.attentionLabel == "99+" && strip.sessionsButton.attentionLabel == "3",- "The three tools share the same bounded notification badge")- try checkTitlebar([strip.machinesButton, strip.modelsButton, strip.sessionsButton].allSatisfy {- $0.iconTint == NSColor(white: 0.96, alpha: 1)- }, "All three icons brighten when they have news")- try checkTitlebar(strip.machinesButton.badgeFrame(textWidth: 8) ==- strip.modelsButton.badgeFrame(textWidth: 8) &&- strip.modelsButton.badgeFrame(textWidth: 8) == strip.sessionsButton.badgeFrame(textWidth: 8),- "Badges align consistently on the three equal-size buttons")- try checkTitlebar((strip.machinesButton.accessibilityValue() as? String)?.contains("2 new computers") == true &&- (strip.modelsButton.accessibilityValue() as? String)?.contains("101 models ready") == true,- "Machine and model notifications are available to assistive technology")- for (step, button) in [("harnesses", strip.sessionsButton as SwarmNoticeButton),- ("machines", strip.machinesButton as SwarmNoticeButton),- ("models", strip.modelsButton as SwarmNoticeButton)] {- _ = try messenger.receive("update", arguments: [- "enabled": true, "onboarding": step, "machineNotices": 2,- "modelNotices": 101, "unread": 3,- ])- try checkTitlebar(button.onboarding &&- [strip.machinesButton, strip.modelsButton, strip.sessionsButton].filter { $0.onboarding }.count == 1,- "Only the current onboarding step gets a dot")- try checkTitlebar((button.accessibilityValue() as? String)?.contains("Suggested next step") == true,- "The onboarding dot has an accessible purpose")- try checkTitlebar(strip.machinesButton.attentionLabel == "2" &&- strip.modelsButton.attentionLabel == "99+" && strip.sessionsButton.attentionLabel == "3",- "Onboarding never inflates or replaces notification counts")- }- _ = try messenger.receive("update", arguments: ["enabled": true])- try checkTitlebar([strip.machinesButton, strip.modelsButton, strip.sessionsButton].allSatisfy { !$0.onboarding },- "Acknowledging onboarding removes the dot")- try checkTitlebar(strip.machinesButton.attentionLabel == nil && strip.modelsButton.attentionLabel == nil,- "Acknowledged machine and model news removes the badge")- try checkTitlebar(strip.machinesButton.iconTint == NSColor(white: 0.60, alpha: 1) &&- strip.modelsButton.iconTint == NSColor(white: 0.60, alpha: 1),- "Acknowledged icons return to muted gray")var recentRows: [[String: Any]] = (0..<20).map { index -> [String: Any] in["id": "agent:\(index)", "title": "Agent \(index) — Machine","detail": "Project \(index)", "machineName": "M2", "current": index == 0,@@ -972,20 +862,11 @@ private extension SwarmTitlebar {menuAction(openModels)try checkTitlebar(messenger.calls.count == menuCalls + 1 && messenger.calls.last?.method == "models","View Models opens the shared panel exactly once")- _ = try messenger.receive("update", arguments: ["enabled": true, "modelsOpen": true])- try checkTitlebar(strip.modelsButton.state == .on && strip.modelsButton.isEnabled- && strip.modelsButton.accessibilityValue() as? String == "Expanded",- "Models exposes the same active state as the other toolbar panels")let modelCalls = messenger.calls.count- strip.modelsButton.performClick(nil)- try checkTitlebar(messenger.calls.count == modelCalls + 1 && messenger.calls.last?.method == "models",- "The Models toolbar opens its overview")- _ = try messenger.receive("update", arguments: ["enabled": false, "modelsOpen": false])- strip.modelsButton.performClick(nil)+ _ = try messenger.receive("update", arguments: ["enabled": false])menuAction(openModels)- try checkTitlebar(!strip.modelsButton.isEnabled && strip.modelsButton.state == .off- && messenger.calls.count == modelCalls + 1 && !validateMenuItem(openModels),- "Neither Models entry point dispatches behind a modal")+ try checkTitlebar(messenger.calls.count == modelCalls && !validateMenuItem(openModels),+ "The Models menu cannot dispatch behind a modal")actionsEnabled = truelet findItems = find.submenu?.items ?? []@@ -1104,11 +985,10 @@ do {try checkTitlebar(swarmRow.menuTitle().string == "My swarm", "Empty swarm rows have no invented machine label")let sharedSwarm = SwarmHistoryEntry(["id": "shared", "title": "Workshop", "swarm": true, "machineName": "2 machines"])!try checkTitlebar(sharedSwarm.menuTitle().string == "Workshop\t2 machines", "Swarm machine counts use the same trailing column as agent machines")- for button in [SwarmIconButton(), SwarmSessionsButton(), SwarmCloseButton()] {+ for button in [SwarmIconButton()] {button.frame = NSRect(x: 0, y: 0, width: 28, height: 28)button.image = NSImage(systemSymbolName: "plus", accessibilityDescription: nil)button.isBordered = false- (button as? SwarmCloseButton)?.showsGlyph = truelet rest = button.renderedPixels()let hover = NSEvent.mouseEvent(with: .mouseMoved, location: .zero, modifierFlags: [],timestamp: 0, windowNumber: 0, context: nil, eventNumber: 0, clickCount: 0, pressure: 0)!