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
Restore native appearance before showing the workspace
deea38482c41b01
diff --git a/desktop/lib/core/desktop_window.dart b/desktop/lib/core/desktop_window.dartindex 2b414c9f9..cbbf6b261 100644--- a/desktop/lib/core/desktop_window.dart+++ b/desktop/lib/core/desktop_window.dart@@ -3,6 +3,7 @@ import 'dart:io' show Platform;import 'package:window_manager/window_manager.dart';import 'package:flutter/services.dart';+import '../shared/theme/color_palette.dart';import 'build_identity.dart';/// Configures the native window before the first Flutter frame.@@ -10,7 +11,9 @@ import 'build_identity.dart';/// On macOS, AppKit places Swarm tabs beside the system traffic lights in a/// compact unified title bar. Flutter starts below that row. Windows and Linux/// keep their native caption bar and use the Flutter Swarm-tab fallback.-Future<void> configureDesktopWindow() async {+Future<void> configureDesktopWindow({+ HarnessPalette palette = HarnessPalette.graphite,+}) async {await windowManager.ensureInitialized();final options = WindowOptions(size: const Size(1280, 800),@@ -19,13 +22,15 @@ Future<void> configureDesktopWindow() async {center: true,titleBarStyle: TitleBarStyle.normal,);- await windowManager.waitUntilReadyToShow(options, () async {- if (Platform.isMacOS) {- await const MethodChannel('harness/swarm_tabs').invokeMethod('configure');- }- await windowManager.show();- await windowManager.focus();- });+ // The plugin's optional callback is a VoidCallback: an async callback would+ // return before native setup finishes and detach any error from this future.+ await windowManager.waitUntilReadyToShow(options);+ if (Platform.isMacOS) {+ await const MethodChannel('harness/swarm_tabs')+ .invokeMethod('configure', {'palette': palette.nativeColors});+ }+ await windowManager.show();+ await windowManager.focus();}/// Bring the window to the front, wherever it was.diff --git a/desktop/lib/main.dart b/desktop/lib/main.dartindex 03e1f48c3..f012af3d5 100644--- a/desktop/lib/main.dart+++ b/desktop/lib/main.dart@@ -38,9 +38,8 @@ Future<void> main() async {// Keyboard configuration has its own file and watchers. It can load beside// the appearance, but both must be ready before the window becomes usable.await Future.wait([loadPersistedSettings(), keymap.start()]);- // After the settings: the window shows itself once it is ready, and the- // first frame it shows must already wear the saved theme.- await configureDesktopWindow();+ // Apply the saved palette to native chrome as well as the Flutter theme.+ await configureDesktopWindow(palette: appearancePrefsStore.value.palette);runApp(ProviderScope(child: DesktopApp(keymap: keymap)));}diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swiftindex cf5ee22a9..a3759a836 100644--- a/desktop/macos/Runner/SwarmTitlebar.swift+++ b/desktop/macos/Runner/SwarmTitlebar.swift@@ -48,7 +48,8 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {guard let self else { result(nil); return }switch call.method {case "configure":- self.configure()+ let state = call.arguments as? [String: Any] ?? [:]+ self.configure(palette: state["palette"] as? [String: Any])result(true)case "update":let state = call.arguments as? [String: Any] ?? [:]@@ -208,7 +209,13 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {keymap.applyMenuKeys(to: main, context: context)}- private func configure() {+ private func configure(palette: [String: Any]? = nil) {+ // Appearance is loaded before the workspace exists. Apply it before the+ // explicit show request, without inventing tabs or enabling their actions.+ if let palette {+ strip.updatePalette(palette)+ window?.backgroundColor = strip.palette.tabBar+ }guard let window, !configured else { return }configured = trueNSWindow.allowsAutomaticWindowTabbing = false@@ -878,6 +885,7 @@ private final class SwarmTabStrip: NSView, NSSearchFieldDelegate {addSubview(button)}button(newButton, "plus", "New swarm (⌘T)", #selector(newSwarm))+ newButton.isEnabled = falsesearchField.delegate = selfsearchField.isEnabled = falsesearchField.begin = { [weak self] in self?.beginSearch() }@@ -889,14 +897,19 @@ private final class SwarmTabStrip: NSView, NSSearchFieldDelegate {}required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }+ func updatePalette(_ values: [String: Any]) {+ let nextPalette = SwarmNativePalette(values)+ guard nextPalette != palette else { return }+ palette = nextPalette+ searchField.palette = palette+ newButton.contentTintColor = palette.accent+ for tab in tabs { tab.palette = palette }+ needsDisplay = true+ }+func update(_ state: [String: Any]) {- let nextPalette = SwarmNativePalette(state["palette"] as? [String: Any] ?? [:])- if nextPalette != palette {- palette = nextPalette- searchField.palette = palette- newButton.contentTintColor = palette.accent- needsDisplay = true- }+ // Workspace teardown clears its controls without changing appearance.+ if let palette = state["palette"] as? [String: Any] { updatePalette(palette) }actionsEnabled = state["enabled"] as? Bool == truelet rows = state["tabs"] as? [[String: Any]] ?? []let nextActiveId = state["activeId"] as? String ?? ""diff --git a/desktop/test/desktop_window_test.dart b/desktop/test/desktop_window_test.dartnew file mode 100644index 000000000..c43e5c775--- /dev/null+++ b/desktop/test/desktop_window_test.dart@@ -0,0 +1,169 @@+import 'dart:async';+import 'dart:io';++import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/desktop_window.dart';+import 'package:harness/shared/theme/color_palette.dart';++const _windowChannel = MethodChannel('window_manager');+const _nativeChannel = MethodChannel('harness/swarm_tabs');+const _screenChannel = MethodChannel(+ 'dev.leanflutter.plugins/screen_retriever',+);+const _screenEvents = MethodChannel(+ 'dev.leanflutter.plugins/screen_retriever_event',+);+const _display = {+ 'id': 'isolated-display',+ 'size': {'width': 1920.0, 'height': 1080.0},+ 'visiblePosition': {'dx': 0.0, 'dy': 0.0},+};++void main() {+ final binding = TestWidgetsFlutterBinding.ensureInitialized();+ final calls = <String>[];+ final nativeCalls = <MethodCall>[];+ Future<Object?> Function(MethodCall)? nativeReply;+ Future<Object?> Function(MethodCall)? windowReply;++ setUp(() {+ calls.clear();+ nativeCalls.clear();+ nativeReply = null;+ windowReply = null;+ binding.defaultBinaryMessenger.setMockMethodCallHandler(_windowChannel, (+ call,+ ) async {+ calls.add(call.method);+ switch (call.method) {+ case 'isFullScreen':+ case 'isMaximized':+ case 'isMinimized':+ return false;+ case 'getBounds':+ return {'x': 0.0, 'y': 0.0, 'width': 1280.0, 'height': 800.0};+ default:+ return await windowReply?.call(call);+ }+ });+ binding.defaultBinaryMessenger.setMockMethodCallHandler(_nativeChannel, (+ call,+ ) async {+ calls.add('native:${call.method}');+ nativeCalls.add(call);+ return nativeReply == null ? true : await nativeReply!(call);+ });+ binding.defaultBinaryMessenger.setMockMethodCallHandler(+ _screenChannel,+ (call) async => switch (call.method) {+ 'getPrimaryDisplay' => _display,+ 'getAllDisplays' => {+ 'displays': [_display],+ },+ 'getCursorScreenPoint' => {'dx': 100.0, 'dy': 100.0},+ _ => null,+ },+ );+ binding.defaultBinaryMessenger.setMockMethodCallHandler(+ _screenEvents,+ (_) async => null,+ );+ });++ tearDown(() {+ for (final channel in [+ _windowChannel,+ _nativeChannel,+ _screenChannel,+ _screenEvents,+ ]) {+ binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null);+ }+ });++ testWidgets('window readiness awaits native setup, show and focus', (+ tester,+ ) async {+ final nativeReady = Completer<Object?>();+ final shown = Completer<Object?>();+ final focused = Completer<Object?>();+ nativeReply = (_) => nativeReady.future;+ windowReply = (call) => switch (call.method) {+ 'show' => shown.future,+ 'focus' => focused.future,+ _ => Future.value(),+ };+ var finished = false;+ final setup = configureDesktopWindow().then((_) => finished = true);+ await tester.pump();+ final beforeNative = finished;+ expect(calls, contains('native:configure'));+ expect(calls, isNot(contains('show')));+ nativeReady.complete(true);+ await tester.pump();+ final beforeShow = finished;+ expect(calls, contains('show'));+ expect(calls, isNot(contains('focus')));+ shown.complete();+ await tester.pump();+ final beforeFocus = finished;+ expect(calls, contains('focus'));+ focused.complete();+ await tester.pump();+ await setup;++ expect([beforeNative, beforeShow, beforeFocus], [false, false, false]);+ expect(finished, isTrue);+ }, skip: !Platform.isMacOS);++ testWidgets('the initial native configuration contains the palette', (+ tester,+ ) async {+ final setup = configureDesktopWindow();+ await tester.pump();+ await setup;+ expect(nativeCalls.single.method, 'configure');+ expect(nativeCalls.single.arguments, {+ 'palette': HarnessPalette.graphite.nativeColors,+ });+ expect(calls.indexOf('native:configure'), lessThan(calls.indexOf('show')));+ }, skip: !Platform.isMacOS);++ testWidgets('every saved palette reaches native setup before showing', (+ tester,+ ) async {+ for (final palette in HarnessPalette.values) {+ calls.clear();+ nativeCalls.clear();+ final setup = configureDesktopWindow(palette: palette);+ await tester.pump();+ await setup;+ expect(nativeCalls.single.arguments, {'palette': palette.nativeColors});+ expect(+ calls.indexOf('native:configure'),+ lessThan(calls.indexOf('show')),+ );+ expect(calls.where((call) => call == 'show'), hasLength(1));+ expect(calls.where((call) => call == 'focus'), hasLength(1));+ }+ }, skip: !Platform.isMacOS);++ testWidgets('native setup failures propagate without showing the window', (+ tester,+ ) async {+ nativeReply = (_) async => throw PlatformException(code: 'SETUP_FAILED');+ final setup = configureDesktopWindow(palette: HarnessPalette.forest);+ final failed = expectLater(+ setup,+ throwsA(+ isA<PlatformException>().having((e) => e.code, 'code', 'SETUP_FAILED'),+ ),+ );+ await tester.pump();+ await failed;+ expect(calls, contains('native:configure'));+ expect(calls, isNot(contains('show')));+ expect(calls, isNot(contains('focus')));+ }, skip: !Platform.isMacOS);+}diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swiftindex 238d9efdb..c805dad44 100644--- a/desktop/tool/swarm_titlebar_checks.swift+++ b/desktop/tool/swarm_titlebar_checks.swift@@ -36,6 +36,14 @@ private extension SwarmTabButton {}private extension SwarmTabStrip {+ func checkStartupPalette(_ expected: SwarmNativePalette) throws {+ try checkTitlebar(palette == expected && searchField.palette == expected &&+ newButton.contentTintColor == expected.accent,+ "Initial search and new-swarm colors use the saved palette")+ try checkTitlebar(tabs.isEmpty && !actionsEnabled && !newButton.isEnabled && !searchField.isEnabled,+ "Initial 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)!@@ -351,6 +359,7 @@ private extension SwarmTabStrip {// No engine, account, terminal or transport is involved in native layout.private final class TitlebarCheckMessenger: NSObject, FlutterBinaryMessenger {var calls: [FlutterMethodCall] = []+ private var handlers: [String: FlutterBinaryMessageHandler] = [:]var holdReplies = falsevar replies: [FlutterBinaryReply] = []func finishNextReply() {@@ -366,7 +375,20 @@ private final class TitlebarCheckMessenger: NSObject, FlutterBinaryMessenger {else { callback(FlutterStandardMethodCodec.sharedInstance().encodeSuccessEnvelope(nil)) }}}- func setMessageHandlerOnChannel(_ channel: String, binaryMessageHandler handler: FlutterBinaryMessageHandler?) -> FlutterBinaryMessengerConnection { 1 }+ func setMessageHandlerOnChannel(_ channel: String, binaryMessageHandler handler: FlutterBinaryMessageHandler?) -> FlutterBinaryMessengerConnection {+ handlers[channel] = handler+ return 1+ }+ func receive(_ method: String, arguments: [String: Any]) throws -> Data? {+ guard let handler = handlers["harness/swarm_tabs"] else {+ throw TitlebarCheckFailure(message: "Native channel handler is installed")+ }+ var reply: Data?+ let message = FlutterStandardMethodCodec.sharedInstance().encode(+ FlutterMethodCall(methodName: method, arguments: arguments))+ handler(message) { reply = $0 }+ return reply+ }func cleanUpConnection(_ connection: FlutterBinaryMessengerConnection) {}}@@ -490,7 +512,29 @@ private extension SwarmTitlebar {main.addItem(item)}NSApp.mainMenu = main+ let startupColors: [String: Any] = [+ "tabBar": Int64(0xff1b2720), "workspace": Int64(0xff2b3b31),+ "search": Int64(0xff293a31), "accent": Int64(0xffb4d8be),+ ]+ let reply = try messenger.receive("configure", arguments: ["palette": startupColors])+ try checkTitlebar(reply == FlutterStandardMethodCodec.sharedInstance().encodeSuccessEnvelope(true),+ "Native configure acknowledges the initial palette synchronously")+ let startupPalette = SwarmNativePalette(startupColors)+ try checkTitlebar(strip.palette == startupPalette && window.backgroundColor == startupPalette.tabBar,+ "The saved palette reaches native chrome before any workspace update")+ try strip.checkStartupPalette(startupPalette)configure()+ try checkTitlebar(strip.palette == startupPalette && window.titlebarAccessoryViewControllers.count == 1,+ "Repeated configuration preserves the saved palette and one titlebar accessory")+ _ = try messenger.receive("update", arguments: [+ "tabs": [["id": "startup-check", "name": "Synthetic swarm"]],+ "activeId": "startup-check", "enabled": true, "palette": startupColors,+ ])+ // SwarmScreen.dispose sends this when sign-in or setup takes its place.+ _ = try messenger.receive("update", arguments: ["tabs": [], "enabled": false])+ try checkTitlebar(window.backgroundColor == startupPalette.tabBar,+ "Leaving the workspace preserves the saved native background")+ try strip.checkStartupPalette(startupPalette)try checkTitlebar(window.firstResponder === window.contentViewController,"Adding the search field does not take initial keyboard focus from the workspace")try checkTitlebar(main.items.map(\.title) == ["Harness V2", "File", "Edit", "View", "History", "Models", "Window", "Help"], "Models replaces the redundant Swarm menu")diff --git a/docs/harness-v2-appearance-onboarding.md b/docs/harness-v2-appearance-onboarding.mdindex 5e68fb894..69ef0abee 100644--- a/docs/harness-v2-appearance-onboarding.md+++ b/docs/harness-v2-appearance-onboarding.md@@ -20,6 +20,14 @@ The existing ANSI color ramp and explicit agent-emitted colors remain intact. AVerification includes persistence/reload, keyboard operation, narrow layout, contrast, retained terminal identity and native titlebar/query identity. Primary text meets 7:1 on each terminal background; the tested secondary text meets 4.5:1 on the search, card and workspace surfaces. These checks cover Harness defaults, not arbitrary colors emitted by an agent.+## Native appearance during startup and sign-in++Saved colors now travel with the initial native `configure` request, before the app's explicit show request. Previously only an authenticated Swarm screen supplied those colors, so the native titlebar used Graphite during startup/sign-in even when Flutter had loaded a different palette. Clearing a workspace also used to reset the native colors because its teardown packet intentionally omits palette data. That omission now means retain the current palette.++New swarm and Search remain disabled until the workspace enables them. Repeated native configuration preserves the current palette and one titlebar accessory. The existing tab controls, search editor, query and composition survive later palette updates.++The window setup future now awaits configure, show and focus requests directly. The installed window library's callback is synchronous and previously allowed that future to report completion before its async native work finished. Delayed-reply checks reproduced the issue; error responses now reach the awaited setup call. These checks exercise actual Dart request ordering and a hidden AppKit window. Live first-frame presentation and macOS foreground activation remain unmeasured.+## Onboarding evidence and direction| Primary source | Observed behavior | Harness adaptation |diff --git a/docs/harness-v2-progress.md b/docs/harness-v2-progress.mdindex 814c19734..f96824073 100644--- a/docs/harness-v2-progress.md+++ b/docs/harness-v2-progress.md@@ -2,6 +2,15 @@Updated 2026-09-13 with coordinated palettes, Models, combined closed-work History and faster unified search. This is a working preview, not a release.+## Native startup appearance checkpoint++- The loaded palette now reaches native titlebar configuration before the explicit show request, including startup and sign-in where no Swarm screen exists yet. Native New swarm and Search controls begin disabled; a palette update neither creates tabs nor enables workspace actions.+- A reproduced teardown regression reset the native palette when Swarm screen disposal sent only `tabs: []` and `enabled: false`. An omitted palette now preserves the current colors, so leaving the workspace does not revert its native chrome to Graphite. Explicit palette updates retain existing tab/search controls.+- Window setup now awaits native configuration, show and focus requests directly. The installed `window_manager` callback is a `VoidCallback` and does not await an async callback. A delayed-reply test showed the old setup future completing while all three operations were still pending. Failures now propagate through the setup future instead of escaping it.+- **40 focused Flutter tests passed**, including all six initial palette payloads, delayed setup replies, error propagation, persisted settings and the existing startup/sign-in/first-workspace screens. **51 native decoder and 371 AppKit checks passed** against Dart's exported bindings. The AppKit checks include initial colors, repeated configuration, workspace teardown, keyboard ownership and retained search composition, with no window displayed.+- Reproductions: `/private/tmp/harness-v2-window-startup-before.log`, `/private/tmp/harness-v2-window-palette-native-before.log` and `/private/tmp/harness-v2-window-palette-exit-before.log`. Final checks: `/private/tmp/harness-v2-window-startup-tests.log` and `/private/tmp/harness-v2-window-palette-native.log`. This establishes request ordering and color retention in isolation; live launch presentation and foreground native timing remain unmeasured.+- Analyzer has zero errors/warnings and the existing 12 vendored infos (`/private/tmp/harness-v2-window-startup-analyze.log`). Public-origin push approval is still pending.+## Startup settings checkpoint- Five per-key appearance reads now use two grouped snapshots through the existing serialized file store. Each snapshot returns only requested keys and is discarded after the read. Locking, private permissions, corruption recovery and future-schema protection remain intact; later reads see intervening writes.@@ -9,6 +18,7 @@ Updated 2026-09-13 with coordinated palettes, Models, combined closed-work Histo- In one isolated debug benchmark run with warm temporary files, settings-plus-keyboard initialization went from **31.877 ms median / 34.919 ms p95** to **13.042 / 14.295 ms**. This is one initialization step, not full app launch or native display latency. The explicit benchmark is `desktop/test/benchmarks/startup_benchmark.dart`; [performance notes](harness-v2-performance.md) record the setup and limits.- **58 focused tests passed**, covering complete preference/counter restoration, all-store readiness under delayed/failed reads, temporary-store isolation, selected-key batches, intervening writes/deletes and existing permission/schema protections. Artifacts: `/private/tmp/harness-v2-startup-tests.log` and `/private/tmp/harness-v2-startup-benchmark-{before,after}.log`.- Analyzer has zero errors/warnings and the existing 12 vendored infos (`/private/tmp/harness-v2-startup-analyze.log`). The explicit benchmark is excluded from ordinary test discovery and does not collect user settings.+- Saved as local commit `6c192ee`. Release build succeeded (`/private/tmp/harness-v2-startup-build.log`), and the exact development preview reopened as PID 40428 after PID 26548 was normally quit and confirmed exited.- Startup tests now inject all three stores; none falls through to the user's global appearance or stats store. No real agent, credential or keyboard configuration was used in validation. Public-origin push approval remains pending; preserve unrelated naming edits, the collaboration draft and native benchmark tooling.## Search arrival and typing checkpoint