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
fix(mobile): a locked state file no longer stops a machine reconnecting for good
deeaefabdd4268d
diff --git a/mobile/lib/viewer/viewer_key_store.dart b/mobile/lib/viewer/viewer_key_store.dartindex a7303731f..317d4f527 100644--- a/mobile/lib/viewer/viewer_key_store.dart+++ b/mobile/lib/viewer/viewer_key_store.dart@@ -1,3 +1,4 @@+import 'dart:async';import 'dart:convert';import 'dart:typed_data';@@ -78,7 +79,12 @@ class ViewerKeyStore {static const _peersKey = 'viewer_e2ee_machine_peers';/// Minted on first use and kept: every linked machine has pinned it.- Future<E2eeIdentity> identity() => _identity ??= _loadOrMintIdentity();+ Future<E2eeIdentity> identity() => _identity ??= _heldUnlessItFails(+ _loadOrMintIdentity(),+ forget: (failed) {+ if (identical(_identity, failed)) _identity = null;+ },+ );Future<E2eeIdentity> _loadOrMintIdentity() async {final stored = await _storage.read(_seedKey);@@ -89,7 +95,30 @@ class ViewerKeyStore {}/// Newest link first. Read once and held — see [_peers].- Future<List<MachinePeer>> peers() => _peers ??= _readPeers();+ Future<List<MachinePeer>> peers() => _peers ??= _heldUnlessItFails(+ _readPeers(),+ forget: (failed) {+ if (identical(_peers, failed)) _peers = null;+ },+ );++ /// [pending], to be held as the answer — unless it fails, in which case it is let go of.+ ///+ /// ⚠️ **A failed read is not an answer.** The store throws when the state file is locked or+ /// caught mid-rename, and both reads held here are on the dial path (`viewerRelayCodecs` asks+ /// before every connect and reconnect). Held, that one rejected future was handed to every dial+ /// after it for the life of the process: a machine that met a locked file once never connected+ /// again until the app was killed — the very failure `WsConn.connect` keeps retryable on purpose.+ static Future<T> _heldUnlessItFails<T>(+ Future<T> pending, {+ required void Function(Future<T> failed) forget,+ }) {+ // A listener of its own, so the caller still sees the failure and nothing goes unhandled.+ unawaited(+ pending.then<void>((_) {}, onError: (Object _) => forget(pending)),+ );+ return pending;+ }Future<List<MachinePeer>> _readPeers() async {final raw = await _storage.read(_peersKey);@@ -128,7 +157,9 @@ class ViewerKeyStore {/// False when [machineId] was not linked.Future<bool> unlink(String machineId) async {final current = await peers();- final remaining = current.where((peer) => peer.machineId != machineId).toList();+ final remaining = current+ .where((peer) => peer.machineId != machineId)+ .toList();if (remaining.length == current.length) return false;await _write(remaining);return true;@@ -149,8 +180,7 @@ class ViewerKeyStore {_peersKey,jsonEncode([for (final peer in peers) peer.toJson()]),);- final sorted = [...peers]- ..sort((a, b) => b.linkedAt.compareTo(a.linkedAt));+ final sorted = [...peers]..sort((a, b) => b.linkedAt.compareTo(a.linkedAt));_peers = Future.value(sorted);}}diff --git a/mobile/test/viewer/viewer_key_store_test.dart b/mobile/test/viewer/viewer_key_store_test.dartnew file mode 100644index 000000000..d7826d72b--- /dev/null+++ b/mobile/test/viewer/viewer_key_store_test.dart@@ -0,0 +1,180 @@+import 'dart:convert';++import 'package:flutter_test/flutter_test.dart';++import 'package:harness_mobile/core/local_key_value_store.dart';+import 'package:harness_mobile/e2ee/bytes.dart';+import 'package:harness_mobile/viewer/viewer_key_store.dart';++import '../voice_fakes.dart' show MemoryKeyValueStore;++/// A state file that can be briefly unreadable or unwritable — locked by another process, or+/// caught mid-rename — the way `HarnessFileStore` throws rather than answers.+class _FlakyStore implements LocalKeyValueStore {+ final values = <String, String>{};+ int failReads = 0;+ int failWrites = 0;+ int reads = 0;++ @override+ Future<String?> read(String key) async {+ reads++;+ if (failReads > 0) {+ failReads--;+ throw StateError('state.json is locked');+ }+ return values[key];+ }++ @override+ Future<void> write(String key, String value) async {+ if (failWrites > 0) {+ failWrites--;+ throw StateError('disk full');+ }+ values[key] = value;+ }++ @override+ Future<void> delete(String key) async => values.remove(key);+}++const _peersKey = 'viewer_e2ee_machine_peers';+const _seedKey = 'viewer_e2ee_identity_seed';++void main() {+ group('identity', () {+ test('is minted once, kept, and the same on the next launch', () async {+ final storage = MemoryKeyValueStore();+ final first = await ViewerKeyStore(storage: storage).identity();+ expect(storage.values[_seedKey], b64e(first.seed));++ final store = ViewerKeyStore(storage: storage);+ final again = await store.identity();+ expect(again.pub, first.pub);+ expect(identical(await store.identity(), again), isTrue);+ });++ // ⚠️ A failed read used to be held as the answer for the life of the process: every dial+ // asks for the identity, so one locked moment at launch meant no machine connected again+ // until the app was killed.+ test('a read that failed once is asked again, not held', () async {+ final storage = _FlakyStore()..failReads = 1;+ final store = ViewerKeyStore(storage: storage);+ await expectLater(store.identity(), throwsStateError);+ final identity = await store.identity();+ expect(identity.pub, hasLength(32));+ });+ });++ group('peers', () {+ test('none linked is an empty list', () async {+ final store = ViewerKeyStore(storage: MemoryKeyValueStore());+ expect(await store.peers(), isEmpty);+ expect(await store.peer('m'), isNull);+ });++ test('pinning keeps the newest first and replaces a re-link', () async {+ final storage = MemoryKeyValueStore();+ final store = ViewerKeyStore(storage: storage);+ await store.pin('a', List.filled(32, 1));+ await Future<void>.delayed(const Duration(milliseconds: 2));+ await store.pin('b', List.filled(32, 2), label: 'Mac');+ await Future<void>.delayed(const Duration(milliseconds: 2));+ await store.pin('a', List.filled(32, 3));++ final peers = await store.peers();+ expect(peers.map((p) => p.machineId), ['a', 'b']);+ expect(peers.first.pub, List.filled(32, 3));+ expect((await store.peer('b'))!.label, 'Mac');++ // And the file says the same to the next launch.+ final reread = await ViewerKeyStore(storage: storage).peers();+ expect(reread.map((p) => p.machineId), ['a', 'b']);+ expect(reread.first.pub, List.filled(32, 3));+ });++ test(+ 'unlinking drops only that machine, and says when there was none',+ () async {+ final store = ViewerKeyStore(storage: MemoryKeyValueStore());+ await store.pin('a', List.filled(32, 1));+ await store.pin('b', List.filled(32, 2));+ expect(await store.unlink('a'), isTrue);+ expect(await store.unlink('a'), isFalse);+ expect((await store.peers()).map((p) => p.machineId), ['b']);+ },+ );++ test('a damaged row loses that row, not every link', () async {+ final storage = MemoryKeyValueStore();+ storage.values[_peersKey] = jsonEncode([+ {'machineId': 'good', 'pub': b64e(List.filled(32, 9)), 'linkedAt': 5},+ {'machineId': 'no-pub', 'linkedAt': 5},+ {'machineId': 'bad-pub', 'pub': '!!!', 'linkedAt': 5},+ {+ 'machineId': 'bad-date',+ 'pub': b64e([1]),+ 'linkedAt': 'yesterday',+ },+ 'not a row',+ null,+ ]);+ final peers = await ViewerKeyStore(storage: storage).peers();+ expect(peers.map((p) => p.machineId), ['good']);+ expect(peers.single.label, '');+ });++ test('a file that is not a list reads as no links', () async {+ for (final raw in ['{"a":1}', 'not json', '"x"']) {+ final storage = MemoryKeyValueStore()..values[_peersKey] = raw;+ expect(await ViewerKeyStore(storage: storage).peers(), isEmpty);+ }+ });++ test('peers are read from disk once, then held', () async {+ final storage = _FlakyStore();+ final store = ViewerKeyStore(storage: storage);+ await store.peers();+ await store.peer('a');+ await store.peer('b');+ expect(storage.reads, 1);+ });++ // ⚠️ The same trap as the identity's, on the dial path: `viewerRelayCodecs` asks for the+ // peer before every connect and reconnect, and a rejected read held as the answer turned a+ // locked moment into a machine that never reconnected.+ test('a read that failed once is asked again, not held', () async {+ final storage = _FlakyStore()+ ..values[_peersKey] = jsonEncode([+ {'machineId': 'm', 'pub': b64e(List.filled(32, 1)), 'linkedAt': 1},+ ])+ ..failReads = 1;+ final store = ViewerKeyStore(storage: storage);+ await expectLater(store.peer('m'), throwsStateError);+ expect((await store.peer('m'))!.machineId, 'm');+ });++ test('a pin that did not reach the disk is not believed', () async {+ final storage = _FlakyStore()..failWrites = 1;+ final store = ViewerKeyStore(storage: storage);+ await expectLater(store.pin('m', List.filled(32, 1)), throwsStateError);+ expect(await store.peer('m'), isNull);+ });++ test('a row round-trips through its JSON', () {+ final peer = MachinePeer.tryParse({+ 'machineId': 'm',+ 'pub': b64e(List.filled(32, 4)),+ 'label': 'Mac',+ 'linkedAt': 1000,+ })!;+ expect(peer.toJson(), {+ 'machineId': 'm',+ 'pub': b64e(List.filled(32, 4)),+ 'label': 'Mac',+ 'linkedAt': 1000,+ });+ });+ });+}