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
Preserve project context and panes when switching agents (#567)
Dee0bc22aad1f50
diff --git a/cli/src/engines/opencode/runtimeProfile.spec.ts b/cli/src/engines/opencode/runtimeProfile.spec.tsindex 58cf70709..2fd011cbe 100644--- a/cli/src/engines/opencode/runtimeProfile.spec.ts+++ b/cli/src/engines/opencode/runtimeProfile.spec.ts@@ -116,6 +116,11 @@ describe('opencode model catalog', () => {.toBe('opencode/ling-3.0-flash-free')})+ it('keeps the project path in the next terminal column out of the model', () => {+ expect(parseOpencodeFooter('┃ Build auto · Muse Spark 1.3 Free OpenCode Zen /private/tmp/harness-agent-switch-e2e'))+ .toEqual({ target: 'Muse Spark 1.3 Free OpenCode Zen', effort: null })+ })+it('reads model and level apart, from a real footer', () => {expect(parseOpencodeFooter('┃ Build · Ox Alpha Free (Unlimited) OpenCode Zen · high')).toEqual({ target: 'Ox Alpha Free (Unlimited) OpenCode Zen', effort: 'high' })diff --git a/cli/src/engines/opencode/runtimeProfile.ts b/cli/src/engines/opencode/runtimeProfile.tsindex bd23b888a..856a247b8 100644--- a/cli/src/engines/opencode/runtimeProfile.ts+++ b/cli/src/engines/opencode/runtimeProfile.ts@@ -170,7 +170,8 @@ export function parseOpencodeFooter(capture: string): OpencodeFooter | null {// [0] is the mode (Build/Plan) and is not ours to report; the chips show model and effort.const parts = line.split('·').map((part) => part.trim()).filter(Boolean)if (parts.length < 2) return null- const target = parts[1]+ // Wide panes put the project path in a separate, padded column.+ const target = parts[1].split(/\s{3,}/)[0].trim()if (!target) return nullconst trailing = parts[2]?.toLowerCase() ?? null// Only a single bare word is treated as a level. Anything longer is part of the name of something,diff --git a/cli/src/lib/runtimeProfile.spec.ts b/cli/src/lib/runtimeProfile.spec.tsindex 9324a60bc..64d2cef45 100644--- a/cli/src/lib/runtimeProfile.spec.ts+++ b/cli/src/lib/runtimeProfile.spec.ts@@ -291,6 +291,20 @@ describe('RuntimeProfileManager', () => {})})+ it('ignores Claude synthetic error models without losing the observed model', () => {+ const manager = new RuntimeProfileManager()+ const value = session('claude')+ const error = JSON.stringify({ type: 'assistant', message: { model: '<synthetic>', content: 'Quota exceeded' } })+ manager.hydrate(value, [error])+ expect(manager.selectedModel(value)).toBeNull()++ manager.ingestPane(value, 'Opus 4.8 with high effort\n❯ ')+ const observed = manager.selectedModel(value)+ expect(observed).not.toBeNull()+ manager.ingest(value, error)+ expect(manager.selectedModel(value)).toBe(observed)+ })+it('hydrates Claude effort from effective settings and backfills the transcript CLI version', async () => {const cwd = await mkdtemp(join(tmpdir(), 'machine-runtime-'))cleanup.push(cwd)diff --git a/cli/src/lib/runtimeProfile.ts b/cli/src/lib/runtimeProfile.tsindex e1b4603f6..9e3694113 100644--- a/cli/src/lib/runtimeProfile.ts+++ b/cli/src/lib/runtimeProfile.ts@@ -1223,7 +1223,9 @@ export class RuntimeProfileManager {}const message = record(raw.message)const assistantModel = raw.type === 'assistant' ? text(message?.model) : ''- if (assistantModel) {+ // Claude uses this marker for local errors such as exhausted quota.+ // It is not a model change; keep the last real observation.+ if (assistantModel && assistantModel !== '<synthetic>') {state.model = assistantModelstate.observedAt = Date.now()}diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.mdindex c1d017b47..203abf284 100644--- a/desktop/CLAUDE.md+++ b/desktop/CLAUDE.md@@ -342,8 +342,8 @@ its headless debug timings do not establish native display or network latency.with harness count, local hardware and subscription allowance used at the bottom left and focused machine/repo/branch/PR at the bottom right.Tabs center their name/status group without permanent number prefixes; Command replacesthe status with the resolved shortcut beside the name. Tab and pane close marks are small- and quiet, with larger click targets. Each pane ends with agent, model, split down,- split right, zoom, close. Split opens New Harness directly for the clicked pane.+ and quiet, with larger click targets. Each terminal pane ends with agent, model,+ close. Split and zoom remain in commands, menus and keyboard shortcuts.Usage has no dot separators and colors only low/exhaustedpercentages. Automatic names use the strongest shared harness type,project, or machine, preferring traits that distinguish tabs and excluding dependent viewers.diff --git a/desktop/design/desktop-design-system.md b/desktop/design/desktop-design-system.mdindex 55f5d7f2e..cee74480a 100644--- a/desktop/design/desktop-design-system.md+++ b/desktop/design/desktop-design-system.md@@ -329,16 +329,14 @@ inner edge beneath their 1-point rim. Only their frame changes: terminal contentinput, selection and status typography remain the terminal's own. AppKit mirrorsthese shared geometry values; Flutter uses AppDesktop directly.-**Pane header** — the right-hand controls read agent, model, split down, split right,-zoom, close. Use the rounded 14-point `AppPaneIcon` split/zoom variants and the-shared 12-point close glyph in 28-point targets. The close target sits 4 points-inside the header's trailing edge. Resting ink is 45%; hover and keyboard focus-brighten the glyph without a fill, border, or movement. Keep the controls on one-line; model and title text truncate before icon targets shrink. Zoom becomes-Restore while enlarged. Unavailable controls stay in place with disabled ink.-Split opens New Harness directly, inheriting the clicked pane's agent, machine,-and project; the pane is created only after submission. Clicking the model focuses that-pane and opens the same Models picker as Cmd-:. The agent name and chevron open the shared Agents picker (`&` in Cmd-P). Selection stays bound to that+**Pane header** — the right-hand controls read agent, model, close. The shared+12-point close glyph has a 28-point target, 4 points inside the trailing edge.+Resting ink is 45%; hover and keyboard focus brighten the glyph without a fill,+border, or movement. Keep the controls on one line; model and title text truncate+before the close target shrinks. Split and zoom remain in commands, menus and+keyboard shortcuts. Clicking the model focuses that+pane and opens the same Models picker as Cmd-:. The agent name and chevron open+the shared Agents picker (`&` in Cmd-P). Selection stays bound to thatharness; a closed or replaced pane cannot receive a stale selection. Long modelnames truncate and retain their full-name tooltip. Keep effort in the terminal,and keep the icon targets clear at narrow widths. Tab-strip close behavior isdiff --git a/desktop/design/new-harness-entry-rules.md b/desktop/design/new-harness-entry-rules.mdindex a7f46f7e4..ba50124a5 100644--- a/desktop/design/new-harness-entry-rules.md+++ b/desktop/design/new-harness-entry-rules.md@@ -40,7 +40,7 @@ Opening, searching, and cancelling never send input to an existing harness.| Cmd-T, then Cmd-N | Last explicit agent, local machine, last selected project on that machine | The blank tab opened by Cmd-T || Cmd-Shift-P → New Harness | Last explicit agent, local machine, last selected project on that machine | Current tab || Cmd-N or the New Harness command | Last explicit agent, local machine, last selected project on that machine; retain explicit task and destination | Current tab unless its source requests a new tab |-| Pane-header split, Split Right/Down command, or shortcut | Opens creation directly with the clicked/focused pane's agent, machine, and project | Requested split in that tab after submission |+| Split Right/Down command, menu, or shortcut | Opens creation directly with the clicked/focused pane's agent, machine, and project | Requested split in that tab after submission || Store New Harness, or a product's Open action in the pane or native Models menu | Explicit product and machine; suggested project named for that product | New tab || Store Resume Harness | Existing harness and its machine; choose from a menu when several match | Focus its existing tab or reopen a view of the same harness || Store Try this prompt | Same as Open, with the example as the editable task | New tab |diff --git a/desktop/design/review/2026-10-01-agent-switch-header.png b/desktop/design/review/2026-10-01-agent-switch-header.pngnew file mode 100644index 000000000..098068525Binary files /dev/null and b/desktop/design/review/2026-10-01-agent-switch-header.png differdiff --git a/desktop/design/terminal-workspace.md b/desktop/design/terminal-workspace.mdindex d1c4697b8..86e89c699 100644--- a/desktop/design/terminal-workspace.md+++ b/desktop/design/terminal-workspace.md@@ -32,15 +32,22 @@ Tooltips explain icon actions and resolve shortcuts from the live keymap.The footer shows a global harness count, local host CPU/RAM/GPU and subscriptionallowance used on the left, all in neutral ink with whole percentages. Its-right-hand context follows the focused pane: machine, project, branch and PR. Each pane header ends with agent, model, split down, split right, zoom,-and close, in that order. The icons stay visible with quiet ink and no button-chrome. Splitting opens New Harness directly with that pane's agent, machine,-and project, then creates into the chosen split on submission. Clicking the-agent opens the shared `&` Agents picker; clicking the model opens the shared Models picker for that harness;-the footer does not repeat model or effort. Do not show worktree implementation+right-hand context follows the focused pane: machine, project, branch and PR.+Each terminal pane header ends with agent, model and close, in that order. The+close icon stays visible with quiet ink and no button chrome. Split and zoom+remain available through commands, menus and keyboard shortcuts. Splitting+opens New Harness with the focused pane's agent, machine and project. Clicking+the agent opens the shared `&` Agents picker; clicking the model opens Models;+the footer does not repeat model or effort. Agent switching saves the original+session before starting its replacement in the same project. Its pane and layout+survive peer cleanup of the stopped source. Agents that accept an initial message+receive bounded recent requests and saved answers, preserving the handoff across+retries; the saved original session keeps the full transcript. Do not show worktree implementationpaths in everyday labels. User-selected shell/Powerline status styles remainavailable, including PR state colors and the option to disable color.++Machine opens its scope, Project opens related harnesses, Branch opens theexisting branches/PR history, and the PR opens its URL. These are navigation,not checkout actions. Missing data stays honest. Dependent viewers use theirdiff --git a/desktop/lib/bootstrap/environment_provisioner.dart b/desktop/lib/bootstrap/environment_provisioner.dartindex 88675d8b0..4133b489f 100644--- a/desktop/lib/bootstrap/environment_provisioner.dart+++ b/desktop/lib/bootstrap/environment_provisioner.dart@@ -1,5 +1,7 @@import '../core/host_platform.dart';+import 'package:flutter/foundation.dart' show kDebugMode;+import 'dart:async';import 'dart:convert';import 'dart:io';@@ -1323,7 +1325,14 @@ fi''';RegExp('^v'),'',);- _harnessOutdated = semverGt(kMinimumHarnessCliVersion, installed)+ // Local CLI builds intentionally use 0.0.1-dev.<revision>. A debug+ // desktop must not mistake these for an obsolete release and offer to+ // overwrite the developer's CLI. Release builds retain the minimum.+ final localDevelopmentBuild =+ kDebugMode && installed.startsWith('0.0.1-dev.');+ _harnessOutdated =+ !localDevelopmentBuild &&+ semverGt(kMinimumHarnessCliVersion, installed)? installed: null;return _harnessOutdated == null;diff --git a/desktop/lib/core/runtime_model_name.dart b/desktop/lib/core/runtime_model_name.dartindex 386949650..be965a9c9 100644--- a/desktop/lib/core/runtime_model_name.dart+++ b/desktop/lib/core/runtime_model_name.dart@@ -23,8 +23,17 @@ String? runtimeModelName(}try {if (Uri.decodeComponent(match[1]!) != agentId) return null;- final model = Uri.decodeComponent(match[3]!).trim();+ var model = Uri.decodeComponent(match[3]!).trim();+ // Older daemons included the adjacent path column from OpenCode's footer.+ // Keep provider/model IDs intact; only strip an explicitly padded path.+ if (engine?.toLowerCase() == 'opencode') {+ model = model+ .split(RegExp(r' {3,}(?=/|~/|[A-Za-z]:[\\/])'))+ .first+ .trimRight();+ }if (model.isEmpty ||+ model == '<synthetic>' ||model.length > 256 ||RegExp(r'[\x00-\x1f\x7f]').hasMatch(model)) {return null;diff --git a/desktop/lib/state/agent_switch_handoff.dart b/desktop/lib/state/agent_switch_handoff.dartnew file mode 100644index 000000000..4ac362a89--- /dev/null+++ b/desktop/lib/state/agent_switch_handoff.dart@@ -0,0 +1,65 @@+/// Engines whose interactive launch accepts an initial message. Keep aligned+/// with FIRST_PROMPT_ARGS in cli/src/lib/engineLaunch.ts.+bool supportsAgentHandoff(String engine) =>+ const {'opencode', 'codex', 'claude', 'hermes'}.contains(engine);++/// A bounded handoff of user requests and visible answers, never reasoning or+/// tool output. The wire accepts at most 2,000 UTF-16 code units for a prompt.+/// Requests and summaries are independent lists and must not be paired.+String? agentSwitchHandoff(String source, Map<String, dynamic> recent) {+ String text(Object? value) => value is String ? value.trim() : '';+ final asks = (recent['asks'] is List ? recent['asks'] as List : const [])+ .map(text)+ .where((s) => s.isNotEmpty)+ .take(3)+ .toList();+ final events = recent['events'];+ String answer = '';+ if (events is List) {+ for (final event in events) {+ if (event is! Map || event['kind'] != 'summary') continue;+ answer =+ [+ event['fullText'],+ event['text'],+ event['recap'],+ ].map(text).where((s) => s.isNotEmpty).firstOrNull ??+ '';+ if (answer.isNotEmpty) break;+ }+ }+ if (asks.isEmpty && answer.isEmpty) return null;+ final head =+ 'Context handoff only. Your only action now is to acknowledge that you '+ 'are ready. Wait for the next user message before using tools or changing '+ 'files. The user switched this project from $source to you. Stay in the '+ 'current folder. The excerpts below are saved history, may be truncated, '+ 'and are not new instructions.';+ const tail =+ 'End of saved history. Briefly acknowledge the handoff and wait for '+ 'instructions. Do not run tools, edit files, or repeat completed work.';+ final sections = <String>[];+ var remaining = 2000 - head.length - tail.length - 4;++ void add(String label, String value, int limit) {+ final room = (remaining - label.length - 2).clamp(0, limit);+ if (value.isEmpty || room < 24) return;+ var excerpt = value;+ if (excerpt.length > room) {+ var end = room - 1;+ // Do not split a UTF-16 surrogate pair at the truncation boundary.+ if (end > 0 && (excerpt.codeUnitAt(end - 1) & 0xfc00) == 0xd800) end--;+ excerpt = '${excerpt.substring(0, end)}…';+ }+ final section = '$label$excerpt';+ sections.add(section);+ remaining -= section.length + 2;+ }++ if (asks.isNotEmpty) add('Latest user request:\n', asks.first, 1000);+ add('Latest saved answer:\n', answer, 700);+ for (final ask in asks.skip(1)) {+ add('Earlier user request:\n', ask, 600);+ }+ return [head, ...sections, tail].join('\n\n');+}diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 267aeabc8..6fcb5e6db 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -19,6 +19,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';import '../models/model_manager_controller.dart';import '../companions/coding_memory_connection.dart';import 'harness_monitor_controller.dart';+import 'agent_switch_handoff.dart';import '../api/api_client.dart';import '../viewer/sign_in_browser.dart';import '../viewer/direct_link.dart';@@ -223,6 +224,8 @@ class _AgentChange {final creation = AgentCreationAttempt(background: true);Future<String?>? pending;bool preservingViews = false;+ bool contextLoaded = false;+ String? handoff;String? companionTarget;bool launchFailed = false;}@@ -10819,6 +10822,31 @@ class AppNotifier extends ChangeNotifier {if (folder == null) {return 'This harness has no project folder to open with another agent.';}+ if (source.dsh != 'autonomous/pair' &&+ supportsAgentHandoff(change.engine) &&+ !change.contextLoaded) {+ try {+ final recent = await _conn(machineId).request(+ 'agent_recent',+ payload: {'agentId': source.id, 'n': 5},+ timeout: const Duration(seconds: 4),+ );+ if (recent['error'] != null ||+ (recent['agentId'] != null && recent['agentId'] != source.id)) {+ return 'Could not read the conversation for the handoff. Try switching again.';+ }+ change.handoff = agentSwitchHandoff(+ source.engine ?? 'the previous agent',+ recent,+ );+ change.contextLoaded = true;+ } catch (_) {+ return 'Could not read the conversation for the handoff. Try switching again.';+ }+ if (!_machineWorkCurrent(machine, change.revision)) {+ return 'This switch is no longer active.';+ }+ }final close = prepareSessionClose(machineId, source);change.preservingViews = true;if (!current.isStopped) {@@ -10863,6 +10891,7 @@ class AppNotifier extends ChangeNotifier {name: source.displayName,permissionMode: mode,bypassPermission: mode == 'auto' || mode == 'full',+ prompt: change.handoff,attempt: change.creation,);if (error != null) return error;@@ -10895,6 +10924,22 @@ class AppNotifier extends ChangeNotifier {if (terminals.isEmpty) {return 'The original pane was closed. Open the new agent from Harness Monitor.';}+ // A peer can still have a queued tab.close for a tab whose only agent+ // was the stopped source. Give that replacement a fresh desk identity:+ // the Swarm/pane objects, active selection and geometry stay unchanged,+ // but an old close can no longer address the new conversation.+ final replacedTabs = _desk.enabled+ ? swarms.where((swarm) {+ final agents = swarm.panes.where((pane) => pane.agentId != null);+ return _deskTracks(swarm) &&+ isDeskId(swarm.id) &&+ agents.isNotEmpty &&+ agents.every(+ (pane) =>+ pane.machineId == machineId && pane.agentId == source.id,+ );+ }).toList()+ : <Swarm>[];// The old process has stopped and its panes were retained through the// acknowledgement. Replace their references without changing geometry.for (final pane in terminals) {@@ -10909,6 +10954,21 @@ class AppNotifier extends ChangeNotifier {for (final pane in viewers) {if (allPanes.contains(pane)) pane.ownerAgentId = nextId;}+ for (final swarm in swarms) {+ if (swarm.titleMachineId == machineId &&+ swarm.titleAgentId == source.id) {+ swarm.titleAgentId = nextId;+ }+ }+ for (final swarm in replacedTabs) {+ if (!swarms.contains(swarm)) continue;+ final previousId = swarm.id;+ swarm.id = newDeskId();+ if (_activeSwarmId == previousId) _activeSwarmId = swarm.id;+ for (final entry in _draftSwarmReturns.entries.toList()) {+ if (entry.value == previousId) _draftSwarmReturns[entry.key] = swarm.id;+ }+ }_agentChanges.remove((machineId, source.id));_syncViewerPane(machine, target);// Publish the replacement before yielding: a peer may already havediff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dartindex 4281503f4..915dec649 100644--- a/desktop/lib/state/swarm_search.dart+++ b/desktop/lib/state/swarm_search.dart@@ -15,6 +15,7 @@ import '../core/models.dart'show Agent, ConnectionStatus, GridModels, GridModel;import 'app_state.dart';+import 'agent_switch_handoff.dart';import 'harness_placement.dart';import 'pane_arrangement.dart';import 'swarm_catalog.dart';@@ -1555,7 +1556,9 @@ class SwarmSearchController extends ChangeNotifier {: agentSelection?.engine == engine.id? 'Current agent': engine.id == 'opencode'- ? 'Muse Spark 1.3 · new conversation'+ ? 'Muse Spark 1.3 · continue with recent context'+ : supportsAgentHandoff(engine.id)+ ? 'Continue this project with recent context': 'New conversation in the same project',swarmId: null,current: agentSelection?.engine == engine.id,diff --git a/desktop/lib/widgets/pane_header_actions.dart b/desktop/lib/widgets/pane_header_actions.dartindex d3d31d8f1..bb0ec07d9 100644--- a/desktop/lib/widgets/pane_header_actions.dart+++ b/desktop/lib/widgets/pane_header_actions.dart@@ -1,7 +1,7 @@import 'package:flutter/widgets.dart';/// Pane-local model selection and optional standalone terminal context.-/// The pane keeps its fixed split, zoom and close targets outside this group.+/// The pane keeps its close target outside this group.class PaneHeaderActions extends StatelessWidget {const PaneHeaderActions({super.key,diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dartindex e299f8829..dc62507db 100644--- a/desktop/lib/widgets/terminal_panel.dart+++ b/desktop/lib/widgets/terminal_panel.dart@@ -7,7 +7,6 @@ import 'dart:convert';import 'dart:math' as math;import 'package:harness/shared/theme/app_icons.dart';-import 'package:harness/shared/theme/app_pane_icon.dart';import 'package:flutter/foundation.dart';import 'package:flutter/material.dart';@@ -2735,11 +2734,7 @@ class _TerminalHeader extends StatelessWidget {// The picker: a model id up to 220px and its padding.final pickerWidth =(showModelPicker ? 250.0 : 0.0) + (agent != null ? 90.0 : 0.0);- final showSplit = compact || onSplitDown != null || onSplitRight != null;- final showZoom = compact || onToggleZoom != null;- final controlsWidth =- ((showSplit ? 2 : 0) + (showZoom ? 1 : 0) + (onClose != null ? 1 : 0)) *- PaneHeaderButton.width;+ final controlsWidth = onClose != null ? PaneHeaderButton.width : 0.0;final actionsWidth = pickerWidth + controlsWidth;// 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.@@ -3111,30 +3106,6 @@ class _TerminalHeader extends StatelessWidget {),),),- if (showSplit) ...[- PaneHeaderButton(- key: const ValueKey('pane-split-down'),- label: 'New Pane Below',- command: 'pane.split_down',- icon: AppPaneSymbol.splitDown,- onPressed: onSplitDown,- ),- PaneHeaderButton(- key: const ValueKey('pane-split-right'),- label: 'New Pane to the Right',- command: 'pane.split_right',- icon: AppPaneSymbol.splitRight,- onPressed: onSplitRight,- ),- ],- if (showZoom)- PaneHeaderButton(- key: const ValueKey('pane-zoom'),- label: zoomed ? 'Restore Pane' : 'Zoom Pane',- command: 'pane.zoom',- icon: zoomed ? AppPaneSymbol.restore : AppPaneSymbol.zoom,- onPressed: onToggleZoom,- ),if (onClose != null) PaneCloseButton(onPressed: onClose!),],);diff --git a/desktop/test/agent_change_test.dart b/desktop/test/agent_change_test.dartindex b6f5c6293..f244788ff 100644--- a/desktop/test/agent_change_test.dart+++ b/desktop/test/agent_change_test.dart@@ -5,6 +5,7 @@ import 'package:flutter_test/flutter_test.dart';import 'package:harness/api/api_client.dart';import 'package:harness/auth/auth_session.dart';import 'package:harness/core/config.dart';+import 'package:harness/state/agent_switch_handoff.dart';import 'package:harness/state/desk_sync.dart';import 'package:harness/core/dsh_catalog.dart';import 'package:harness/core/models.dart';@@ -21,6 +22,8 @@ class SwitchConnection extends MonitorConnection {final events = <String>[];String? closeError;Completer<void>? holdClose;+ Map<String, dynamic> recent = {'asks': <String>[], 'events': <Object>[]};+ int recentReads = 0;@overrideFuture<Map<String, dynamic>> request(@@ -28,6 +31,10 @@ class SwitchConnection extends MonitorConnection {Map<String, dynamic> payload = const {},Duration timeout = const Duration(seconds: 20),}) async {+ if (type == 'agent_recent') {+ if (payload['n'] == 5) recentReads++;+ return recent;+ }if (type == 'agent_close') {events.add('save/stop');expect(payload['mode'], 'now');@@ -69,13 +76,14 @@ AppNotifier fixture(SwitchConnection connection, {bool viewer = false,bool companion = false,+ String sourceEngine = 'codex',}) {final app = createApp(connectionForTest: (_) => connection, connected: true);connection.app = app;final source = Agent(id: 'a0',name: 'Work',- engine: 'codex',+ engine: sourceEngine,sessionId: 'saved-conversation',createdAt: DateTime.utc(2026, 10, 1),closeSupported: true,@@ -127,6 +135,80 @@ class SwitchDeskApi extends ApiClient {}void main() {+ for (final (source, target) in [+ ('claude', 'opencode'),+ ('claude', 'codex'),+ ('opencode', 'codex'),+ ('opencode', 'claude'),+ ('codex', 'opencode'),+ ('codex', 'claude'),+ ]) {+ test(+ 'hands recent context from $source to $target exactly once on retry',+ () async {+ final connection = SwitchConnection()+ ..loseFirstReply = true+ ..recent = {+ 'asks': [+ 'Remember maple-42; next append step 2.',+ 'Create progress.txt.',+ ],+ 'events': [+ {'kind': 'reasoning', 'fullText': 'private reasoning'},+ {+ 'kind': 'summary',+ 'fullText': 'Created progress.txt with step 1.',+ },+ ],+ };+ final app = fixture(connection, sourceEngine: source);+ addTearDown(app.dispose);+ await app.addAgentToSwarm('m', 'a0');+ expect(await app.changeAgent('m', 'a0', target), isNotNull);+ connection.recent = {+ 'asks': ['Changed after dispatch'],+ };+ expect(await app.changeAgent('m', 'a0', target), isNull);+ expect(connection.recentReads, 1);+ final prompt = connection.creations.single['prompt'] as String;+ expect(prompt, contains('maple-42'));+ expect(prompt, contains('Created progress.txt with step 1.'));+ expect(prompt, isNot(contains('private reasoning')));+ expect(prompt, contains('wait for instructions'));+ },+ );+ }++ test('an unreadable handoff leaves the original agent running', () async {+ final connection = SwitchConnection()..recent = {'error': 'UNAVAILABLE'};+ final app = fixture(connection);+ addTearDown(app.dispose);+ await app.addAgentToSwarm('m', 'a0');+ expect(await app.changeAgent('m', 'a0', 'claude'), contains('handoff'));+ expect(connection.events, isEmpty);+ expect(app.panes.single.agentId, 'a0');+ });++ test(+ 'handoff clips long context to the wire limit, excluding tool output',+ () {+ final prompt = agentSwitchHandoff('claude', {+ 'asks': ['latest ${'🍁' * 1600}', 'older ' * 600],+ 'events': [+ {'kind': 'tool', 'fullText': 'tool secrets'},+ {'kind': 'summary', 'fullText': 'answer ' * 900},+ ],+ })!;+ expect(prompt.length, lessThanOrEqualTo(2000));+ expect(prompt, contains('latest'));+ expect(prompt, contains('Latest saved answer:'));+ expect(prompt, isNot(contains('tool secrets')));+ expect(prompt, endsWith('or repeat completed work.'));+ expect(prompt, startsWith('Context handoff only.'));+ expect(agentSwitchHandoff('claude', {}), isNull);+ },+ );+for (final entireTab in [true, false]) {test('switch keeps its slot when a peer prunes ${entireTab ? 'the tab' : 'the pane'}',@@ -198,6 +280,64 @@ void main() {);}+ for (final otherPane in [false, true]) {+ test(+ 'late source cleanup cannot close the replacement (other pane: $otherPane)',+ () async {+ final connection = SwitchConnection();+ final app = fixture(connection);+ final api = SwitchDeskApi();+ app.api = api;+ addTearDown(app.dispose);+ await app.addAgentToSwarm('m', 'a0');+ if (otherPane) await app.addAgentToSwarm('m', 'a1');+ await app.deskStartForTest();+ final tab = app.swarms.single;+ final oldId = tab.id;+ final pane = tab.panes.first;+ final sizes = Map.of(tab.paneSizes);+ expect(await app.changeAgent('m', 'a0', 'opencode'), isNull);+ await app.deskFlushForTest();+ expect(tab.id == oldId, otherPane);+ // This was queued by an old window when it saw the source stop,+ // then arrived after our replacement was already acknowledged.+ api.doc = DeskDoc(+ revision: api.doc.revision + 1,+ tabs: applyDeskOps(api.doc.tabs, [+ if (otherPane)+ {+ 'op': 'pane.remove',+ 'tabId': oldId,+ 'machineId': 'm',+ 'agentId': 'a0',+ }+ else+ {'op': 'tab.close', 'id': oldId},+ ]),+ );+ await app.deskFetchForTest();+ expect(app.swarms.single, same(tab));+ expect(tab.panes.first, same(pane));+ expect(pane.agentId, 'local-session');+ expect(tab.paneSizes, sizes);+ expect(app.activeSwarmId, tab.id);+ expect(+ api.doc.tabs.single.panes.map((p) => p.agentId),+ contains('local-session'),+ );+ // A subsequent deliberate close of the replacement still works.+ api.doc = DeskDoc(+ revision: api.doc.revision + 1,+ tabs: applyDeskOps(api.doc.tabs, [+ {'op': 'tab.close', 'id': tab.id},+ ]),+ );+ await app.deskFetchForTest();+ expect(app.allPanes, isNot(contains(pane)));+ },+ );+ }+test('saves before starting, then replaces every view without changing tabs or layout', () async {final connection = SwitchConnection();final app = fixture(connection, viewer: true);diff --git a/desktop/test/environment_provisioner_test.dart b/desktop/test/environment_provisioner_test.dartindex 14ec252a7..3930b755d 100644--- a/desktop/test/environment_provisioner_test.dart+++ b/desktop/test/environment_provisioner_test.dart@@ -46,6 +46,7 @@ void main() {int tmuxInstallExitCode = 0,int linuxInstallExitCode = 0,String linuxInstallStderr = 'apt install failed',+ String cliVersion = '1.2.3',}) {return (executable, arguments, {environment}) async {final command = '$executable ${arguments.join(' ')}';@@ -132,7 +133,7 @@ void main() {return result(0, stdout: 'v20.18.0');}if (executable == managedNode.path && arguments.contains('version')) {- return result(0, stdout: 'harness 1.2.3');+ return result(0, stdout: cliVersion);}// System tools, writable HOME and chmod.return result(0);@@ -164,6 +165,37 @@ void main() {},);+ for (final (version, ready) in [+ ('0.0.1-dev.7c3d6315c.startup-retry.dirty', true),+ ('0.2.48', true),+ ('0.2.47', false),+ ('0.0.1', false),+ ]) {+ test(+ 'debug desktop checks CLI $version without replacing a local build',+ () async {+ await createManagedHarness();+ final calls = <String>[];+ final provisioner = EnvironmentProvisioner(+ harnessHome: scratch,+ isMacOS: true,+ isLinux: false,+ run: runner(+ tmuxPresent: () => true,+ cliVersion: version,+ calls: calls,+ ),+ );+ final readiness = await provisioner.ensureReady(+ onProgress: (_) {},+ install: false,+ );+ expect(readiness.isReady, ready, reason: readiness.output.join('\n'));+ expect(calls.where((line) => line.contains('install.sh')), isEmpty);+ },+ );+ }+// The macOS ladder: tmux, else one in-app installer step that uses the// Homebrew already here or downloads the managed build. Nothing here ever// needs a Terminal window, Xcode, or a password.diff --git a/desktop/test/runtime_model_name_test.dart b/desktop/test/runtime_model_name_test.dartindex 564395610..971888059 100644--- a/desktop/test/runtime_model_name_test.dart+++ b/desktop/test/runtime_model_name_test.dart@@ -25,6 +25,20 @@ void main() {}});+ test('OpenCode labels exclude an adjacent padded project path', () {+ for (final path in ['/private/tmp/work', '~/code/work', r'C:\work']) {+ final model = 'Muse Spark 1.3 Free OpenCode Zen $path';+ expect(+ runtimeModelName(+ 'runtime-v1:a:opencode:${Uri.encodeComponent(model)}@auto',+ agentId: 'a',+ engine: 'opencode',+ ),+ 'Muse Spark 1.3 Free OpenCode Zen',+ );+ }+ });+test('observed effort stays with the validated model', () {for (final (effort, label) in [('low', 'Low'),@@ -64,6 +78,7 @@ void main() {'runtime-v1:a:codex:%FF@high','runtime-v1:a:codex:%C0%80@high','runtime-v1:a:codex:%20@high',+ 'runtime-v1:a:codex:%3Csynthetic%3E@high','runtime-v1:a:codex:model%0Aname@high','runtime-v1:a:codex:${'x' * 257}@high',]) {diff --git a/desktop/test/swarm_split_test.dart b/desktop/test/swarm_split_test.dartindex 764da6750..98ede2b2c 100644--- a/desktop/test/swarm_split_test.dart+++ b/desktop/test/swarm_split_test.dart@@ -277,77 +277,77 @@ void main() {});}- testWidgets('header creates $direction from the clicked, unfocused pane', (- tester,- ) async {- final (app, connection) = _splitApp();- final frames = <TerminalBinaryFrame>[];- final first = app.adoptSessionForTest(terminal('a0', frames));- final neighbor = app.adoptSessionForTest(terminal('a1', frames));- app.focusPane(neighbor.id);- await mountWide(tester, app);- tester.view.physicalSize = const Size(3000, 1800);- await tester.pump();- final target = find.byKey(first.cellKey);- final rect = tester.getRect(target);- final neighborRect = tester.getRect(find.byKey(neighbor.cellKey));- final view = find.descendant(- of: target,- matching: find.byType(TerminalView),- );- final retained = tester.element(view);- final previousFocus = FocusManager.instance.primaryFocus;- final button = find.descendant(- of: target,- matching: find.byKey(ValueKey('pane-split-$direction')),- );- expect(button.hitTestable(), findsOneWidget);- final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);- await mouse.addPointer(location: rect.center);- await mouse.moveTo(tester.getCenter(button));- await tester.pump();- expect(app.focusedPaneId, neighbor.id);- expect(FocusManager.instance.primaryFocus, same(previousFocus));- expect(tester.element(view), same(retained));- expect(tester.getRect(target), rect);- await tester.tap(button);- await tester.pump();- expect(_form(tester).split?.paneId, first.id);- expect(_form(tester).engine, 'claude');- expect(_form(tester).project.folder, '/work/a0');- expect(app.focusedPaneId, first.id);- expect(connection.creation, isNull);- await tester.sendKeyEvent(LogicalKeyboardKey.escape);- await tester.pump();- expect(app.panes, [first, neighbor]);- expect(tester.getRect(target), rect);- expect(tester.element(view), same(retained));- await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);- await tester.pump(const Duration(milliseconds: 10));- expect(frames.single.streamId, first.session!.streamId);- frames.clear();- await tester.tap(button);- await tester.pump();- await _create(tester, connection);- expect(app.panes.map((pane) => pane.agentId), ['a0', 'created', 'a1']);- expect(tester.element(view), same(retained));- expect(tester.getRect(find.byKey(neighbor.cellKey)), neighborRect);- final splitRect = tester.getRect(target);- final addedRect = tester.getRect(find.byKey(app.panes[1].cellKey));- if (axis == PaneResizeAxis.x) {- expect(addedRect.left, greaterThan(splitRect.right));- expect(addedRect.top, splitRect.top);- expect(addedRect.height, splitRect.height);- } else {- expect(addedRect.top, greaterThan(splitRect.bottom));- expect(addedRect.left, splitRect.left);- expect(addedRect.width, splitRect.width);- }- expect(frames, isEmpty);- await mouse.removePointer();- await tester.pumpWidget(const SizedBox());- app.dispose();- });+ testWidgets(+ 'focusing a pane then splitting $direction keeps its project and terminal',+ (tester) async {+ final (app, connection) = _splitApp();+ final frames = <TerminalBinaryFrame>[];+ final first = app.adoptSessionForTest(terminal('a0', frames));+ final neighbor = app.adoptSessionForTest(terminal('a1', frames));+ app.focusPane(neighbor.id);+ await mountWide(tester, app);+ tester.view.physicalSize = const Size(3000, 1800);+ await tester.pump();+ final target = find.byKey(first.cellKey);+ final rect = tester.getRect(target);+ final neighborRect = tester.getRect(find.byKey(neighbor.cellKey));+ final view = find.descendant(+ of: target,+ matching: find.byType(TerminalView),+ );+ final retained = tester.element(view);+ expect(find.byKey(ValueKey('pane-split-$direction')), findsNothing);+ final title = find.descendant(+ of: target,+ matching: find.byKey(const ValueKey('terminal-pane-title')),+ );+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);+ await mouse.addPointer(location: rect.center);+ await mouse.moveTo(tester.getCenter(title));+ await tester.pump();+ expect(app.focusedPaneId, neighbor.id);+ expect(tester.element(view), same(retained));+ expect(tester.getRect(target), rect);+ await tester.tap(title);+ await chord(tester, shortcut);+ await tester.pump();+ expect(_form(tester).split?.paneId, first.id);+ expect(_form(tester).engine, 'claude');+ expect(_form(tester).project.folder, '/work/a0');+ expect(app.focusedPaneId, first.id);+ expect(connection.creation, isNull);+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pump();+ expect(app.panes, [first, neighbor]);+ expect(tester.getRect(target), rect);+ expect(tester.element(view), same(retained));+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);+ await tester.pump(const Duration(milliseconds: 10));+ expect(frames.single.streamId, first.session!.streamId);+ frames.clear();+ await chord(tester, shortcut);+ await tester.pump();+ await _create(tester, connection);+ expect(app.panes.map((pane) => pane.agentId), ['a0', 'created', 'a1']);+ expect(tester.element(view), same(retained));+ expect(tester.getRect(find.byKey(neighbor.cellKey)), neighborRect);+ final splitRect = tester.getRect(target);+ final addedRect = tester.getRect(find.byKey(app.panes[1].cellKey));+ if (axis == PaneResizeAxis.x) {+ expect(addedRect.left, greaterThan(splitRect.right));+ expect(addedRect.top, splitRect.top);+ expect(addedRect.height, splitRect.height);+ } else {+ expect(addedRect.top, greaterThan(splitRect.bottom));+ expect(addedRect.left, splitRect.left);+ expect(addedRect.width, splitRect.width);+ }+ expect(frames, isEmpty);+ await mouse.removePointer();+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ },+ );}testWidgets('zoom restores the layout and keeps terminal renderers alive', (@@ -362,26 +362,20 @@ void main() {final view = find.descendant(of: pane, matching: find.byType(TerminalView));final retained = tester.element(view);final rect = tester.getRect(pane);- final zoom = find.descendant(- of: pane,- matching: find.byKey(const ValueKey('pane-zoom')),- );- await tester.tap(zoom);+ expect(find.byKey(const ValueKey('pane-zoom')), findsNothing);+ app.focusPane(first.id);+ await chord(tester, LogicalKeyboardKey.enter);await tester.pump();expect(app.focusedPaneId, first.id);expect(app.zoomedPaneId, first.id);expect(tester.element(view), same(retained));expect(tester.getSize(pane).width, greaterThan(rect.width));- final split = find.descendant(- of: pane,- matching: find.byKey(const ValueKey('pane-split-right')),- );- expect(tester.widget<PaneHeaderButton>(split).onPressed, isNull);- await tester.tap(split);+ expect(find.byKey(const ValueKey('pane-split-right')), findsNothing);+ await chord(tester, LogicalKeyboardKey.keyR);await tester.pump();expect(find.byType(NewHarnessForm), findsNothing);expect(connection.creation, isNull);- await tester.tap(zoom);+ await chord(tester, LogicalKeyboardKey.enter);await tester.pump();expect(app.zoomedPaneId, isNull);expect(tester.getRect(pane), rect);diff --git a/desktop/test/terminal_panel_header_test.dart b/desktop/test/terminal_panel_header_test.dartindex 17e5397d0..254d5f089 100644--- a/desktop/test/terminal_panel_header_test.dart+++ b/desktop/test/terminal_panel_header_test.dart@@ -167,15 +167,7 @@ void main() {final model = tester.getRect(find.byKey(const ValueKey(('pane-model', 'local', 'agent-1'))),);- final controls = [- for (final key in [- 'pane-split-down',- 'pane-split-right',- 'pane-zoom',- ])- tester.getRect(find.byKey(ValueKey(key))),- tester.getRect(find.byType(PaneCloseButton)),- ];+ final controls = [tester.getRect(find.byType(PaneCloseButton))];final agent = tester.getRect(find.byKey(const ValueKey('pane-agent-control')),);diff --git a/desktop/test/workspace_status_test.dart b/desktop/test/workspace_status_test.dartindex a6c760f68..ce305981f 100644--- a/desktop/test/workspace_status_test.dart+++ b/desktop/test/workspace_status_test.dart@@ -229,12 +229,6 @@ void main() {final cell = find.byKey(pane.cellKey);final controls = [find.byKey(ValueKey(('pane-model', 'm', pane.agentId!))),- for (final key in [- 'pane-split-down',- 'pane-split-right',- 'pane-zoom',- ])- find.descendant(of: cell, matching: find.byKey(ValueKey(key))),find.descendant(of: cell, matching: find.byType(PaneCloseButton)),];for (var i = 1; i < controls.length; i++) {diff --git a/docs/keyboard.md b/docs/keyboard.mdindex 9cf897422..8bada781c 100644--- a/docs/keyboard.md+++ b/docs/keyboard.md@@ -42,7 +42,7 @@ A harness can have views in several swarms, with one view per swarm; closing a pThe view closes immediately, without a minimize animation.Cmd-P opens an empty search field. Cmd-O inserts an editable `#` for projects.-Type `&` to choose a different agent for the focused harness. The pane header's agent name opens the same picker.+Type `&` to choose a different agent for the focused harness. The pane header's agent name opens the same picker. Switching saves the old session, keeps the project and pane in place, and passes recent requests and saved answers to agents that accept an initial message (OpenCode, Codex, Claude Code and Hermes). This is a bounded handoff, not the full original transcript; the original session remains saved.Delete the prefix to return to harness search. These fields use a thin caret andno separate prompt character.