Skip to content

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.

Reduce settings initialization work before the first frame

dee6c192ee42560
diff --git a/desktop/lib/core/harness_file_store.dart b/desktop/lib/core/harness_file_store.dart
index c5bd7ffc5..6d0994fd3 100644
--- a/desktop/lib/core/harness_file_store.dart
+++ b/desktop/lib/core/harness_file_store.dart
@@ -9,7 +9,7 @@ import 'local_key_value_store.dart';
/// The file contains credentials and E2EE key material. Its parent directory
/// is private to the current user and every file created here is mode 0600 on
/// POSIX platforms. Values are never logged.
-class HarnessFileStore implements LocalKeyValueStore {
+class HarnessFileStore implements BatchLocalKeyValueStore {
static const schemaVersion = 1;
// Separate from production; the CLI still owns shared authentication and links.
static const directoryName = 'desktop-app-v2';
@@ -52,6 +52,20 @@ class HarnessFileStore implements LocalKeyValueStore {
Future<String?> read(String key) =>
_serialized(() async => (await _readDocument())[key]);
+ /// One lock and document read for related preferences. The snapshot is scoped
+ /// to this call: later reads still observe intervening writes, including
+ /// writes from another store or process. Unrequested credentials never leave
+ /// this operation.
+ @override
+ Future<Map<String, String?>> readMany(Iterable<String> keys) {
+ final requested = keys.toSet();
+ if (requested.isEmpty) return Future.value(const <String, String?>{});
+ return _serialized(() async {
+ final values = await _readDocument();
+ return {for (final key in requested) key: values[key]};
+ });
+ }
+
@override
Future<void> write(String key, String value) => _serialized(() async {
final values = await _readDocument();
diff --git a/desktop/lib/core/local_key_value_store.dart b/desktop/lib/core/local_key_value_store.dart
index 4f085a067..106467ae8 100644
--- a/desktop/lib/core/local_key_value_store.dart
+++ b/desktop/lib/core/local_key_value_store.dart
@@ -5,3 +5,22 @@ abstract interface class LocalKeyValueStore {
Future<void> delete(String key);
}
+
+/// Stores that can read a group in one operation, preserving a single snapshot.
+abstract interface class BatchLocalKeyValueStore implements LocalKeyValueStore {
+ /// Returns only the requested keys. Missing values are represented by null.
+ Future<Map<String, String?>> readMany(Iterable<String> keys);
+}
+
+extension LocalKeyValueStoreBatchRead on LocalKeyValueStore {
+ /// Falls back to ordinary reads for stores without a batch operation.
+ Future<Map<String, String?>> readMany(Iterable<String> keys) async {
+ final store = this;
+ if (store is BatchLocalKeyValueStore) return store.readMany(keys);
+ final values = <String, String?>{};
+ for (final key in keys.toSet()) {
+ values[key] = await read(key);
+ }
+ return values;
+ }
+}
diff --git a/desktop/lib/core/startup.dart b/desktop/lib/core/startup.dart
index e22ca01c1..277a25187 100644
--- a/desktop/lib/core/startup.dart
+++ b/desktop/lib/core/startup.dart
@@ -19,15 +19,16 @@ Future<void> loadPersistedSettings({
AppearancePrefsStore? appearance,
HarnessStats? stats,
}) async {
- await (terminalFont ?? terminalFontStore).load();
- // Not optional. Every control box in the app is sized from
- // `AppControl.heightScaled`/`paddingScaled`, so a UI size that arrived after
- // the first frame would relayout the whole window one frame in — a worse
- // flicker than a late theme, because the geometry moves and not just the ink.
- await (appearance ?? appearancePrefsStore).load();
- // Not for the first frame — nothing paints these counters until Settings ▸
- // Usage is opened. It is loaded here anyway because the counters START moving
- // as soon as an agent does, and a load that landed after the first
- // `onAgentSpawned` would overwrite it with the number from disk.
- await (stats ?? harnessStats).load();
+ // Independent stores may load together, but all must finish before runApp.
+ // Font and appearance share a serialized file store; each reads its related
+ // preferences as one snapshot. Stats uses a separate file and can overlap.
+ await Future.wait([
+ (terminalFont ?? terminalFontStore).load(),
+ // Every control box uses these values. A late load would move the whole
+ // window's geometry after its first frame, as well as changing its palette.
+ (appearance ?? appearancePrefsStore).load(),
+ // Counters begin moving with the first agent event. Loading them later
+ // could overwrite a new event with the old count from disk.
+ (stats ?? harnessStats).load(),
+ ]);
}
diff --git a/desktop/lib/main.dart b/desktop/lib/main.dart
index 10db79eeb..03e1f48c3 100644
--- a/desktop/lib/main.dart
+++ b/desktop/lib/main.dart
@@ -34,9 +34,10 @@ Future<void> main() async {
installFileLogs();
CrashLog.install();
appLog.info('app', 'launched');
- await loadPersistedSettings();
final keymap = AppKeymap(store: AppKeymap.fileStore());
- await keymap.start();
+ // 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();
diff --git a/desktop/lib/shared/theme/appearance_prefs_store.dart b/desktop/lib/shared/theme/appearance_prefs_store.dart
index 529b11b9a..18d94af35 100644
--- a/desktop/lib/shared/theme/appearance_prefs_store.dart
+++ b/desktop/lib/shared/theme/appearance_prefs_store.dart
@@ -96,13 +96,15 @@ class AppearancePrefsStore extends ValueNotifier<AppearancePrefs> {
/// should get a plain-looking app, not an app that refuses to start.
Future<void> load() async {
try {
- final family = await _storage.read(_familyKey);
- final size = await _storage.read(_sizeKey);
- final palette = await _storage.read(_paletteKey);
+ final saved = await _storage.readMany([
+ _familyKey,
+ _sizeKey,
+ _paletteKey,
+ ]);
value = AppearancePrefs(
- uiFamily: _familyFrom(family),
- uiSize: _sizeFrom(size),
- palette: HarnessPalette.fromId(palette),
+ uiFamily: _familyFrom(saved[_familyKey]),
+ uiSize: _sizeFrom(saved[_sizeKey]),
+ palette: HarnessPalette.fromId(saved[_paletteKey]),
);
} catch (_) {
value = const AppearancePrefs();
diff --git a/desktop/lib/terminal/terminal_font_store.dart b/desktop/lib/terminal/terminal_font_store.dart
index e36455ee6..637d3fb51 100644
--- a/desktop/lib/terminal/terminal_font_store.dart
+++ b/desktop/lib/terminal/terminal_font_store.dart
@@ -149,8 +149,9 @@ class TerminalFontStore extends ValueNotifier<TerminalStyle> {
/// an unreadable state file is not a reason to refuse to start.
Future<void> load() async {
try {
- final savedFamily = await _storage.read(_familyKey);
- final savedSize = await _storage.read(_sizeKey);
+ final saved = await _storage.readMany([_familyKey, _sizeKey]);
+ final savedFamily = saved[_familyKey];
+ final savedSize = saved[_sizeKey];
final choice = TerminalFontChoice.values
.where((c) => c.name == savedFamily)
.firstOrNull;
diff --git a/desktop/test/benchmarks/startup_benchmark.dart b/desktop/test/benchmarks/startup_benchmark.dart
new file mode 100644
index 000000000..0a4fe23ec
--- /dev/null
+++ b/desktop/test/benchmarks/startup_benchmark.dart
@@ -0,0 +1,109 @@
+// Run explicitly: flutter test --no-pub test/benchmarks/startup_benchmark.dart
+// Measures settings initialization in the debug runner with temporary files.
+// It does not measure a cold process launch, native window or first frame.
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/harness_file_store.dart';
+import 'package:harness/core/snapshot_store.dart';
+import 'package:harness/core/startup.dart';
+import 'package:harness/shared/theme/appearance_prefs_store.dart';
+import 'package:harness/shared/theme/color_palette.dart';
+import 'package:harness/shortcuts/app_keymap.dart';
+import 'package:harness/shortcuts/keymap_commands.dart';
+import 'package:harness/shortcuts/keymap_store.dart';
+import 'package:harness/stats/harness_stats.dart';
+import 'package:harness/terminal/terminal_font_store.dart';
+
+Map<String, num> distribution(List<int> times) {
+ times.sort();
+ return {
+ 'samples': times.length,
+ 'medianMs': times[times.length ~/ 2] / 1000,
+ 'p95Ms': times[(times.length * .95).ceil() - 1] / 1000,
+ };
+}
+
+void main() {
+ test('isolated persisted settings and keyboard initialization', () async {
+ final directory = await Directory.systemTemp.createTemp(
+ 'harness-startup-benchmark-',
+ );
+ addTearDown(() => directory.delete(recursive: true));
+ final preferences = Directory('${directory.path}/preferences');
+ final storage = HarnessFileStore(directory: preferences);
+ await storage.write('terminal_font_family', 'menlo');
+ await storage.write('terminal_font_size', '17');
+ await storage.write('app_ui_font_family', 'Helvetica Neue');
+ await storage.write('app_ui_font_size', '16');
+ await storage.write('app_color_palette', 'forest');
+ final statsStore = FileSnapshotStore('stats', directory: directory);
+ await statsStore.write(
+ jsonEncode({
+ 'version': 1,
+ 'agentsSpawned': 12,
+ 'turns': 34,
+ 'workedMs': 56000,
+ }),
+ );
+ final keymapFile = File('${directory.path}/config/keybindings.jsonc');
+ await keymapFile.parent.create();
+ await keymapFile.writeAsString(
+ '{"bindings":[{"keys":"cmd+g","command":"navigation.quick_open"}]}',
+ );
+
+ for (final withKeymap in [false, true]) {
+ final times = <int>[];
+ // Fresh store objects, warm filesystem. Never read the user's settings.
+ for (var sample = -20; sample < 100; sample++) {
+ final storage = HarnessFileStore(directory: preferences);
+ final font = TerminalFontStore(storage: storage);
+ final appearance = AppearancePrefsStore(storage: storage);
+ final stats = HarnessStats(store: statsStore);
+ final keymapStore = KeymapStore(
+ file: keymapFile,
+ defaults: harnessDefaultBindings,
+ commands: harnessCommandById.keys.toSet(),
+ validate: (map) =>
+ AppKeymap.validateNativeKeys(map, macOS: Platform.isMacOS),
+ );
+ final keymap = AppKeymap(store: keymapStore);
+ try {
+ final watch = Stopwatch()..start();
+ await Future.wait([
+ loadPersistedSettings(
+ terminalFont: font,
+ appearance: appearance,
+ stats: stats,
+ ),
+ if (withKeymap) keymap.start(),
+ ]);
+ watch.stop();
+ if (sample >= 0) times.add(watch.elapsedMicroseconds);
+ expect(font.family, TerminalFontChoice.menlo);
+ expect(font.size, 17);
+ expect(appearance.value.uiFamily, 'Helvetica Neue');
+ expect(appearance.value.uiSize, 16);
+ expect(appearance.value.palette, HarnessPalette.forest);
+ expect(stats.summary.agentsSpawned, 12);
+ if (withKeymap) {
+ expect(keymap.error, isNull);
+ expect(keymap.bindings('navigation.quick_open').length, 2);
+ }
+ } finally {
+ keymap.dispose();
+ keymapStore.dispose();
+ stats.dispose();
+ font.dispose();
+ appearance.dispose();
+ }
+ }
+ // Only timing and a fixed workload label leave the fixture.
+ debugPrint(
+ 'STARTUP_BENCH ${jsonEncode({'kind': 'headless_debug_warm_filesystem', 'operation': withKeymap ? 'settings_and_keymap' : 'settings', ...distribution(times)})}',
+ );
+ }
+ });
+}
diff --git a/desktop/test/harness_file_store_test.dart b/desktop/test/harness_file_store_test.dart
index 89500e4ca..e57a98a05 100644
--- a/desktop/test/harness_file_store_test.dart
+++ b/desktop/test/harness_file_store_test.dart
@@ -96,6 +96,57 @@ void main() {
);
});
+ test('batch reads select keys and respect intervening writes', () async {
+ final first = HarnessFileStore(directory: dataDirectory);
+ final second = HarnessFileStore(directory: dataDirectory);
+ await first.write('preference', 'before');
+ await first.write('credential', 'synthetic-secret');
+
+ final keys = ['preference', 'missing', 'preference'];
+ final before = first.readMany(keys);
+ keys.add('credential'); // An enqueued request owns its original key set.
+ final write = second.write('preference', 'after');
+ final after = first.readMany(['preference', 'missing']);
+ expect(await before, {'preference': 'before', 'missing': null});
+ await write;
+ expect(await after, {'preference': 'after', 'missing': null});
+
+ await second.delete('preference');
+ expect(await first.readMany(['preference']), {'preference': null});
+ expect(await second.read('credential'), 'synthetic-secret');
+ });
+
+ test('an empty batch does not create storage', () async {
+ final store = HarnessFileStore(directory: dataDirectory);
+ expect(await store.readMany([]), isEmpty);
+ expect(await dataDirectory.exists(), isFalse);
+ });
+
+ test('batch reads retain corruption and future-schema recovery', () async {
+ final store = HarnessFileStore(directory: dataDirectory);
+ await store.write('seed', 'value');
+ await store.stateFile.writeAsString('{broken');
+ expect(await store.readMany(['seed']), {'seed': null});
+ expect(await store.stateFile.exists(), isFalse);
+ final backups = await dataDirectory
+ .list()
+ .where((entry) => entry.path.contains('state.corrupt-'))
+ .toList();
+ expect(backups, hasLength(1));
+ expect(await File(backups.single.path).readAsString(), '{broken');
+
+ final futureDocument = jsonEncode({
+ 'version': HarnessFileStore.schemaVersion + 1,
+ 'values': {'seed': 'future'},
+ });
+ await store.stateFile.writeAsString(futureDocument);
+ await expectLater(
+ store.readMany(['seed']),
+ throwsA(isA<UnsupportedStateVersionException>()),
+ );
+ expect(await store.stateFile.readAsString(), futureDocument);
+ });
+
test('quarantines malformed JSON and starts with empty state', () async {
final store = HarnessFileStore(directory: dataDirectory);
await store.write('seed', 'value');
diff --git a/desktop/test/startup_test.dart b/desktop/test/startup_test.dart
index 5b6ee0450..b1a22a4bd 100644
--- a/desktop/test/startup_test.dart
+++ b/desktop/test/startup_test.dart
@@ -1,56 +1,206 @@
+import 'dart:async';
+import 'dart:convert';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/harness_file_store.dart';
+import 'package:harness/core/local_key_value_store.dart';
+import 'package:harness/core/snapshot_store.dart';
import 'package:harness/core/startup.dart';
+import 'package:harness/shared/theme/appearance_prefs_store.dart';
+import 'package:harness/shared/theme/color_palette.dart';
+import 'package:harness/stats/harness_stats.dart';
import 'package:harness/terminal/terminal_font_store.dart';
+import 'package:harness/terminal/terminal_typography.dart';
+
+class _GatedSettings extends Fake implements BatchLocalKeyValueStore {
+ final ready = Completer<Map<String, String?>>();
+ final requests = <Set<String>>[];
+
+ @override
+ Future<Map<String, String?>> readMany(Iterable<String> keys) {
+ requests.add(keys.toSet());
+ return ready.future;
+ }
+}
+
+class _GatedSnapshot extends Fake implements SnapshotStore {
+ final ready = Completer<String?>();
+ var requested = false;
+
+ @override
+ Future<String?> read() {
+ requested = true;
+ return ready.future;
+ }
+}
void main() {
late Directory dir;
+ late HarnessFileStore storage;
+ late FileSnapshotStore statsStorage;
+ late TerminalFontStore font;
+ late AppearancePrefsStore appearance;
+ late HarnessStats stats;
setUp(() async {
dir = await Directory.systemTemp.createTemp('harness-startup-');
+ storage = HarnessFileStore(directory: Directory('${dir.path}/settings'));
+ statsStorage = FileSnapshotStore('stats', directory: dir);
+ font = TerminalFontStore(storage: storage);
+ appearance = AppearancePrefsStore(storage: storage);
+ stats = HarnessStats(store: statsStorage);
});
tearDown(() async {
- if (dir.existsSync()) await dir.delete(recursive: true);
+ font.dispose();
+ appearance.dispose();
+ stats.dispose();
+ await dir.delete(recursive: true);
});
- test(
- 'a relaunch restores every preference the first frame depends on',
- () async {
- // A previous run, writing through the real store rather than a fake: this is the one test that
- // covers the on-disk FORMAT as well as the logic, so a change to how values are serialized
- // cannot pass here while breaking real launches.
- final previousRun = HarnessFileStore(directory: dir);
- // One instance for both edits, as the app has: a second store would not know about the family
- // the first one set, and would write the default back over it.
- final previousFont = TerminalFontStore(storage: previousRun);
- await previousFont.setFamily(TerminalFontChoice.menlo);
- await previousFont.setSize(17);
-
- // The next launch: a brand-new store over the same directory, loaded the way main() loads it.
- final terminalFont = TerminalFontStore(
- storage: HarnessFileStore(directory: dir),
- );
- await loadPersistedSettings(terminalFont: terminalFont);
+ test('a relaunch restores appearance and counters before returning', () async {
+ // Every store, including stats, uses only this test's temporary directory.
+ // Write through the real setters so the persisted formats are exercised.
+ await font.setFamily(TerminalFontChoice.menlo);
+ await font.setSize(17);
+ await appearance.setUiFamily('Helvetica Neue');
+ await appearance.setUiSize(16);
+ await appearance.setPalette(HarnessPalette.forest);
+ final at = DateTime.utc(2026, 9, 13);
+ stats.onAgentSpawned(at: at);
+ stats.onTurnStarted('synthetic-agent', at: at);
+ stats.onTurnEnded(
+ 'synthetic-agent',
+ at: at.add(const Duration(minutes: 2)),
+ );
+ await stats.flush();
- expect(terminalFont.family, TerminalFontChoice.menlo);
- expect(terminalFont.size, 17.0);
- },
- );
+ final reopened = HarnessFileStore(directory: storage.directory);
+ final nextFont = TerminalFontStore(storage: reopened);
+ final nextAppearance = AppearancePrefsStore(storage: reopened);
+ final nextStats = HarnessStats(
+ store: FileSnapshotStore('stats', directory: dir),
+ );
+ addTearDown(nextFont.dispose);
+ addTearDown(nextAppearance.dispose);
+ addTearDown(nextStats.dispose);
+ await loadPersistedSettings(
+ terminalFont: nextFont,
+ appearance: nextAppearance,
+ stats: nextStats,
+ );
+
+ expect(nextFont.family, TerminalFontChoice.menlo);
+ expect(nextFont.size, 17);
+ expect(
+ nextAppearance.value,
+ const AppearancePrefs(
+ uiFamily: 'Helvetica Neue',
+ uiSize: 16,
+ palette: HarnessPalette.forest,
+ ),
+ );
+ expect(nextStats.summary.agentsSpawned, 1);
+ expect(nextStats.summary.turns, 1);
+ expect(nextStats.summary.timeWorked, const Duration(minutes: 2));
+ expect(nextStats.summary.firstEventAt, at);
+ });
+
+ test('a first launch restores defaults from empty isolated stores', () async {
+ await loadPersistedSettings(
+ terminalFont: font,
+ appearance: appearance,
+ stats: stats,
+ );
+ expect(font.family, TerminalFontChoice.defaultForPlatform);
+ expect(font.size, terminalFontSize);
+ expect(appearance.value, const AppearancePrefs());
+ expect(stats.summary.isEmpty, isTrue);
+ expect(await storage.stateFile.exists(), isFalse);
+ expect(await statsStorage.file.exists(), isFalse);
+ });
test(
- 'a first-ever launch lands on the defaults instead of throwing',
+ 'independent loads overlap but readiness waits for every store',
() async {
- // Nothing written yet — the directory exists and holds no state file at all.
- final terminalFont = TerminalFontStore(
- storage: HarnessFileStore(directory: dir),
+ final fontStorage = _GatedSettings();
+ final appearanceStorage = _GatedSettings();
+ final counters = _GatedSnapshot();
+ final font = TerminalFontStore(storage: fontStorage);
+ final appearance = AppearancePrefsStore(storage: appearanceStorage);
+ final stats = HarnessStats(store: counters);
+ addTearDown(font.dispose);
+ addTearDown(appearance.dispose);
+ addTearDown(stats.dispose);
+ var finished = false;
+ final loading = loadPersistedSettings(
+ terminalFont: font,
+ appearance: appearance,
+ stats: stats,
+ ).then((_) => finished = true);
+
+ expect(fontStorage.requests, [
+ {'terminal_font_family', 'terminal_font_size'},
+ ]);
+ expect(appearanceStorage.requests, [
+ {'app_ui_font_family', 'app_ui_font_size', 'app_color_palette'},
+ ]);
+ expect(counters.requested, isTrue);
+ expect(finished, isFalse);
+ appearanceStorage.ready.complete({
+ 'app_ui_font_family': null,
+ 'app_ui_font_size': '18',
+ 'app_color_palette': 'midnight',
+ });
+ await Future<void>.delayed(Duration.zero);
+ expect(appearance.value.uiSize, 18);
+ expect(appearance.value.palette, HarnessPalette.midnight);
+ expect(finished, isFalse);
+
+ fontStorage.ready.complete({
+ 'terminal_font_family': 'menlo',
+ 'terminal_font_size': '17',
+ });
+ await Future<void>.delayed(Duration.zero);
+ expect(font.family, TerminalFontChoice.menlo);
+ expect(font.size, 17);
+ expect(
+ finished,
+ isFalse,
+ reason: 'Counters must precede new agent events',
);
- await loadPersistedSettings(terminalFont: terminalFont);
- // Per platform since the Linux work — not a fixed face this repo picked.
- expect(terminalFont.family, TerminalFontChoice.defaultForPlatform);
+ counters.ready.complete(jsonEncode({'version': 1, 'agentsSpawned': 12}));
+ await loading;
+ expect(finished, isTrue);
+ stats.onAgentSpawned();
+ expect(stats.summary.agentsSpawned, 13);
},
);
+
+ test('failed appearance reads still wait for saved counters', () async {
+ final broken = _GatedSettings();
+ final counters = _GatedSnapshot();
+ final font = TerminalFontStore(storage: broken);
+ final appearance = AppearancePrefsStore(storage: broken);
+ final stats = HarnessStats(store: counters);
+ addTearDown(font.dispose);
+ addTearDown(appearance.dispose);
+ addTearDown(stats.dispose);
+ var finished = false;
+ final loading = loadPersistedSettings(
+ terminalFont: font,
+ appearance: appearance,
+ stats: stats,
+ ).then((_) => finished = true);
+ broken.ready.completeError(const FileSystemException('unreadable'));
+ await Future<void>.delayed(Duration.zero);
+ expect(finished, isFalse);
+ expect(font.family, TerminalFontChoice.defaultForPlatform);
+ expect(appearance.value, const AppearancePrefs());
+ counters.ready.complete(jsonEncode({'version': 1, 'agentsSpawned': 5}));
+ await loading;
+ expect(stats.summary.agentsSpawned, 5);
+ });
}
diff --git a/docs/harness-v2-performance.md b/docs/harness-v2-performance.md
index 4e59fd825..61ffefe70 100644
--- a/docs/harness-v2-performance.md
+++ b/docs/harness-v2-performance.md
@@ -10,6 +10,29 @@ flutter test --no-pub --reporter expanded test/benchmarks/swarm_benchmark.dart
It prints `SWARM_BENCH` JSON records. Its filename deliberately does not end in `_test.dart`, so ordinary correctness runs do not include timing measurements.
+## Persisted settings initialization (2026-09-13)
+
+The font and appearance stores previously restored five keys with five separate file-lock, permission-check and JSON-read cycles. Each group now uses one requested-key snapshot, reducing that work to two cycles. File locking, private permissions, corrupt-file quarantine and future-schema protection remain in the same storage path. Snapshots are not cached; an intervening write is visible to the next read, including writes through another store instance. No unrelated credential keys are returned to the preference stores.
+
+The independent stats file loads alongside these groups, and `main()` starts the keyboard file/watch setup at the same time. The window still waits for all settings and keyboard configuration before becoming usable. Counters finish loading before any agent events can increment them.
+
+Run the explicit isolated benchmark from `desktop/`:
+
+```bash
+flutter test --no-pub --reporter expanded test/benchmarks/startup_benchmark.dart
+```
+
+One before/after run used 20 warmups and 100 samples for each workload. Each sample creates fresh store objects over temporary files containing five synthetic preferences, counters and, for the combined workload, a valid keyboard override with its real directory watches. Object construction is outside the timer. Filesystem caches are warm; this runs in the headless debug test runner.
+
+| Initialization workload | Before median / p95 | After median / p95 |
+| --- | ---: | ---: |
+| Font, appearance and counters | 29.505 / 32.234 ms | 12.149 / 13.468 ms |
+| Settings plus keyboard read, validation and watches | 31.877 / 34.919 ms | 13.042 / 14.295 ms |
+
+This measures one initialization step, not a cold process launch, native first-frame presentation, agent connection or input latency. No production settings were read. Logs: `/private/tmp/harness-v2-startup-benchmark-{before,after}.log`.
+
+All 58 focused startup, file-store, appearance, font, counter, palette and keyboard checks passed (`/private/tmp/harness-v2-startup-tests.log`). Startup regressions now inject every store instead of allowing appearance and stats to reach their global defaults. They cover complete restoration, empty storage, overlapping delayed loads, the readiness barrier and failed appearance reads while counters are still pending. Batch-store checks cover selected keys, an intervening write/delete, empty requests, corruption and newer schemas; existing private-file permission checks still pass.
+
## Native search field updates (2026-09-13)
The production bridge was sending the same placeholder hint back to AppKit for every native query edit. A regression observed five reverse-channel `searchState` messages for the five-query burst `w`, `wo`, `wor`, `work`, `work 木`, including interleaved catalog updates. The revised bridge sends zero for that burst and one changed hint when entering command mode. It still sends an intentional query replacement when the user invokes Search commands.
diff --git a/docs/harness-v2-progress.md b/docs/harness-v2-progress.md
index d0c0bc7b6..814c19734 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.
+## 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.
+- Independent counters and keyboard configuration load concurrently with appearance. All still finish before the window becomes usable, so saved styling and shortcuts are present at arrival and a late stats load cannot overwrite new agent events.
+- 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.
+- 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
- An isolated full-screen probe reproduced inconsistent arrival: initial launch focused the shell, while New swarm after work and close-last-swarm immediately opened suggestions over the welcome choices. All three now focus the inline field with results closed. Clicking, typing or a configured picker navigation/accept key opens results in place. The opening key never activates an unseen result. Escape keeps the query and caret; returning from the native search or a dialog does not reopen inline suggestions automatically.
@@ -10,7 +19,7 @@ Updated 2026-09-13 with coordinated palettes, Models, combined closed-work Histo
- Visual review at 880×560 covered fresh welcome, the prefilled New agent form, New swarm after work and inline results. It also caught singular machine/project labels; they now reuse the swarm agent-count formatter. These images use the Flutter fallback titlebar, not a live native capture.
- Validation: both arrival regressions and the redundant-message regression failed before their fixes. **48 focused Flutter tests plus the isolated render passed**; the final count-label reuse then passed nine search checks plus the rerender. **51 native decoder and 363 AppKit checks passed**. Analyzer has zero errors/warnings and the existing 12 vendored infos. Artifacts: `/private/tmp/harness-v2-search-arrival-{before,tests,final-tests,native,analyze,copy-render}.log`, `/private/tmp/harness-v2-search-echo-before.log`, and `/private/tmp/harness-v2-search-arrival-{welcome,form,new-swarm,search}.png`.
- Saved as local commit `72355d9`. Release build succeeded (`/private/tmp/harness-v2-search-arrival-build.log`), and the exact preview reopened as PID 26548 after PID 11785 was normally quit and confirmed exited. No real agent input, provider installation or foreground latency measurement was used. Public-origin push approval is still pending.
-- Next independent audit: startup reads before the first frame (`main.dart`, `core/startup.dart`, persisted setting stores and the keyboard config). Inspect shared-store behavior and measure isolated initialization before changing ordering. Native foreground calibration and automatic key-view traversal remain unverified; do not retry them without new access evidence.
+- The subsequent startup audit and measurements are recorded above. Native foreground calibration and automatic key-view traversal remain unverified; do not retry them without new access evidence.
## Native tab interaction checkpoint