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
Refactor agent selection logic and enhance tests for last opened agent persistence
Dev jacob022b01091114
diff --git a/mobile/lib/phone/agent_home.dart b/mobile/lib/phone/agent_home.dartindex 1b325d418..73834f5ea 100644--- a/mobile/lib/phone/agent_home.dart+++ b/mobile/lib/phone/agent_home.dart@@ -348,12 +348,9 @@ class _AgentHomeState extends State<AgentHome> {// something real while the machine dials rather than blanking to a skeleton.final awaiting = _awaitingMachine;if (awaiting != null) {- final arrival = entries- .where(- (entry) =>- entry.machineId == awaiting && entry.agent.terminalAvailable,- )- .firstOrNull;+ final arrival = _mostRecentOpenable(+ entries.where((entry) => entry.machineId == awaiting),+ );if (arrival != null) return arrival;}// ⚠️ **The pager the screen already holds is asked FIRST, before [_showing], and that ordering@@ -401,7 +398,24 @@ class _AgentHomeState extends State<AgentHome> {}}}- return entries.where((entry) => entry.agent.terminalAvailable).firstOrNull;+ return _mostRecentOpenable(entries);+ }++ /// The agent to fall back on: the one whose conversation moved last, of those that can be opened.+ ///+ /// ⚠️ **Not the first in the list, which is what it was — and the first is the OLDEST.** [entries]+ /// run in each machine's own order, which is creation order, so every miss of the record above —+ /// the agent left on paused from the desktop's monitor since, deleted, or no record at all — landed+ /// on the same agent untouched for days, and the pager then remembered THAT, so it stuck. The+ /// desktop's monitor puts the most recently active harness on top ([compareMonitorOrder]); this is+ /// the agent somebody means when the one they left is gone.+ static AgentEntry? _mostRecentOpenable(Iterable<AgentEntry> entries) {+ AgentEntry? best;+ for (final entry in entries) {+ if (!entry.agent.terminalAvailable) continue;+ if (best == null || compareMonitorOrder(entry, best) < 0) best = entry;+ }+ return best;}/// Whether any machine can currently host an agent.diff --git a/mobile/test/encrypted_down_types_test.dart b/mobile/test/encrypted_down_types_test.dartindex cd6a0d477..0340a6c2c 100644--- a/mobile/test/encrypted_down_types_test.dart+++ b/mobile/test/encrypted_down_types_test.dart@@ -5,17 +5,30 @@ import 'package:harness_mobile/e2ee/envelope.dart';/// The phone seals exactly the frames the machine insists on.///-/// ⚠️ **Read from the CLI's source, not copied into this test.** A type the CLI adds to-/// `ENCRYPTED_DOWN_TYPES` and the phone does not fails nowhere on the phone — the frame leaves in the-/// clear and the machine answers E2EE_REQUIRED, which is how `agent_resume` shipped broken. Only a-/// test that reads the CLI's list notices the day it grows.+/// ⚠️ **Read from the CLI's source, not copied into this test.** A type the CLI requires sealed and+/// the phone does not fails nowhere on the phone — the frame leaves in the clear and the machine+/// answers E2EE_REQUIRED, which is how `agent_resume` and `git_project_info` both shipped broken.+/// Only a test that reads the CLI's lists notices the day they grow.+///+/// The CLI's rule is `encryptDownFrame` (`cli/src/lib/e2ee/applicationFrames.ts`): the shared core's+/// `ENCRYPTED_DOWN_TYPES` plus the harness-only extensions declared beside it. Both halves are read.void main() {- /// The quoted names in a set literal, with `//` comments stripped first — the CLI's comments quote- /// type names too.- Set<String> namesIn(String source, String start, String end) {+ String cli(String path) {+ final file = File('../cli/src/$path');+ if (!file.existsSync()) {+ throw StateError(+ '${file.path} missing — run from mobile/ in the monorepo',+ );+ }+ return file.readAsStringSync();+ }++ /// The quoted names in the set literal that follows [start], `//` comments stripped first — the+ /// CLI's comments quote type names too.+ Set<String> namesIn(String source, String start) {final from = source.indexOf(start);- expect(from, isNonNegative, reason: 'could not find $start');- final body = source.substring(from, source.indexOf(end, from));+ if (from < 0) throw StateError('could not find $start');+ final body = source.substring(from, source.indexOf('])', from));final code = body.split('\n').map((line) => line.split('//').first)@@ -25,63 +38,43 @@ void main() {};}- test('seals every type the CLI insists on', () {- final core = File('../cli/src/lib/e2ee/core.ts');- expect(- core.existsSync(),- isTrue,- reason: 'run from mobile/ in the monorepo',- );- final cli = namesIn(- core.readAsStringSync(),+ late Set<String> core, machineRequests, unwrapped;+ setUpAll(() {+ core = namesIn(+ cli('lib/e2ee/core.ts'),'ENCRYPTED_DOWN_TYPES = new Set<string>([',- '])',- );- expect(cli, isNotEmpty);- expect(- encryptedDownTypes,- containsAll(cli),- reason:- 'a type the machine requires and the phone sends in the clear '- 'comes back E2EE_REQUIRED',);+ final frames = cli('lib/e2ee/applicationFrames.ts');+ machineRequests = namesIn(frames, 'MACHINE_REQUESTS = new Set([');+ unwrapped = {+ ...core,+ ...machineRequests,+ ...namesIn(frames, 'FLEET_REQUESTS = new Set(['),+ ...namesIn(cli('sharing/protocol.ts'), 'SHARE_REQUEST_TYPES = new Set(['),+ ...namesIn(cli('lib/viewerWire.ts'), 'VIEWER_DOWN_TYPES = new Set(['),+ };});- /// ⚠️ **`ENCRYPTED_DOWN_TYPES` is NOT the machine's whole rule**, and reading- /// it as though it were cost an afternoon: `git_project_info` is required by- /// `encryptDownFrame` in `lib/e2ee/applicationFrames.ts`, which is that set- /// OR several types named outright beside it. Sealing it looked wrong against- /// the narrow list, the entry was taken back out, and the machine went on- /// answering E2EE_REQUIRED.- ///- /// So the two halves are tested apart: everything the set names must be- /// sealed (above), and anything sealed BEYOND it must be something the- /// machine will actually unwrap (here). Sealing a type the CLI does not- /// unwrap is the quieter fault of the two — the envelope is never opened, the- /// payload reads back as undefined fields, and the caller waits out its- /// timeout.- test('seals nothing the CLI would refuse to unwrap', () {- final frames = File('../cli/src/lib/e2ee/applicationFrames.ts');- expect(- frames.existsSync(),- isTrue,- reason: 'run from mobile/ in the monorepo',- );- final source = frames.readAsStringSync();- final rule = source.substring(- source.indexOf('encryptDownFrame'),- source.indexOf('encryptRpcResult'),- );- final core = namesIn(- File('../cli/src/lib/e2ee/core.ts').readAsStringSync(),- 'ENCRYPTED_DOWN_TYPES = new Set<string>([',- '])',- );- // The types the rule names outright, beside the set it starts from.- final named = {- for (final match in RegExp(r"'([a-z0-9_]+)'").allMatches(rule)) match[1]!,- };- expect(named, contains('git_project_info'));- expect(encryptedDownTypes.difference(core.union(named)), isEmpty);+ test('every frame the shared core requires sealed is sealed', () {+ expect(core, isNotEmpty);+ expect(core.difference(encryptedDownTypes), isEmpty);+ });++ test('nothing is sealed that the machine would not open', () {+ expect(encryptedDownTypes.difference(unwrapped), isEmpty);+ });++ test('a machine request the phone sends is sealed', () {+ // Any quoted use outside the list itself counts as sending it.+ final sent = <String>{};+ for (final file in Directory('lib').listSync(recursive: true)) {+ if (file is! File || !file.path.endsWith('.dart')) continue;+ if (file.path.endsWith('e2ee/envelope.dart')) continue;+ final source = file.readAsStringSync();+ for (final type in machineRequests) {+ if (source.contains("'$type'")) sent.add(type);+ }+ }+ expect(sent.difference(encryptedDownTypes), isEmpty);});}diff --git a/mobile/test/last_opened_agent_test.dart b/mobile/test/last_opened_agent_test.dartnew file mode 100644index 000000000..9d9cfb1b8--- /dev/null+++ b/mobile/test/last_opened_agent_test.dart@@ -0,0 +1,45 @@+import 'dart:io';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/core/harness_file_store.dart';+import 'package:harness_mobile/core/last_opened_agent.dart';++/// The record survives the app: written through the state file a phone really uses, read back by a+/// fresh process.+void main() {+ late Directory dir;+ setUp(() => dir = Directory.systemTemp.createTempSync('last-agent-'));+ tearDown(() => dir.deleteSync(recursive: true));++ /// What a relaunch has: a new store and a new record over the same file.+ LastOpenedAgent launch() => LastOpenedAgent(HarnessFileStore(directory: dir));++ /// [LastOpenedAgent.remember] does not wait for its write; a relaunch comes+ /// long after it has landed.+ Future<void> settle() =>+ Future<void>.delayed(const Duration(milliseconds: 200));++ test('the last agent remembered is the one the next launch reads', () async {+ final first = launch();+ first.remember((machineId: 'm', agentId: 'a'));+ first.remember((machineId: 'm', agentId: 'c'));+ await settle();++ expect(await launch().read(), (machineId: 'm', agentId: 'c'));+ });++ test(+ 'a prefetched read serves the launch, then reads the disk again',+ () async {+ launch().remember((machineId: 'm', agentId: 'a'));+ await settle();++ final second = launch()..prefetch();+ expect(await second.read(), (machineId: 'm', agentId: 'a'));+ second.remember((machineId: 'm', agentId: 'b'));+ await settle();+ // Not the prefetch again: that read belonged to the launch.+ expect(await second.read(), (machineId: 'm', agentId: 'b'));+ },+ );+}diff --git a/mobile/test/phone_restore_last_agent_test.dart b/mobile/test/phone_restore_last_agent_test.dartindex fac2909be..aa4cfb882 100644--- a/mobile/test/phone_restore_last_agent_test.dart+++ b/mobile/test/phone_restore_last_agent_test.dart@@ -20,13 +20,22 @@ import 'voice_fakes.dart';/// for a second or two. Reading that as "gone" put the phone on whichever agent happened to have/// been verified first, which is the oldest one on the machine.void main() {+ /// What the shell hands the home screen when an agent is picked elsewhere —+ /// the search sheet, the tabs panel (`PhoneShell._openAgentAtHome`).+ ValueNotifier<({String machineId, String agentId})?>? picked;+Future<void> pumpHome(WidgetTester tester, AppNotifier app) async {+ final request = picked = ValueNotifier(null);+ addTearDown(request.dispose);await tester.pumpWidget(MaterialApp(home: PhoneShellScope(onMachineLinked: (_) {},- onOpenAgent: (_, _) {},- child: AgentHome(notifier: app),+ onOpenAgent: (machineId, agentId) {+ request.value = null;+ request.value = (machineId: machineId, agentId: agentId);+ },+ child: AgentHome(notifier: app, openAgent: request),),),);@@ -133,6 +142,63 @@ void main() {expect(storage.values['phone_last_agent_v1'], isNotNull);});+ testWidgets('the next launch opens the agent picked last, not the first', (+ tester,+ ) async {+ final storage = remembering('a');+ final first = await app(tester, storage: storage);+ machineLists(first, [+ for (final id in pagerAgentIds) agent(id, terminal: true),+ ]);+ await pumpHome(tester, first);+ expect(openedAgent(tester), 'a');++ // Picked from the search sheet or the tabs panel.+ picked!.value = (machineId: 'm', agentId: 'c');+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 700));+ expect(openedAgent(tester), 'c');+ expect(storage.values['phone_last_agent_v1'], contains('"agentId":"c"'));++ // Relaunch: a new app over the same storage.+ await tester.pumpWidget(const SizedBox());+ final second = await app(tester, storage: storage);+ machineLists(second, [+ for (final id in pagerAgentIds) agent(id, terminal: true),+ ]);+ await pumpHome(tester, second);+ expect(openedAgent(tester), 'c');+ });++ testWidgets(+ 'the agent left on was paused: the most recent one opens, not the oldest',+ (tester) async {+ final now = DateTime.now();+ Agent at(String id, int minutesAgo, {bool stopped = false}) => Agent(+ id: id,+ name: id,+ engine: 'claude',+ sessionId: 'session-$id',+ status: stopped ? 'stopped' : 'active',+ project: const AgentProject(name: 'work', cwd: '/work'),+ updatedAt: now.subtract(Duration(minutes: minutesAgo)),+ terminalAvailable: !stopped,+ );+ final notifier = await app(tester, storage: remembering('b'));+ machineLists(notifier, [+ // First on the machine's list, and untouched for days — what the+ // phone kept landing on.+ at('a', 60 * 24 * 3),+ // Where the phone was left, paused since from the desktop's monitor.+ at('b', 5, stopped: true),+ at('c', 20),+ at('d', 90),+ ]);+ await pumpHome(tester, notifier);+ expect(openedAgent(tester), 'c');+ },+ );+testWidgets('waits for the remembered agent\'s terminal to be verified', (tester,) async {