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
feat(desktop): add validated keymap configuration core
deea49a383ec00e
diff --git a/desktop/lib/shortcuts/keymap.dart b/desktop/lib/shortcuts/keymap.dartnew file mode 100644index 000000000..1bc429c71--- /dev/null+++ b/desktop/lib/shortcuts/keymap.dart@@ -0,0 +1,385 @@+import 'dart:convert';++enum KeymapContext { workspace, terminal, picker }++/// A canonical logical key name and exact modifier set. Parsing happens on reload,+/// never on the input path. The Flutter adapter supplies the same canonical keys.+class KeyStroke {+ const KeyStroke(+ this.key, {+ this.control = false,+ this.alt = false,+ this.command = false,+ this.shift = false,+ });++ final String key;+ final bool control, alt, command, shift;++ static const _modifiers = {+ 'ctrl': 'control',+ 'control': 'control',+ 'alt': 'alt',+ 'option': 'alt',+ 'opt': 'alt',+ 'cmd': 'command',+ 'command': 'command',+ 'super': 'command',+ 'shift': 'shift',+ };+ static const _aliases = {+ 'return': 'enter',+ 'esc': 'escape',+ 'arrowleft': 'left',+ 'arrowright': 'right',+ 'arrowup': 'up',+ 'arrowdown': 'down',+ 'pgup': 'pageup',+ 'pgdn': 'pagedown',+ 'pagedn': 'pagedown',+ 'del': 'delete',+ 'backspace': 'backspace',+ ',': 'comma',+ '.': 'period',+ '/': 'slash',+ '\\': 'backslash',+ ';': 'semicolon',+ "'": 'quote',+ '`': 'backquote',+ '[': 'bracketleft',+ ']': 'bracketright',+ '-': 'minus',+ '=': 'equal',+ 'spacebar': 'space',+ };+ static const _named = {+ 'enter',+ 'escape',+ 'left',+ 'right',+ 'up',+ 'down',+ 'pageup',+ 'pagedown',+ 'home',+ 'end',+ 'delete',+ 'backspace',+ 'tab',+ 'space',+ 'comma',+ 'period',+ 'slash',+ 'backslash',+ 'semicolon',+ 'quote',+ 'backquote',+ 'bracketleft',+ 'bracketright',+ 'minus',+ 'equal',+ 'insert',+ };++ factory KeyStroke.parse(String value) {+ final parts = value.toLowerCase().split('+');+ final modifiers = <String>{};+ String? key;+ for (final part in parts) {+ final modifier = _modifiers[part];+ if (modifier != null) {+ if (!modifiers.add(modifier)) {+ throw FormatException('Repeated modifier in "$value"');+ }+ } else {+ if (key != null || part.isEmpty) {+ throw FormatException('Expected one key in "$value"');+ }+ key = _aliases[part] ?? part;+ }+ }+ if (key == null ||+ !(_named.contains(key) ||+ RegExp(r'^[a-z0-9]$').hasMatch(key) ||+ RegExp(r'^f([1-9]|1[0-9]|2[0-4])$').hasMatch(key))) {+ throw FormatException('Unknown key in "$value"');+ }+ return KeyStroke(+ key,+ control: modifiers.contains('control'),+ alt: modifiers.contains('alt'),+ command: modifiers.contains('command'),+ shift: modifiers.contains('shift'),+ );+ }++ @override+ String toString() => [+ if (control) 'ctrl',+ if (alt) 'alt',+ if (command) 'cmd',+ if (shift) 'shift',+ key,+ ].join('+');++ @override+ bool operator ==(Object other) =>+ other is KeyStroke &&+ key == other.key &&+ control == other.control &&+ alt == other.alt &&+ command == other.command &&+ shift == other.shift;++ @override+ int get hashCode => Object.hash(key, control, alt, command, shift);+}++class KeyBinding {+ KeyBinding({+ required Iterable<KeyStroke> keys,+ required this.command,+ this.context = KeymapContext.workspace,+ this.custom = false,+ }) : keys = List.unmodifiable(keys) {+ if (this.keys.isEmpty || this.keys.length > 4) {+ throw const FormatException('Use one to four keys in a sequence');+ }+ }++ final List<KeyStroke> keys;++ /// Null explicitly unbinds this sequence, including any longer descendants.+ final String? command;+ final KeymapContext context;+ final bool custom;+ String get sequence => keys.join(' ');+}++class KeymapConfig {+ const KeymapConfig.empty() : bindings = const [];+ KeymapConfig(Iterable<KeyBinding> bindings)+ : bindings = List.unmodifiable(bindings);+ final List<KeyBinding> bindings;++ factory KeymapConfig.parse(String source, {required Set<String> commands}) {+ final cleaned = _cleanJsonc(source);+ if (cleaned.trim().isEmpty) return const KeymapConfig.empty();+ final dynamic value;+ try {+ value = jsonDecode(cleaned);+ } on FormatException catch (error) {+ throw FormatException(error.message, source, error.offset);+ }+ if (value is! Map<String, dynamic>) {+ throw const FormatException('Keyboard config must be an object');+ }+ if (value.keys.any(+ (key) => !{'version', 'bindings', r'$schema'}.contains(key),+ )) {+ throw const FormatException('Unknown keyboard config property');+ }+ if ((value['version'] ?? 1) != 1) {+ throw const FormatException('Unsupported keyboard config version');+ }+ final rows = value['bindings'] ?? [];+ if (rows is! List || rows.length > 512) {+ throw const FormatException(+ 'bindings must be an array of at most 512 entries',+ );+ }+ final result = <KeyBinding>[];+ final seen = <String>{};+ for (var i = 0; i < rows.length; i++) {+ final row = rows[i];+ if (row is! Map<String, dynamic> ||+ row.keys.any((key) => !{'keys', 'command', 'when'}.contains(key)) ||+ row['keys'] is! String ||+ !row.containsKey('command')) {+ throw FormatException(+ 'bindings[$i] needs keys, command, and an optional when',+ );+ }+ final command = row['command'];+ if (command != null &&+ (command is! String || !commands.contains(command))) {+ throw FormatException('Unknown command in bindings[$i]: $command');+ }+ final scope = row['when'] ?? 'workspace';+ final contexts = KeymapContext.values.where(+ (context) => context.name == scope,+ );+ if (contexts.isEmpty) {+ throw FormatException('Unknown context in bindings[$i]: $scope');+ }+ final sequence = (row['keys'] as String).trim().replaceAll(+ RegExp(r'\s*\+\s*'),+ '+',+ );+ final binding = KeyBinding(+ keys: sequence.split(RegExp(r'\s+')).map(KeyStroke.parse),+ command: command as String?,+ context: contexts.first,+ custom: true,+ );+ if (!seen.add('${binding.context.name}:${binding.sequence}')) {+ throw FormatException(+ 'Duplicate binding: ${binding.sequence} in $scope',+ );+ }+ result.add(binding);+ }+ return KeymapConfig(result);+ }+}++class KeymapMatch {+ const KeymapMatch({this.command, this.prefix = false});+ final String? command;+ final bool prefix;+ bool get matched => command != null || prefix;+}++class _KeyNode {+ final children = <KeyStroke, _KeyNode>{};+ String? command;+}++/// Immutable lookup tables for each input context. Workspace commands are+/// inherited by a terminal; a modal picker owns its own keys.+class ResolvedKeymap {+ ResolvedKeymap(Iterable<KeyBinding> defaults, KeymapConfig config) {+ for (final context in KeymapContext.values) {+ final effective = <String, KeyBinding>{};+ void apply(Iterable<KeyBinding> entries, KeymapContext scope) {+ for (final entry in entries.where(+ (binding) => binding.context == scope,+ )) {+ if (entry.command == null) {+ effective.removeWhere(+ (key, _) =>+ key == entry.sequence || key.startsWith('${entry.sequence} '),+ );+ } else {+ effective[entry.sequence] = entry;+ }+ }+ }++ if (context == KeymapContext.terminal) {+ apply(defaults, KeymapContext.workspace);+ }+ apply(defaults, context);+ if (context == KeymapContext.terminal) {+ apply(config.bindings, KeymapContext.workspace);+ }+ apply(config.bindings, context);+ _bindings[context] = List.unmodifiable(effective.values);+ final root = _KeyNode();+ for (final entry in effective.values) {+ var node = root;+ for (final key in entry.keys) {+ if (node.command != null) _ambiguous(entry, context);+ node = node.children.putIfAbsent(key, _KeyNode.new);+ }+ if (node.children.isNotEmpty) _ambiguous(entry, context);+ node.command = entry.command;+ }+ _roots[context] = root;+ }+ }++ final _roots = <KeymapContext, _KeyNode>{};+ final _bindings = <KeymapContext, List<KeyBinding>>{};++ Never _ambiguous(KeyBinding binding, KeymapContext context) =>+ throw FormatException(+ 'Ambiguous prefix for ${binding.sequence} in ${context.name}; '+ 'unbind the shorter command before defining a sequence',+ );++ List<KeyBinding> bindingsFor(KeymapContext context) => _bindings[context]!;++ KeymapMatch match(KeymapContext context, Iterable<KeyStroke> keys) {+ var node = _roots[context]!;+ for (final key in keys) {+ final next = node.children[key];+ if (next == null) return const KeymapMatch();+ node = next;+ }+ return KeymapMatch(command: node.command, prefix: node.children.isNotEmpty);+ }+}++/// Strip comments/trailing commas without shifting JSON decoder error offsets.+/// String contents, escapes and newlines remain byte-for-byte intact.+String _cleanJsonc(String source) {+ final chars = source.codeUnits.toList();+ var inString = false;+ for (var i = 0; i < chars.length; i++) {+ final c = chars[i];+ if (inString) {+ if (c == 92) {+ i++;+ } else if (c == 34) {+ inString = false;+ }+ continue;+ }+ if (c == 34) {+ inString = true;+ continue;+ }+ if (c != 47 || i + 1 >= chars.length) continue;+ final next = chars[i + 1];+ if (next == 47) {+ while (i < chars.length && chars[i] != 10 && chars[i] != 13) {+ chars[i++] = 32;+ }+ i--;+ } else if (next == 42) {+ final start = i;+ chars[i++] = 32;+ chars[i++] = 32;+ while (i < chars.length &&+ !(chars[i] == 42 && i + 1 < chars.length && chars[i + 1] == 47)) {+ if (chars[i] != 10 && chars[i] != 13) chars[i] = 32;+ i++;+ }+ if (i + 1 >= chars.length) {+ throw FormatException('Unterminated block comment', source, start);+ }+ chars[i] = 32;+ chars[++i] = 32;+ }+ }+ inString = false;+ for (var i = 0; i < chars.length; i++) {+ if (inString) {+ if (chars[i] == 92) {+ i++;+ } else if (chars[i] == 34) {+ inString = false;+ }+ } else if (chars[i] == 34) {+ inString = true;+ } else if (chars[i] == 44) {+ var next = i + 1;+ while (next < chars.length &&+ const {9, 10, 13, 32}.contains(chars[next])) {+ next++;+ }+ var previous = i - 1;+ while (previous >= 0 && const {9, 10, 13, 32}.contains(chars[previous])) {+ previous--;+ }+ if (previous >= 0 &&+ !const {91, 123, 44, 58}.contains(chars[previous]) &&+ next < chars.length &&+ (chars[next] == 93 || chars[next] == 125)) {+ chars[i] = 32;+ }+ }+ }+ return String.fromCharCodes(chars);+}diff --git a/desktop/lib/shortcuts/keymap_store.dart b/desktop/lib/shortcuts/keymap_store.dartnew file mode 100644index 000000000..d8a56e220--- /dev/null+++ b/desktop/lib/shortcuts/keymap_store.dart@@ -0,0 +1,300 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';+import 'dart:typed_data';++import 'package:flutter/foundation.dart';+import 'package:path/path.dart' as p;++import 'keymap.dart';++/// Owns one dotfile. Invalid edits retain the last working keymap, and file+/// activity never performs work on the keyboard event path.+class KeymapStore extends ChangeNotifier {+ KeymapStore({+ required this.file,+ required Iterable<KeyBinding> defaults,+ required Set<String> commands,+ this.watchFiles = true,+ }) : _defaults = List.unmodifiable(defaults),+ _commands = Set.unmodifiable(commands) {+ current = ResolvedKeymap(_defaults, const KeymapConfig.empty());+ _signature = _describe(current);+ }++ static const maximumBytes = 128 * 1024;+ final File file;+ final bool watchFiles;+ final List<KeyBinding> _defaults;+ final Set<String> _commands;+ late ResolvedKeymap current;+ late String _signature;+ int revision = 0;+ String? _readError, _watchError;+ String? get error => _readError ?? _watchError;+ bool _disposed = false;+ int _generation = 0, _watchFailures = 0;+ final _watchers = <String, StreamSubscription<FileSystemEvent>>{};+ Set<String> _targets = {};+ Timer? _debounce;++ static String defaultPath({Map<String, String>? environment}) {+ final env = environment ?? Platform.environment;+ final xdg = env['XDG_CONFIG_HOME'];+ final home = env['HOME'] ?? env['USERPROFILE'];+ final String root;+ if (xdg != null && p.isAbsolute(xdg)) {+ root = xdg;+ } else if (home != null && home.isNotEmpty) {+ root = p.join(home, '.config');+ } else {+ throw const FileSystemException(+ 'No home directory for keyboard configuration',+ );+ }+ return p.join(root, 'harness', 'keybindings.jsonc');+ }++ Future<void> start() async {+ if (watchFiles && !_disposed) await _refreshWatches(_generation);+ await reload();+ }++ Future<void> reload({bool fromWatcher = false}) async {+ if (_disposed) return;+ if (!fromWatcher) _watchFailures = 0;+ final generation = ++_generation;+ final priorError = error;+ var changed = false;+ try {+ String source;+ try {+ final bytes = await file+ .openRead(0, maximumBytes + 1)+ .fold(+ BytesBuilder(copy: false),+ (builder, chunk) => builder..add(chunk),+ );+ if (bytes.length > maximumBytes) {+ throw const FormatException('Keyboard config exceeds 128 KiB');+ }+ source = utf8.decode(bytes.takeBytes());+ } on FileSystemException catch (error) {+ if (!const {2, 3}.contains(error.osError?.errorCode)) rethrow;+ source = ''; // A missing file inherits defaults.+ }+ final next = ResolvedKeymap(+ _defaults,+ KeymapConfig.parse(source, commands: _commands),+ );+ if (_disposed || generation != _generation) return;+ final signature = _describe(next);+ if (_signature != signature) {+ current = next;+ _signature = signature;+ revision++;+ changed = true;+ }+ _readError = null;+ } catch (failure) {+ if (_disposed || generation != _generation) return;+ _readError = 'Keyboard config: $failure';+ }+ if (!_disposed &&+ generation == _generation &&+ (changed || priorError != error)) {+ notifyListeners();+ }+ final priorWatchError = error;+ if (watchFiles && !_disposed) await _refreshWatches(generation);+ if (!_disposed && generation == _generation && priorWatchError != error) {+ notifyListeners();+ }+ }++ String _describe(ResolvedKeymap map) => [+ for (final context in KeymapContext.values)+ for (final binding in map.bindingsFor(context))+ '${context.name}:${binding.sequence}:${binding.command}:${binding.custom}',+ ].join('\n');++ Future<void> _refreshWatches(int generation) async {+ try {+ await _updateWatches(generation);+ } catch (failure) {+ if (_disposed || generation != _generation) return;+ _watchError = 'Could not watch keyboard config: $failure';+ if (++_watchFailures <= 3) {+ _scheduleReload(Duration(milliseconds: 200 * _watchFailures));+ }+ }+ }++ Future<void> _updateWatches(int generation) async {+ final targets = {p.normalize(file.absolute.path)};+ var linkPath = targets.first;+ for (var depth = 0; depth < 8; depth++) {+ try {+ if (await FileSystemEntity.type(linkPath, followLinks: false) !=+ FileSystemEntityType.link) {+ break;+ }+ final destination = await Link(linkPath).target();+ final next = p.normalize(+ p.isAbsolute(destination)+ ? destination+ : p.join(p.dirname(linkPath), destination),+ );+ if (!targets.add(next)) break;+ linkPath = next;+ } on FileSystemException {+ break;+ }+ }+ try {+ targets.add(p.normalize(await file.resolveSymbolicLinks()));+ } on FileSystemException {+ /* Missing file or target. */+ }+ final directories = <String>{};+ for (final target in targets.toList()) {+ var directory = Directory(p.dirname(target));+ final original = directory.path;+ while (!await directory.exists()) {+ final parent = directory.parent;+ if (parent.path == directory.path) break;+ directory = parent;+ }+ // Observe creation of missing config directories without watching an+ // entire filesystem root. No recursive subscriptions are needed.+ if (directory.parent.path != directory.path) {+ final canonical = await directory.resolveSymbolicLinks();+ targets.add(+ p.normalize(+ p.join(canonical, p.relative(target, from: directory.path)),+ ),+ );+ directories.add(canonical);+ }+ if (directory.path == original &&+ directory.parent.parent.path != directory.parent.path) {+ directories.add(await directory.parent.resolveSymbolicLinks());+ }+ }+ if (_disposed || generation != _generation) return;+ _targets = targets;+ for (final path+ in _watchers.keys+ .where((path) => !directories.contains(path))+ .toList()) {+ unawaited(_watchers.remove(path)!.cancel());+ }+ _watchError = directories.isEmpty+ ? 'Create the keyboard config directory to enable automatic reload.'+ : null;+ for (final path in directories) {+ if (_watchers.containsKey(path)) continue;+ late StreamSubscription<FileSystemEvent> subscription;+ void lost(Object? failure) {+ if (_disposed || _watchers[path] != subscription) return;+ _watchers.remove(path);+ unawaited(subscription.cancel());+ _watchError =+ 'Keyboard config watch stopped. Reload to retry${failure == null ? '.' : ': $failure'}';+ notifyListeners();+ if (++_watchFailures <= 3) {+ _scheduleReload(Duration(milliseconds: 200 * _watchFailures));+ }+ }++ try {+ subscription = Directory(path).watch().listen(+ (event) {+ if (_related(event.path) ||+ event is FileSystemMoveEvent &&+ event.destination != null &&+ _related(event.destination!)) {+ if (event.isDirectory) {+ final changed = p.normalize(p.absolute(event.path));+ for (final watched+ in _watchers.keys+ .where(+ (path) =>+ path == changed || p.isWithin(changed, path),+ )+ .toList()) {+ unawaited(_watchers.remove(watched)!.cancel());+ }+ }+ _watchFailures = 0;+ _scheduleReload(const Duration(milliseconds: 80));+ }+ },+ onError: (Object failure) => lost(failure),+ onDone: () => lost(null),+ cancelOnError: true,+ );+ _watchers[path] = subscription;+ } catch (failure) {+ _watchError = 'Could not watch keyboard config: $failure';+ }+ }+ }++ bool _related(String path) {+ final normalized = p.normalize(p.absolute(path));+ return _targets.any(+ (target) => target == normalized || p.isWithin(normalized, target),+ );+ }++ void _scheduleReload(Duration delay) {+ if (_disposed) return;+ _debounce?.cancel();+ _debounce = Timer(delay, () {+ _debounce = null;+ unawaited(reload(fromWatcher: true));+ });+ }++ /// Invoked only by the explicit Open Keyboard Config action. Starting the+ /// app never creates a dotfile or rewrites existing user configuration.+ Future<File> ensureFile() async {+ await file.parent.create(recursive: true);+ final handle = await file.open(mode: FileMode.append);+ try {+ await handle.lock(FileLock.exclusive);+ if (await handle.length() == 0) {+ await handle.writeString(+ '''// Harness keyboard overrides. Defaults are inherited.+// Use command names from Keyboard Shortcuts / the command picker.+// A null command unbinds a key or a sequence prefix.+{+ "version": 1,+ "bindings": [+ // { "keys": "cmd+ctrl+h", "command": "pane.focus_left", "when": "terminal" },+ ],+}+''',+ );+ await handle.flush();+ }+ } finally {+ await handle.close();+ }+ await reload();+ return file;+ }++ @override+ void dispose() {+ _disposed = true;+ _generation++;+ _debounce?.cancel();+ for (final watcher in _watchers.values) {+ unawaited(watcher.cancel());+ }+ _watchers.clear();+ super.dispose();+ }+}diff --git a/desktop/test/keymap_store_test.dart b/desktop/test/keymap_store_test.dartnew file mode 100644index 000000000..e74809cf0--- /dev/null+++ b/desktop/test/keymap_store_test.dart@@ -0,0 +1,212 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shortcuts/keymap.dart';+import 'package:harness/shortcuts/keymap_store.dart';++String config(String command) => jsonEncode({+ 'bindings': [+ {'keys': 'cmd+p', 'command': command},+ ],+});+KeymapStore storeFor(File file, {bool watch = false}) => KeymapStore(+ file: file,+ watchFiles: watch,+ defaults: [+ KeyBinding(+ keys: [KeyStroke.parse('cmd+p')],+ command: 'navigation.quick_open',+ ),+ ],+ commands: {'navigation.quick_open', 'pane.focus_left'},+);+String? selected(KeymapStore store) => store.current.match(+ KeymapContext.terminal,+ [KeyStroke.parse('cmd+p')],+).command;++Future<void> eventually(bool Function() condition) async {+ final until = DateTime.now().add(const Duration(seconds: 5));+ while (!condition()) {+ if (DateTime.now().isAfter(until)) {+ fail('Directory watch did not publish the expected keymap');+ }+ await Future<void>.delayed(const Duration(milliseconds: 20));+ }+}++class _ControlledFile extends Fake implements File {+ final reads = <StreamController<List<int>>>[];+ @override+ Stream<List<int>> openRead([int? start, int? end]) {+ final controller = StreamController<List<int>>();+ reads.add(controller);+ return controller.stream;+ }+}++void main() {+ late Directory directory;+ setUp(() async {+ directory = await Directory.systemTemp.createTemp('harness-keymap-test-');+ });+ tearDown(() async {+ await directory.delete(recursive: true);+ });++ test('missing file uses defaults without creating a user config', () async {+ final file = File('${directory.path}/config/keybindings.jsonc');+ final store = storeFor(file);+ addTearDown(store.dispose);+ await store.start();+ expect(selected(store), 'navigation.quick_open');+ expect(store.error, isNull);+ expect(await file.parent.exists(), false);+ expect(store.revision, 0);+ });++ test(+ 'invalid edit retains working bindings; repair and removal recover',+ () async {+ final file = File('${directory.path}/keybindings.jsonc');+ final store = storeFor(file);+ addTearDown(store.dispose);+ var changes = 0;+ store.addListener(() => changes++);+ await file.writeAsString(config('pane.focus_left'));+ await store.start();+ expect(selected(store), 'pane.focus_left');+ final good = store.current;+ final revision = store.revision;+ await file.writeAsString('{');+ await store.reload();+ expect(store.current, same(good));+ expect(store.revision, revision);+ expect(store.error, contains('FormatException'));+ await file.writeAsString(+ '// comments only change\n${config('pane.focus_left')}',+ );+ await store.reload();+ expect(store.current, same(good));+ expect(store.error, isNull);+ expect(changes, 3); // New map, diagnostic, diagnostic cleared.+ await file.delete();+ await store.reload();+ expect(selected(store), 'navigation.quick_open');+ },+ );++ test('a slower old read cannot overwrite a newer map or error', () async {+ final file = _ControlledFile();+ final store = storeFor(file);+ addTearDown(store.dispose);+ final first = store.reload();+ final second = store.reload();+ file.reads[1].add(utf8.encode(config('pane.focus_left')));+ await file.reads[1].close();+ await second;+ file.reads[0].add(utf8.encode('{'));+ await file.reads[0].close();+ await first;+ expect(selected(store), 'pane.focus_left');+ expect(store.error, isNull);+ });++ test('oversized and malformed UTF-8 files retain the current map', () async {+ final file = File('${directory.path}/keybindings.jsonc');+ final store = storeFor(file);+ addTearDown(store.dispose);+ await store.start();+ final good = store.current;+ await file.writeAsBytes(List.filled(KeymapStore.maximumBytes + 1, 32));+ await store.reload();+ expect(store.error, contains('128 KiB'));+ expect(store.current, same(good));+ await file.writeAsBytes([0xff]);+ await store.reload();+ expect(store.error, isNotNull);+ expect(store.current, same(good));+ });++ test(+ 'explicit open creates a template and preserves existing file contents',+ () async {+ final file = File('${directory.path}/config/keybindings.jsonc');+ final store = storeFor(file);+ addTearDown(store.dispose);+ await store.ensureFile();+ expect(await file.readAsString(), contains('Defaults are inherited'));+ final customized = config('pane.focus_left');+ await file.writeAsString(customized);+ await store.ensureFile();+ expect(await file.readAsString(), customized);+ expect(selected(store), 'pane.focus_left');+ },+ );++ test(+ 'watch discovers a new directory and an editor atomic replacement',+ () async {+ final file = File('${directory.path}/config/keybindings.jsonc');+ final store = storeFor(file, watch: true);+ addTearDown(store.dispose);+ await store.start();+ await file.parent.create();+ await file.writeAsString(config('pane.focus_left'));+ await eventually(() => selected(store) == 'pane.focus_left');+ final replacement = File('${file.path}.save');+ await replacement.writeAsString(config('navigation.quick_open'));+ await replacement.rename(file.path);+ await eventually(() => selected(store) == 'navigation.quick_open');+ expect(store.error, isNull);+ },+ );++ test(+ 'watch follows a dotfiles symlink and its replacement target',+ () async {+ final first = File('${directory.path}/repo1/keys.jsonc');+ final second = File('${directory.path}/repo2/keys.jsonc');+ await first.parent.create();+ await second.parent.create();+ await first.writeAsString(config('navigation.quick_open'));+ await second.writeAsString(config('pane.focus_left'));+ final link = Link('${directory.path}/app/keybindings.jsonc');+ await Directory('${directory.path}/app').create();+ await link.create(first.path);+ final store = storeFor(File(link.path), watch: true);+ addTearDown(store.dispose);+ await store.start();+ await link.update(second.path);+ await eventually(() => selected(store) == 'pane.focus_left');+ final replacement = File('${second.path}.save');+ await replacement.writeAsString(config('navigation.quick_open'));+ await replacement.rename(second.path);+ await eventually(() => selected(store) == 'navigation.quick_open');+ },+ skip: Platform.isWindows+ ? 'Creating Windows symlinks requires host permission'+ : false,+ );++ test('configuration path follows XDG and rejects a relative XDG root', () {+ expect(+ KeymapStore.defaultPath(environment: {'HOME': '/users/dev'}),+ '/users/dev/.config/harness/keybindings.jsonc',+ );+ expect(+ KeymapStore.defaultPath(+ environment: {'HOME': '/users/dev', 'XDG_CONFIG_HOME': '/dotfiles'},+ ),+ '/dotfiles/harness/keybindings.jsonc',+ );+ expect(+ KeymapStore.defaultPath(+ environment: {'HOME': '/users/dev', 'XDG_CONFIG_HOME': 'relative'},+ ),+ '/users/dev/.config/harness/keybindings.jsonc',+ );+ });+}diff --git a/desktop/test/keymap_test.dart b/desktop/test/keymap_test.dartnew file mode 100644index 000000000..241002bb6--- /dev/null+++ b/desktop/test/keymap_test.dart@@ -0,0 +1,172 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shortcuts/keymap.dart';++const commands = {'navigation.quick_open', 'pane.focus_left', 'picker.next'};+KeyBinding bind(+ String keys,+ String? command, [+ KeymapContext context = KeymapContext.workspace,+]) => KeyBinding(+ keys: keys.split(' ').map(KeyStroke.parse),+ command: command,+ context: context,+);+KeymapMatch match(+ ResolvedKeymap map,+ String keys, [+ KeymapContext context = KeymapContext.terminal,+]) => map.match(context, keys.split(' ').map(KeyStroke.parse));++void main() {+ test('dotfile accepts comments, aliases and trailing commas', () {+ final config = KeymapConfig.parse('''+ // Keep the defaults and add my preferred movement key.+ {+ "version": 1,+ "bindings": [+ {"keys": "SUPER + CONTROL + H", "command": "pane.focus_left", "when": "terminal"},+ /* Leave this chord to my terminal. */+ {"keys": "cmd+alt+left", "command": null},+ ],+ }+ ''', commands: commands);+ final map = ResolvedKeymap([+ bind('cmd+alt+left', 'pane.focus_left'),+ ], config);+ expect(match(map, 'cmd+ctrl+h').command, 'pane.focus_left');+ expect(match(map, 'cmd+alt+left').matched, false);+ expect(match(map, 'cmd+ctrl+h', KeymapContext.workspace).matched, false);+ });++ test('string escapes and comment-like strings retain their exact value', () {+ const command = 'url://a"/*b*/';+ final config = KeymapConfig.parse(+ r'{"bindings":[{"keys":"cmd+p","command":"url://a\"/*b*/"}]}',+ commands: {command},+ );+ expect(config.bindings.single.command, command);+ });++ test('invalid edits are rejected with actionable diagnostics', () {+ for (final source in [+ '{"version":2}',+ '{"binding":[]}',+ '{"bindings":[{"keys":"cmd+p","command":"unknown"}]}',+ '{"bindings":[{"keys":"cmd+p"}]}',+ '{"bindings":[{"keys":"cmd+p","command":null,"when":"typo"}]}',+ '{"bindings":[{"keys":"cmd+cmd+p","command":null}]}',+ '{"bindings":[{"keys":"cmd","command":null}]}',+ '{"bindings":[{"keys":"made-up","command":null}]}',+ '{"bindings":[{"keys":"a b c d e","command":null}]}',+ '{"bindings":[{"keys":"cmd+p","command":null},{"keys":"super+p","command":null}]}',+ '{"bindings":[,]}',+ '{,}',+ '/* unfinished',+ ]) {+ expect(+ () => KeymapConfig.parse(source, commands: commands),+ throwsFormatException,+ reason: source,+ );+ }+ });++ test('decoder offsets still point into the original commented file', () {+ const source = '/* comment */\n{"bindings": ?}';+ try {+ KeymapConfig.parse(source, commands: commands);+ fail('Expected syntax error');+ } on FormatException catch (error) {+ expect(error.offset, source.indexOf('?'));+ }+ });++ test('terminal overrides do not change workspace or modal picker keys', () {+ final map = ResolvedKeymap([+ bind('cmd+p', 'navigation.quick_open'),+ bind('ctrl+n', 'picker.next', KeymapContext.picker),+ ], KeymapConfig([bind('cmd+p', null, KeymapContext.terminal)]));+ expect(match(map, 'cmd+p').matched, false);+ expect(+ match(map, 'cmd+p', KeymapContext.workspace).command,+ 'navigation.quick_open',+ );+ expect(match(map, 'cmd+p', KeymapContext.picker).matched, false);+ expect(match(map, 'ctrl+n', KeymapContext.picker).command, 'picker.next');+ expect(match(map, 'ctrl+n', KeymapContext.terminal).matched, false);+ });++ test('explicit workspace overrides also replace terminal defaults', () {+ final map = ResolvedKeymap([+ bind('cmd+p', 'navigation.quick_open'),+ bind('cmd+p', 'pane.focus_left', KeymapContext.terminal),+ ], KeymapConfig([bind('cmd+p', null)]));+ expect(match(map, 'cmd+p').matched, false);+ });++ test('sequences need explicit removal of an ambiguous shorter binding', () {+ final defaults = [bind('cmd+p', 'navigation.quick_open')];+ final sequence = bind('cmd+p h', 'pane.focus_left');+ expect(+ () => ResolvedKeymap(defaults, KeymapConfig([sequence])),+ throwsFormatException,+ );+ final map = ResolvedKeymap(+ defaults,+ KeymapConfig([bind('cmd+p', null), sequence]),+ );+ expect(match(map, 'cmd+p').prefix, true);+ expect(match(map, 'cmd+p').command, null);+ expect(match(map, 'cmd+p h').command, 'pane.focus_left');+ expect(match(map, 'cmd+p l').matched, false);+ expect(match(map, 'cmd+p h j').matched, false);+ });++ test(+ 'prefix ambiguity is rejected in both insertion orders and across scopes',+ () {+ expect(+ () => ResolvedKeymap([+ bind('cmd+p h', 'pane.focus_left'),+ bind('cmd+p', 'navigation.quick_open'),+ ], const KeymapConfig.empty()),+ throwsFormatException,+ );+ expect(+ () => ResolvedKeymap([+ bind('cmd+p h', 'pane.focus_left', KeymapContext.terminal),+ ], KeymapConfig([bind('cmd+p', 'navigation.quick_open')])),+ throwsFormatException,+ );+ },+ );++ test('unbinding a prefix releases its entire inherited sequence tree', () {+ final map = ResolvedKeymap([+ bind('cmd+p h', 'pane.focus_left'),+ bind('cmd+p p', 'navigation.quick_open'),+ ], KeymapConfig([bind('cmd+p', null)]));+ expect(match(map, 'cmd+p').matched, false);+ expect(match(map, 'cmd+p h').matched, false);+ });++ test(+ 'oversized binding lists and unknown fields fail instead of being ignored',+ () {+ expect(+ () => KeymapConfig.parse(+ '{"bindings":[${List.filled(513, '{}').join(',')}]}',+ commands: commands,+ ),+ throwsFormatException,+ );+ expect(+ () => KeymapConfig.parse(+ '{"bindings":[{"keys":"cmd+p","command":null,"scope":"terminal"}]}',+ commands: commands,+ ),+ throwsFormatException,+ );+ },+ );+}diff --git a/docs/harness-v2-developer-tools-research.md b/docs/harness-v2-developer-tools-research.mdindex 0eff3de0c..13a0fca57 100644--- a/docs/harness-v2-developer-tools-research.md+++ b/docs/harness-v2-developer-tools-research.md@@ -15,9 +15,11 @@ Updated 2026-09-13. This is the working list; [the progress log](harness-v2-prog| In the preview | Real machine/project data; native Swarm tabs; wallpaper only in New swarm; Cmd+P jump, Needs input and terminal Find. || Fixed and rebuilt | Cmd+P stale focus/offscreen targets; retained offline output and composer drafts; blocking frozen overlays removed. || In the rebuilt preview | Settings gear removed on macOS; native File/History menus and Cmd+P routing. Menus and picker typing verified live; focus/input regression tests pass. |-| Rebuilt and reviewed live | Chrome-style Back/Forward, Recently Closed/Visited and full session History; compact branch-aware headers; wallpaper control moved to View/context menus; Workshop now includes its requested iMac Home agent. |+| Rebuilt and reviewed live | Chrome-style Back/Forward, Recently Closed/Visited and full session History; compact branch-aware headers; Workshop now includes its requested iMac Home agent. || In the rebuilt preview; regression verified | Preserve the session, terminal view, Find, viewport, selection and draft context through reconnect/keyframe replacement. Stale output/input/upload completions cannot affect the replacement stream. A real remote interruption remains to be validated. |-| Next | Live keyboard/tab/drag review and native input-to-display measurements under output load. |+| Rebuilt; live search/project review passed | One top-right Cmd-P search for agents, Swarms, machines and projects, with Focus/Open and explicit Add here actions; machine/project browsing and explicit group opening. Separate Add picker, floating pane + and titlebar bell removed. New swarm uses only the selected mountain/lake wallpaper; rotation and other assets removed. A group-click focus correction passes isolated tests; its final native Escape check is pending because the user resumed using the preview. |+| In progress | [Audit all shortcuts and implement a coherent terminal-friendly key system with file-first remapping](harness-v2-keyboard-system.md). Config parser/resolver and live reload core pass isolated tests. Apart from the unified search change, new defaults remain proposed until dispatch, native menus and help are integrated and verified. |+| Calibration in progress; foreground runs paused | Native Release input/navigation fixture with synthetic terminals. No validated latency result yet; resume after the keyboard work stabilizes. Live keyboard/tab/drag and real remote interruption checks remain. || Next small addition | Optional cached preview and match highlighting in the existing Cmd+P picker. [The six-prototype review](harness-v2-prototype-review.md) records what to borrow and what stays out. || Keep deferred | Workflow canvases, autonomous manager layers, a full IDE/Git client and a marketplace. |diff --git a/docs/harness-v2-keyboard-system.md b/docs/harness-v2-keyboard-system.mdnew file mode 100644index 000000000..2a25edc2a--- /dev/null+++ b/docs/harness-v2-keyboard-system.md@@ -0,0 +1,77 @@+# A coherent keyboard system for Harness++Research and complete default-binding audit: 2026-09-13. **Most defaults and file remapping below remain an implementation plan.** The current search change consolidates the old Cmd-P and Cmd-Shift-F experiences under Cmd-P, with an explicit Add action inside the picker. The parser/resolver and file reload core have isolated tests but are not connected to production dispatch yet. The [working queue](harness-v2-developer-tools-research.md) remains the status list.++## Principles from the tools++There is no universal expert keymap. These tools disagree about particular combinations; their useful common ground is stable commands, predictable scope, configurable bindings, and preserving the program inside the terminal.++| Primary source | Relevant behavior | Harness decision |+| --- | --- | --- |+| [Vim window commands](https://github.com/vim/vim/blob/master/runtime/doc/windows.txt) | Ctrl-W introduces window commands; h/j/k/l focus directions, while capitals move windows to edges. | Preserve these bytes inside Vim. Make focus and rearrangement distinct commands. A shifted Harness movement binding is an analogy, not identical Vim layout semantics. |+| [GNU Emacs reference](https://www.gnu.org/software/emacs/refcards/pdf/refcard.pdf) | Control and Meta are used extensively; Ctrl-X introduces commands, Ctrl-N/P move by line, and Ctrl-G cancels. | Preserve terminal Control/Meta input. Borrow Ctrl-N/P and Ctrl-G only inside Harness-owned pickers. |+| [tmux getting started](https://github.com/tmux/tmux/wiki/Getting-Started) | Prefix commands operate on persistent sessions, windows and panes. The default Ctrl-B prefix includes navigation, splitting, zoom, last-pane and command selection. | Keep the session/view distinction and reversible navigation. Do not intercept the inner tmux prefix by default. |+| [Zsh line editor](https://zsh.sourceforge.io/Doc/Release/Zsh-Line-Editor.html) | Explicit keymaps support Emacs and vi editing, and bindkey customizes widgets and sequences. | Respect the user's shell keymap; do not try to infer or replace its editing mode. |+| [fzf shell integration](https://github.com/junegunn/fzf#key-bindings-for-command-line) and [binding defaults](https://github.com/junegunn/fzf/blob/master/man/man1/fzf.1) | Incremental narrowing, configurable actions, arrow/Ctrl-N/P navigation and cancellation. Shell integration uses Ctrl-R, Ctrl-T and Alt-C. | Keep these shell keys available. Use one picker and shared picker navigation; plain letters continue entering the query. |+| [VS Code shortcuts](https://code.visualstudio.com/shortcuts/keyboard-shortcuts-macos.pdf) and [configuration](https://code.visualstudio.com/docs/configure/keybindings) | Quick Open is Cmd-P; commands are Cmd-Shift-P. Bindings have command identities, optional contexts, overrides and sequences. JSON and the visual editor configure the same system. | Keep Quick Open, add a small command mode backed by the existing actions, and make a text file the first customization interface. |+| [iTerm2 split panes](https://iterm2.com/documentation-one-page.html#split-panes) and [Ghostty actions](https://ghostty.org/docs/config/keybind/reference) | Directional split focus, reversible pane zoom and explicit split creation are first-class terminal operations. iTerm2 uses Cmd-Option-arrows for focus and Cmd-Shift-Enter for pane zoom. | Use that focus/zoom family. Reserve Cmd-D / Cmd-Shift-D for explicit splits when the layout feature exists. |+| [kitty configuration](https://sw.kovidgoyal.net/kitty/conf/#keyboard-shortcuts) | Tabs, inner windows, command navigation and configurable key mappings are separate concepts. Its defaults demonstrate that even terminal apps disagree on numeric navigation. | Choose and document Harness's object model consistently instead of mixing each app's defaults. |+| [Chrome shortcuts](https://support.google.com/chrome/answer/157179?hl=en) and [Mac conventions](https://support.apple.com/en-us/102650) | Familiar tab lifecycle, tab selection, back/forward, Find, and standard app commands. | Swarms are tabs. Keep that lifecycle familiar and restore standard Mac commands that current Harness bindings displaced. |++These references establish behavior, not a claim that every developer uses or prefers it. Control/Meta compatibility still needs exact input tests and native checks, including IME and modified-key encoding.++## Audit and proposed defaults++The current source is `desktop/lib/shortcuts/app_shortcuts.dart`, the Swarm screen's handlers, native menus in `SwarmTitlebar.swift` and `MainMenu.xib`, the terminal's handlers and the picker implementations. The legacy workspace and debug-only bindings were reviewed too.++The proposed macOS family is **Command for Swarms and common app actions; Command-Option for individual panes**. Shift reverses traversal or modifies a related action where that is already familiar. Terminal applications keep Control/Meta, ordinary keys, Escape and Tab by default. The app owns navigation keys inside its own picker.++| Action | Current binding | Proposed decision |+| --- | --- | --- |+| Quick Open / jump | Cmd-P | Keep. Return focuses an existing destination or explicitly opens an unviewed agent. |+| Add an existing agent here | Cmd-Shift-F, separate picker | Consolidated into Cmd-P by the user's latest decision. Return focuses an existing pane or opens its first view here. A visible Add to this swarm action (Cmd-Enter inside the picker) adds a shared view here. No separate default launcher, including Cmd-O. |+| Search app commands | None; Cmd-Shift-P pins | Cmd-Shift-P, reusing the picker with command mode. |+| New agent | Cmd-N; menu omits its shortcut | Keep and make menu/help agree. |+| New / close / reopen Swarm | Cmd-T / Cmd-W / Cmd-Shift-T | Keep. Closing a view does not end an agent. |+| Next / previous Swarm | Cmd-Shift-] / Cmd-Shift-[, plus Ctrl-Tab pair | Keep Command brackets; release the Control pair to terminal programs by default. Users can assign it explicitly. |+| Direct numeric selection | Cmd-1…9 focuses panes | Cmd-1…8 selects Swarm tabs; Cmd-9 selects the last tab. Cmd-Option-1…9 focuses pane positions. This is a deliberate default change to match the tab object model. |+| Back / forward | Cmd-[ / Cmd-] | Keep navigation history. |+| Full session history | Cmd-Y | Keep. |+| Directional pane focus | Cmd-arrows and Cmd-h/j/k/l | Cmd-Option-arrows. Vim-style letters are user mappings; Cmd-Option-H itself conflicts with native Hide Others and is not a safe default alias. |+| Rearrange pane | Cmd-Shift-arrows and Cmd-Shift-h/j/k/l | Cmd-Option-Shift-arrows, with distinct command IDs. |+| Zoom pane / restore | Cmd-Enter | Cmd-Shift-Enter, following established terminal apps. |+| Close pane view | Cmd-Shift-W | Cmd-Option-W. Keep normal window closing separate. |+| Last pane | Cmd-; | Retain as a searchable command. Quick Open / Return and history already support the common return loop. |+| Pin pane | Cmd-Shift-P | Retain as a searchable/context command; release Command Palette's familiar shortcut. |+| Choose layout | Cmd-S | Retain in View/commands; release Save's familiar shortcut. |+| Rename Swarm | Cmd-Shift-R | Retain in tab context menu and commands; avoid a surprising use of the reload family. |+| Needs input | Cmd-Shift-I | Keep: I identifies input, and this is an agent-specific action. |+| Find / next / previous | Cmd-F / Cmd-G / Cmd-Shift-G | Keep in the current terminal. |+| Refresh machines/agents | Cmd-R | Keep with an accurate label and explicit semantics; never reinterpret Ctrl-R history search. |+| Task routing | Cmd-B | Remove its default binding. Existing explicit/hardware entry points are a separate capability decision. |+| Settings / shortcuts help | Cmd-, / Cmd-/ | Keep and show effective configured bindings. |+| Debug inspector | Cmd-D in developer builds | Use a secondary inspector command; release split creation's familiar key. |+| Legacy sidebar toggle | Cmd-backslash, absent from Swarms | Keep absent from the active Swarm keymap. |+| Copy / paste / select all / undo / redo | Standard Mac keys through native/Flutter owners | Preserve. Audit actual event ownership, not just labels; native menu equivalents must not swallow the terminal's action. |+| Hide / Hide Others / minimize / quit / full screen | Hide's Cmd-H removed; other native defaults present | Restore Cmd-H. Preserve native app/window conventions and avoid assigning the same chord elsewhere. |+| Picker movement / acceptance / cancellation | Arrows, Ctrl-N/P, Return, Escape | The unified picker also accepts Ctrl-J/K and Ctrl-G. Return browses a machine/project or activates a destination; group opening is an explicit button. A composing-text guard has an isolated check; native IME behavior still needs validation. No global plain-letter Vim navigation in a search field. |++Do not advertise unimplemented splitting, global transcript search, terminal scrolling, or arbitrary remapping as working. Freeing a key does not by itself implement its expected action.++## File-first customization++Use one declarative, versioned text configuration, with sensible defaults inherited automatically. Proposed location: `$XDG_CONFIG_HOME/harness/keybindings.jsonc`, defaulting to `~/.config/harness/keybindings.jsonc`. Keep it separate from credentials and session state. JSON with comments follows the editor workflow without introducing an executable configuration language.++The app provides **Open Keyboard Config…**, effective bindings in help and menus, and automatic reload. A full visual keybinding editor is deferred; any future editor should modify the same file. Reading a missing config uses defaults and does not create files. Opening the config explicitly can create a small commented template.++The engine needs stable command IDs; aliases for modifier/key names; individual overrides; explicit unbinding; scoped bindings; and user-defined sequences. It should validate unknown commands, malformed keys, duplicate/ambiguous prefixes and conflicting native owners. Invalid reloads retain the last good map and report a useful error. Watch the containing directory so editor atomic-save replacement is supported, with bounded reload work and no polling per keystroke.++Resolve bindings when config or context changes. Ordinary input should perform a bounded lookup, with no disk, network or parsing work. Sequence handling must be explicit and cancelable; never introduce a delay to disambiguate a default single-key command, or replay an unsuccessful prefix into a real agent. Unbinding restores the normal terminal/platform route; what bytes a modified key can represent depends on the terminal protocol.++## Implementation and verification order++1. Build the command/config model, parser, validation and temporary-file reload tests. Keep current production defaults intact until dispatch and menu integration are ready.+2. Apply the coherent defaults and integrate one runtime resolver with native menus, the command/agent picker, help, tooltips and focused-terminal dispatch. Handle app, terminal and picker context explicitly.+3. Verify Control/Meta passthrough, exact key destinations, custom bindings, unbinding, sequences, modal/IME behavior and reload during active use with isolated sessions. Check all native menu equivalents against the same resolved definitions.+4. Rebuild/relaunch the authorized V2 preview, review the menus/help and navigation without typing tests into real agents, and publish the reviewed `app-v2` changes.+5. Resume native performance measurement after the keyboard work stabilizes. The isolated benchmark is currently calibration work, not a validated performance result. Foreground measurement is paused while the user is actively discussing the key system.