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 scanned pairing code no longer outlives its session
deee942ac3304f6
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex 44c5a6170..d8ca394fb 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -1282,6 +1282,7 @@ class AppNotifier extends ChangeNotifier {ViewerServices? viewer,PaneLayoutStore? paneLayoutStore,SystemNotices? systemNotices,+ MachineCache? machineCache,this.turnActivityTimeout = const Duration(seconds: 12),}) : _paneLayout = paneLayoutStore,// On the same terms as the stores below: no layout store means a test,@@ -1303,8 +1304,10 @@ class AppNotifier extends ChangeNotifier {searchHistory = PhoneSearchHistory(paneLayoutStore?.storage),// On the same terms as the stores above: a layout store means this is a// real app with a real Harness home to cache into, and its absence means- // a test, which must not read or write one.- _machineCache = paneLayoutStore == null ? null : MachineCache(),+ // a test, which must not read or write one — unless it hands over a+ // cache of its own, kept in memory.+ _machineCache =+ machineCache ?? (paneLayoutStore == null ? null : MachineCache()),session = authSession,_store = configStore,cliLink = cliLink ?? CliLink(),@@ -2579,6 +2582,8 @@ class AppNotifier extends ChangeNotifier {currentUser = null;signingIn = false;pendingAuthorizeUrl = null;+ // The code was scanned into the session that just ended — see [logout].+ pendingPairing = null;_awaitingFirstMessage = null;_desk.reset();analyticsAccount.clear();@@ -2905,6 +2910,12 @@ class AppNotifier extends ChangeNotifier {cliLogin.cancel();signingIn = false;pendingAuthorizeUrl = null;+ // A scanned code belongs to the session it was scanned into. Held past this,+ // the next sign-in — perhaps another account's — would spend it on the first+ // locked machine of that id and show a pairing error where its password form+ // belongs. Not in [_invalidateAuthWork]: signing IN starts there too, and the+ // code is set before that sign-in on purpose (`phone_welcome.dart`).+ pendingPairing = null;_closedHistory.clear();// Best-effort and fire-and-forget: local state is cleared below regardless of whether the CLI// process could be reached, but a real `harness logout` clears its saved session so the NEXT@@ -3024,6 +3035,11 @@ class AppNotifier extends ChangeNotifier {if (nextStatus == ConnectionStatus.connected) {machine.needsLink = false;_stopLinkRetry(machineId);+ // A relay socket reports `connected` only after the machine's welcome+ // proved the link (`WsConn._markReady`), so a code held to pair this+ // machine has nothing left to do. Kept, it would be spent the next time+ // the machine locks — an unlink, say — in place of its password form.+ if (pendingPairing?.machineId == machineId) pendingPairing = null;// A daemon that just came up — first connect, or a reconnect after it// restarted — has never been told what is on the grid. Without this// the dial goes back to beeping about tiles in plain sight until the@@ -3149,6 +3165,12 @@ class AppNotifier extends ChangeNotifier {.where((machine) => machine.authMode == MachineAuthMode.remote).toList();final visible = machines.map((machine) => machine.machineId).toSet();+ // A code scanned for a machine this account does not have can never be+ // spent: the pairing screen waits for that machine to show up locked.+ if (pendingPairing case final pending?+ when !visible.contains(pending.machineId)) {+ pendingPairing = null;+ }for (final entry in machineStates.entries) {if (!visible.contains(entry.key)) {_clearMachineActivity(entry.value);@@ -3681,7 +3703,7 @@ class AppNotifier extends ChangeNotifier {// connection as a side effect of being asked about one — for a machine// `_connectMachine` had just declined to dial, that would be this method// quietly undoing its own decision.- if (_pool?[machine.machineId]?.isReady == true) {+ if (_connectionReady(machine.machineId)) {unawaited(_loadMachineData(state));}}@@ -3824,6 +3846,16 @@ class AppNotifier extends ChangeNotifier {return connection;}+ /// Whether [machineId]'s socket has finished its handshake — asked of the+ /// connection the app already HOLDS, never of one built for the asking (see+ /// [_autoConnectAndLoadMachines] for why that matters). A test's+ /// [connectionForTest] stands in for the pool here, as it does in [_conn].+ bool _connectionReady(String machineId) {+ final testConnection = connectionForTest;+ if (testConnection != null) return testConnection(machineId).isReady;+ return _pool?[machineId]?.isReady == true;+ }+// Every machine — this computer's own, or a relayed one — now speaks the same plaintext local wire// protocol to the CLI (which terminates E2EE itself for relayed machines; see remoteRelay.ts in the// harness CLI repo). There is no per-machine branching left here at all.@@ -5295,10 +5327,10 @@ class AppNotifier extends ChangeNotifier {// Created HERE, so it joins the tab this phone is in — the way an agent// created in a window joins that window's tab. See [PhoneDesk.adopt] for// what happens when the phone is in no tab.- _desk.adopt(- (machineId: machineId, agentId: agent.id),- name: agent.displayName,- );+ _desk.adopt((+ machineId: machineId,+ agentId: agent.id,+ ), name: agent.displayName);await assignAgentToPane(null,machineId,@@ -5803,7 +5835,7 @@ class AppNotifier extends ChangeNotifier {final pending = machine.pendingOfflineAgentId;if (pending != null) {unawaited(_recoverPendingAgent(machine, pending));- } else if (_pool?[machineId]?.isReady == true &&+ } else if (_connectionReady(machineId) &&(wasOnline == false || panesFor(machineId).any(_paneNeedsAttach))) {// ⚠️ **A machine that was OFF and is back owes a fresh list, whether or// not anything here was waiting on it.** This arrives as a `node_status`@@ -5862,7 +5894,7 @@ class AppNotifier extends ChangeNotifier {// budget waiting for the handshake and then report the machine offline —// on the very path that exists to recover a machine coming back. The// delay at the foot of this loop is the poll; this just skips the turn.- if (_pool?[machineId]?.isReady != true) {+ if (!_connectionReady(machineId)) {await Future<void>.delayed(const Duration(milliseconds: 250));continue;}@@ -7036,10 +7068,7 @@ class AppNotifier extends ChangeNotifier {if (!_canAttachPane(pane)) return;final session = pane.session;if (session == null) {- await _attachSession(- pane,- takeControl: intent == AttachIntent.person,- );+ await _attachSession(pane, takeControl: intent == AttachIntent.person);} else {if (intent == AttachIntent.person) session.takeover = true;await session.reopen();@@ -7548,6 +7577,11 @@ class AppNotifier extends ChangeNotifier {void localFailureForTest(String machineId, int code, String reason) =>_onLocalFailure(machineId, code, reason);+ /// What a socket finding the session gone for good does to the model — the+ /// `WsPool.onAuthFailure` path ([WsCredentialRevoked]), without a socket.+ @visibleForTesting+ void authFailureForTest(String message) => _signedOutAtRuntime(message);+@overridevoid dispose() {_localGitProjects.dispose();diff --git a/mobile/test/app_state_pairing_test.dart b/mobile/test/app_state_pairing_test.dartnew file mode 100644index 000000000..947642c89--- /dev/null+++ b/mobile/test/app_state_pairing_test.dart@@ -0,0 +1,279 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/auth/cli_link.dart';+import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/terminal/terminal_session.dart';++import 'agent_pager_fixture.dart' show goLive;+import 'viewer_app_fixture.dart';++/// Linking a phone to a machine: by its password, by the code an "Add phone" QR+/// carries, and taking the link away again.+void main() {+ /// Signed in to an account with one machine, `m`, that wants its password.+ Future<ViewerRig> lockedMachine() async {+ final rig = viewerApp();+ rig.api.onMachines = () async => [remoteMachine('m')];+ await rig.app.bootstrap();+ await settle();+ rig.app.localFailureForTest('m', 4404, 'NO_PEER_LINK');+ return rig;+ }++ group('by password', () {+ test('an empty one is not sent', () async {+ final rig = await lockedMachine();+ addTearDown(rig.app.dispose);++ expect(+ await rig.app.connectWithPassword('m', ''),+ 'Enter the remote password first',+ );+ expect(rig.links.passwords, isEmpty);+ });++ test('a refused one says why and leaves the machine locked', () async {+ final rig = await lockedMachine();+ addTearDown(rig.app.dispose);+ rig.links.connectResult = const CliLinkConnectResult(+ error: 'Wrong password',+ );++ expect(await rig.app.connectWithPassword('m', 'nope'), 'Wrong password');+ expect(rig.app.stateOf('m')!.needsLink, isTrue);+ });++ test('a right one unlocks the machine and dials it again', () async {+ final rig = await lockedMachine();+ addTearDown(rig.app.dispose);+ final stages = <String>[];++ final error = await rig.app.connectWithPassword(+ 'm',+ 'hunter2',+ onProgress: stages.add,+ );++ expect(error, isNull);+ expect(rig.links.passwords.single, ('m', 'hunter2'));+ expect(stages, ['connecting']);+ final machine = rig.app.stateOf('m')!;+ expect(machine.needsLink, isFalse);+ expect(machine.agentLoadStatus, AgentLoadStatus.idle);+ });++ test('the machine the link actually named is the one unlocked', () async {+ final rig = viewerApp();+ addTearDown(rig.app.dispose);+ rig.api.onMachines = () async => [remoteMachine('m'), remoteMachine('n')];+ await rig.app.bootstrap();+ await settle();+ rig.app.localFailureForTest('m', 4404, 'NO_PEER_LINK');+ rig.app.localFailureForTest('n', 4404, 'NO_PEER_LINK');+ rig.links.connectResult = const CliLinkConnectResult(+ linkedMachineId: 'n',+ );++ expect(await rig.app.connectWithPassword('m', 'pw'), isNull);++ expect(rig.app.stateOf('n')!.needsLink, isFalse);+ expect(rig.app.stateOf('m')!.needsLink, isTrue);+ });+ });++ group('by the code a QR carries', () {+ test('pairs, naming this phone, and unlocks the machine', () async {+ final rig = await lockedMachine();+ addTearDown(rig.app.dispose);++ expect(await rig.app.connectWithCode('m', 'K7QM'), isNull);++ final (machineId, code, label) = rig.links.codes.single;+ expect((machineId, code), ('m', 'K7QM'));+ expect(label, rig.app.phoneClientDescriptor().name);+ expect(rig.app.stateOf('m')!.needsLink, isFalse);+ });++ test('a spent code says so and leaves the machine locked', () async {+ final rig = await lockedMachine();+ addTearDown(rig.app.dispose);+ rig.links.codeResult = const CliLinkConnectResult(error: 'Code expired');++ expect(await rig.app.connectWithCode('m', 'OLD'), 'Code expired');+ expect(rig.app.stateOf('m')!.needsLink, isTrue);+ });++ test('dropping a held code is said once, and only when there was one', () {+ final rig = viewerApp();+ addTearDown(rig.app.dispose);+ var redraws = 0;+ rig.app.addListener(() => redraws++);++ rig.app.dropPendingPairing();+ expect(redraws, 0);++ rig.app.pendingPairing = (machineId: 'm', code: 'K7QM');+ rig.app.dropPendingPairing();+ expect(rig.app.pendingPairing, isNull);+ expect(redraws, 1);+ });++ test(+ 'a held code does not outlive the session it was scanned into',+ () async {+ final rig = await lockedMachine();+ addTearDown(rig.app.dispose);+ rig.app.pendingPairing = (machineId: 'm', code: 'K7QM');++ await rig.app.logout();++ // Left standing, the next sign-in — perhaps another account's — would+ // try this spent code on the first locked machine of that id instead of+ // offering its password.+ expect(rig.app.pendingPairing, isNull);+ },+ );++ test('a held code goes when its machine connects without it', () async {+ final rig = viewerApp();+ addTearDown(rig.app.dispose);+ rig.app.pendingPairing = (machineId: 'm', code: 'K7QM');+ rig.api.onMachines = () async => [remoteMachine('m')];+ await rig.app.bootstrap();+ await settle();++ // Already linked: the socket comes up and nothing asks for a password.+ rig.app.connectionStatusForTest('m', ConnectionStatus.connected);+ await settle();+ expect(rig.app.pendingPairing, isNull);++ // So unlinking it later offers the password, not a code long spent.+ await rig.app.unlinkMachine('m');+ expect(rig.app.pendingPairing, isNull);+ });++ test(+ 'a held code for a machine the account does not have is dropped',+ () async {+ final rig = viewerApp();+ addTearDown(rig.app.dispose);+ rig.app.pendingPairing = (machineId: 'gone', code: 'K7QM');+ rig.api.onMachines = () async => [remoteMachine('m')];++ await rig.app.bootstrap();+ await settle();++ expect(rig.app.pendingPairing, isNull);+ },+ );++ test(+ 'a held code survives a machine list that is still on its way',+ () async {+ final rig = viewerApp();+ addTearDown(rig.app.dispose);+ rig.app.pendingPairing = (machineId: 'm', code: 'K7QM');+ rig.api.onMachines = () async => [remoteMachine('m')];++ await rig.app.bootstrap();+ await settle();+ rig.app.localFailureForTest('m', 4404, 'NO_PEER_LINK');++ expect(rig.app.pendingPairing, (machineId: 'm', code: 'K7QM'));+ },+ );+ });++ group('taking the link away', () {+ test('a refusal is said and nothing changes', () async {+ final rig = viewerApp();+ addTearDown(rig.app.dispose);+ rig.api.onMachines = () async => [remoteMachine('m')];+ await rig.app.bootstrap();+ await settle();+ rig.links.unlinkError = 'Could not unlink';++ expect(await rig.app.unlinkMachine('m'), 'Could not unlink');+ expect(rig.app.stateOf('m')!.needsLink, isFalse);+ expect(rig.links.lists, 0);+ });++ test('locks the machine, keeps it on, and freezes its terminals', () async {+ final rig = viewerApp();+ addTearDown(rig.app.dispose);+ rig.api.onMachines = () async => [remoteMachine('m')];+ await rig.app.bootstrap();+ await settle();+ final machine = rig.app.stateOf('m')!+ ..agents = [Agent.fromJson(agentJson('a'))]+ ..terminalCapabilityAvailable = true;+ final session = TerminalSession(+ machineId: 'm',+ agentId: 'a',+ agentName: 'a',+ engineId: 'claude',+ send: (_, _) async => true,+ sendBinary: (_) async => true,+ );+ rig.app.adoptSessionForTest(session);+ await goLive(session);++ expect(await rig.app.unlinkMachine('m'), isNull);++ expect(rig.links.unlinked, ['m']);+ expect(rig.links.lists, 1, reason: 'the linked list is read again');+ expect(machine.needsLink, isTrue);+ expect(machine.agentLoadStatus, AgentLoadStatus.needsLink);+ expect(machine.nodeOnline, isNot(false), reason: 'still switched on');+ expect(session.status, TerminalSessionStatus.error);+ expect(session.errorMessage, contains('no longer linked'));+ });++ test('an unknown machine is unlinked with nothing else to do', () async {+ final rig = viewerApp();+ addTearDown(rig.app.dispose);++ expect(await rig.app.unlinkMachine('ghost'), isNull);+ expect(rig.links.unlinked, ['ghost']);+ });+ });++ group('the relay saying a machine is not linked', () {+ test('marks it locked, and a phone does not poll for the link', () async {+ final rig = viewerApp();+ addTearDown(rig.app.dispose);+ rig.api.onMachines = () async => [remoteMachine('m')];+ await rig.app.bootstrap();+ await settle();+ final asked = rig.conn('m').requests.length;++ rig.app.localFailureForTest('m', 4404, 'NO_PEER_LINK');+ await Future<void>.delayed(+ AppNotifier.offlineRetryInterval + const Duration(milliseconds: 200),+ );++ final machine = rig.app.stateOf('m')!;+ expect(machine.needsLink, isTrue);+ expect(machine.agentLoadStatus, AgentLoadStatus.needsLink);+ expect(+ rig.conn('m').requests.length,+ asked,+ reason: 'only the password form can fix this on a phone',+ );+ });++ test('any other close, or an unknown machine, changes nothing', () async {+ final rig = viewerApp();+ addTearDown(rig.app.dispose);+ rig.api.onMachines = () async => [remoteMachine('m')];+ await rig.app.bootstrap();+ await settle();++ rig.app.localFailureForTest('m', 1006, 'abnormal');+ rig.app.localFailureForTest('ghost', 4404, 'NO_PEER_LINK');++ expect(rig.app.stateOf('m')!.needsLink, isFalse);+ expect(rig.app.stateOf('ghost'), isNull);+ });+ });+}diff --git a/mobile/test/app_state_sign_in_test.dart b/mobile/test/app_state_sign_in_test.dartnew file mode 100644index 000000000..ed77541f0--- /dev/null+++ b/mobile/test/app_state_sign_in_test.dart@@ -0,0 +1,309 @@+import 'dart:async';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/state/app_state.dart';++import 'viewer_app_fixture.dart';++/// Signing a phone in and out: the viewer build's half of `AppNotifier` —+/// bootstrap with no CLI beside it, the emailed code and the scanned QR, and+/// every late reply that must not outlive the session it was asked for.+void main() {+ group('bootstrap', () {+ test('signed out: the welcome screen, and nothing is fetched', () async {+ final rig = viewerApp(signedIn: false);+ addTearDown(rig.app.dispose);++ await rig.app.bootstrap();++ expect(rig.app.status, AppStatus.unauthenticated);+ expect(rig.api.machineFetches, 0);+ expect(rig.app.currentUser, isNull);+ });++ test('signed in: machines and profile, with no environment step', () async {+ final rig = viewerApp();+ addTearDown(rig.app.dispose);+ rig.api.onMachines = () async => [remoteMachine('m')];+ final seen = <AppStatus>[];+ rig.app.addListener(() => seen.add(rig.app.status));++ await rig.app.bootstrap();+ await settle();++ expect(rig.app.status, AppStatus.authenticated);+ // A viewer installs nothing: provisioning is never shown.+ expect(seen, isNot(contains(AppStatus.checkingEnvironment)));+ expect(seen, isNot(contains(AppStatus.preparingEnvironment)));+ expect(rig.app.machines.map((m) => m.machineId), ['m']);+ expect(rig.app.stateOf('m'), isNotNull);+ expect(rig.app.machinesLoading, isFalse);+ expect(rig.app.bootStatusMessage, isNull);+ expect(rig.app.currentUser?.email, '[email protected]');+ expect(rig.api.machineFetches, 1, reason: 'fetched once, not twice');+ expect(rig.app.lastError, isNull);+ });++ test('says what it is doing while the machines are coming', () async {+ final rig = viewerApp();+ addTearDown(rig.app.dispose);+ final list = Completer<List<Machine>>();+ rig.api.onMachines = () => list.future;+ String? message;+ rig.app.addListener(() => message ??= rig.app.bootStatusMessage);++ final boot = rig.app.bootstrap();+ await settle();++ expect(message, 'Getting your machines…');+ list.complete([remoteMachine('m')]);+ await boot;+ expect(rig.app.bootStatusMessage, isNull);+ });++ test('a session store that cannot be read falls back to sign-in', () async {+ final rig = viewerApp();+ addTearDown(rig.app.dispose);+ rig.signIn.statusFailure = StateError('keychain locked');++ await rig.app.bootstrap();++ expect(rig.app.status, AppStatus.unauthenticated);+ expect(rig.api.machineFetches, 0);+ });++ test('machines that cannot be read leave the app in, saying so', () async {+ final rig = viewerApp();+ addTearDown(rig.app.dispose);+ rig.api.onMachines = () async => throw StateError('relay down');++ await rig.app.bootstrap();++ expect(rig.app.status, AppStatus.authenticated);+ expect(rig.app.lastError, startsWith('Could not load machines'));+ expect(rig.app.lastErrorRetryable, isTrue);+ expect(rig.app.machinesLoading, isFalse);+ });++ test('a profile the account will not give is not an error', () async {+ final rig = viewerApp();+ addTearDown(rig.app.dispose);+ rig.api.profile = null;++ await rig.app.bootstrap();+ await settle();++ expect(rig.app.status, AppStatus.authenticated);+ expect(rig.app.currentUser, isNull);+ expect(rig.app.lastError, isNull);+ });+ });++ group('the emailed code', () {+ test('sends the code, then signs in with it', () async {+ final rig = viewerApp(signedIn: false);+ addTearDown(rig.app.dispose);+ rig.api.onMachines = () async => [remoteMachine('m')];+ expect(rig.app.signsInWithEmailCode, isTrue);++ await rig.app.sendLoginCode('[email protected]');+ await rig.app.signInWithCode(email: '[email protected]', code: '1234');+ await settle();++ expect(rig.viewer.emailLogin.codesSent, ['[email protected]']);+ expect(rig.viewer.emailLogin.signIns, [('[email protected]', '1234')]);+ expect(rig.app.status, AppStatus.authenticated);+ expect(rig.app.signingIn, isFalse);+ expect(rig.app.machines, hasLength(1));+ });++ test(+ 'a wrong code is thrown to the form, never raised as the app\'s error',+ () async {+ final rig = viewerApp(signedIn: false);+ addTearDown(rig.app.dispose);+ rig.viewer.emailLogin.failure = StateError('That code is wrong');++ await expectLater(+ rig.app.signInWithCode(email: '[email protected]', code: '0000'),+ throwsStateError,+ );++ expect(rig.app.status, AppStatus.unauthenticated);+ expect(rig.app.signingIn, isFalse);+ expect(rig.app.lastError, isNull);+ expect(rig.api.machineFetches, 0);+ },+ );++ test('a second press while the first is in the air does nothing', () async {+ final rig = viewerApp(signedIn: false);+ addTearDown(rig.app.dispose);+ final gate = rig.viewer.emailLogin.gate = Completer<void>();++ final first = rig.app.signInWithCode(email: '[email protected]', code: '1111');+ await rig.app.signInWithCode(email: '[email protected]', code: '1111');+ expect(rig.viewer.emailLogin.signIns, hasLength(1));+ expect(rig.app.signingIn, isTrue);++ gate.complete();+ await first;+ expect(rig.app.signingIn, isFalse);+ });++ test(+ 'signing out while the code is checked keeps the phone signed out',+ () async {+ final rig = viewerApp(signedIn: false);+ addTearDown(rig.app.dispose);+ rig.api.onMachines = () async => [remoteMachine('m')];+ final gate = rig.viewer.emailLogin.gate = Completer<void>();++ final signIn = rig.app.signInWithCode(email: '[email protected]', code: '1111');+ await settle();+ await rig.app.logout();+ gate.complete();+ await signIn;+ await settle();++ expect(rig.app.status, AppStatus.unauthenticated);+ expect(rig.app.signingIn, isFalse);+ expect(rig.app.machines, isEmpty);+ expect(rig.api.machineFetches, 0);+ },+ );+ });++ group('the scanned QR', () {+ test('signs in with the code, naming this phone', () async {+ final rig = viewerApp(signedIn: false);+ addTearDown(rig.app.dispose);++ // Named before anybody is signed in: the phone's own name, not an account's.+ final named = rig.app.phoneClientDescriptor().name;+ await rig.app.signInWithScan('HANDOFF');+ await settle();++ final (code, label) = rig.viewer.emailLogin.scans.single;+ expect(code, 'HANDOFF');+ expect(label, named);+ expect(rig.app.status, AppStatus.authenticated);+ });++ test('a spent code is thrown for the email fallback', () async {+ final rig = viewerApp(signedIn: false);+ addTearDown(rig.app.dispose);+ rig.viewer.emailLogin.failure = StateError('expired');++ await expectLater(rig.app.signInWithScan('OLD'), throwsStateError);++ expect(rig.app.status, AppStatus.unauthenticated);+ expect(rig.app.signingIn, isFalse);+ });++ test('nothing happens after the app is gone', () async {+ final rig = viewerApp(signedIn: false);+ rig.app.dispose();++ await rig.app.signInWithScan('HANDOFF');+ await rig.app.signInWithCode(email: '[email protected]', code: '1');++ expect(rig.viewer.emailLogin.scans, isEmpty);+ expect(rig.viewer.emailLogin.signIns, isEmpty);+ });+ });++ group('signing out', () {+ test('forgets the account, its machines and its sockets', () async {+ final rig = viewerApp();+ addTearDown(rig.app.dispose);+ rig.api.onMachines = () async => [remoteMachine('m')];+ await rig.app.bootstrap();+ await settle();++ await rig.app.logout();++ expect(rig.app.status, AppStatus.unauthenticated);+ expect(rig.app.machines, isEmpty);+ expect(rig.app.machineStates, isEmpty);+ expect(rig.app.currentUser, isNull);+ expect(rig.app.selectedMachineId, isNull);+ expect(rig.signIn.logouts, 1);+ });++ test('a machine list that lands after sign-out is thrown away', () async {+ final rig = viewerApp();+ addTearDown(rig.app.dispose);+ final list = Completer<List<Machine>>();+ rig.api.onMachines = () => list.future;++ final boot = rig.app.bootstrap();+ await settle();+ await rig.app.logout();+ list.complete([remoteMachine('m')]);+ await boot;+ await settle();++ expect(rig.app.status, AppStatus.unauthenticated);+ expect(rig.app.machines, isEmpty);+ expect(rig.app.machineStates, isEmpty);+ });++ test('an agent created while signing out does not come back', () async {+ final rig = viewerApp();+ addTearDown(rig.app.dispose);+ rig.api.onMachines = () async => [remoteMachine('m')];+ await rig.app.bootstrap();+ await settle();+ final reply = Completer<Map<String, dynamic>>();+ rig.conn('m').answers['agent_create'] = (_) => reply.future;+ final attempt = AgentCreationAttempt();++ final creating = rig.app.createAgent(+ 'm',+ engine: 'claude',+ folder: '/work',+ attempt: attempt,+ );+ await settle();+ await rig.app.logout();+ final creationId = rig.conn('m').payloadsOf('agent_create').single;+ reply.complete({+ 'creationId': creationId['creationId'],+ 'state': 'created',+ 'agent': agentJson('new'),+ });++ expect(await creating, isNull, reason: 'the machine did start it');+ expect(attempt.agentId, 'new');+ expect(rig.app.machineStates, isEmpty);+ expect(+ rig.app.allPanes,+ isEmpty,+ reason: 'no terminal for a signed-out phone',+ );+ });++ test(+ 'a session revoked under a running app lands on sign-in, once',+ () async {+ final rig = viewerApp();+ addTearDown(rig.app.dispose);+ rig.api.onMachines = () async => [remoteMachine('m')];+ await rig.app.bootstrap();+ await settle();+ var redraws = 0;+ rig.app.addListener(() => redraws++);++ rig.app.authFailureForTest('Your sign-in expired. Sign in again.');+ rig.app.authFailureForTest('Your sign-in expired. Sign in again.');++ expect(rig.app.status, AppStatus.unauthenticated);+ expect(rig.app.lastError, 'Your sign-in expired. Sign in again.');+ expect(rig.app.currentUser, isNull);+ expect(redraws, 1, reason: 'several sockets can race to say so');+ },+ );+ });+}diff --git a/mobile/test/viewer_app_fixture.dart b/mobile/test/viewer_app_fixture.dartnew file mode 100644index 000000000..281688d2a--- /dev/null+++ b/mobile/test/viewer_app_fixture.dart@@ -0,0 +1,430 @@+import 'dart:async';+import 'dart:typed_data';++import 'package:harness_mobile/api/api_client.dart';+import 'package:harness_mobile/auth/auth_session.dart';+import 'package:harness_mobile/auth/cli_link.dart';+import 'package:harness_mobile/auth/cli_login.dart';+import 'package:harness_mobile/auth/peer_link_client.dart';+import 'package:harness_mobile/auth/sign_in_client.dart';+import 'package:harness_mobile/core/config.dart';+import 'package:harness_mobile/core/machine_cache.dart';+import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/viewer/direct_auth.dart';+import 'package:harness_mobile/viewer/direct_auth_api.dart';+import 'package:harness_mobile/viewer/direct_link.dart';+import 'package:harness_mobile/viewer/direct_login.dart';+import 'package:harness_mobile/viewer/email_code_api.dart';+import 'package:harness_mobile/viewer/email_code_login.dart';+import 'package:harness_mobile/viewer/viewer_key_store.dart';+import 'package:harness_mobile/viewer/viewer_services.dart';+import 'package:harness_mobile/ws/relay_codec.dart';+import 'package:harness_mobile/ws/terminal_transport_plugin.dart';+import 'package:harness_mobile/ws/ws_conn.dart';++import 'agent_pager_fixture.dart';+import 'viewer/fake_http.dart';+import 'voice_fakes.dart' show MemoryKeyValueStore;++/// The phone app with everything outside the process faked: the account's REST+/// API ([FakeApi]), each machine's socket ([ScriptedConn]), the sign-in+/// ([FakeSignIn], [FakeEmailLogin]) and the links to machines ([FakeLinks]).+///+/// ⚠️ **Nothing here may reach a real account, a real daemon or a real+/// `~/.harness`.** The session is kept in memory, every HTTP client answers from+/// a map ([FakeHttp]), and no [WsConn] ever dials — a [ScriptedConn] is built+/// with an address that does not resolve and never has `connect` called.++/// A machine's socket that answers each request type from [answers], and+/// remembers everything it was asked and sent.+class ScriptedConn extends PagerConn {+ ScriptedConn({this.ready = true});++ /// Whether the handshake is done — what `isReady` and `waitUntilReady` say.+ bool ready;++ /// Whether the socket has given up for good ([WsConn.isClosed]).+ bool closed = false;++ /// Request type → its reply. A type with no entry answers `{}`. Throwing+ /// stands for a refusal ([WsRequestFailure]), a timeout+ /// ([WsRequestTimeout]) or a dropped socket.+ final Map<+ String,+ FutureOr<Map<String, dynamic>> Function(Map<String, dynamic> payload)+ >+ answers = {};++ final List<(String, Map<String, dynamic>)> requests = [];+ final List<Uint8List> binaries = [];+ int redials = 0;++ /// The request types asked, in order.+ List<String> get asked => [for (final (type, _) in requests) type];++ /// The payloads of every request of [type].+ List<Map<String, dynamic>> payloadsOf(String type) => [+ for (final (asked, payload) in requests)+ if (asked == type) payload,+ ];++ @override+ bool get isReady => ready;++ @override+ bool get isClosed => closed;++ @override+ Future<void> waitUntilReady({required Duration timeout}) async {+ if (!ready) throw const WsRequestTimeout('machine_select');+ }++ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async {+ requests.add((type, payload));+ final answer = answers[type];+ if (answer == null) return {};+ return await answer(payload);+ }++ @override+ Future<bool> sendTerminalBinary(Uint8List bytes) async {+ binaries.add(bytes);+ return true;+ }++ @override+ Future<void> forceReconnect() async => redials++;+}++/// A refusal from the machine, as `request` throws it.+WsRequestFailure refusal(String code, {String? detail}) =>+ WsRequestFailure(responseType: 'result', code: code, detail: detail);++/// The account's REST API: `/api/machines`, `/api/auth/me` and the desk.+class FakeApi extends ApiClient {+ FakeApi()+ : super(+ config: AppConfig.dev,+ session: AuthSession(storage: MemoryKeyValueStore()),+ );++ /// What `/api/machines` answers; replace to change the account, or throw+ /// from it for an account that cannot be read.+ Future<List<Machine>> Function() onMachines = () async => const [];+ int machineFetches = 0;++ Map<String, dynamic>? profile = const {+ 'user': {'id': 'u1', 'email': '[email protected]', 'name': 'Pat'},+ };+ int profileReads = 0;++ final List<String> renamed = [];+ final List<String> deleted = [];+ Object? renameFailure;+ Object? deleteFailure;++ @override+ Future<List<Machine>> machines() {+ machineFetches++;+ return onMachines();+ }++ @override+ Future<Map<String, dynamic>?> me() async {+ profileReads++;+ return profile;+ }++ @override+ Future<Map<String, dynamic>?> desk() async => null;++ @override+ Future<Map<String, dynamic>?> deskOps(List<Map<String, dynamic>> ops) async =>+ null;++ @override+ Future<String?> renameMachine({+ required String machineId,+ required String name,+ }) async {+ if (renameFailure case final failure?) throw failure;+ renamed.add('$machineId=$name');+ return name;+ }++ @override+ Future<void> deleteMachine({required String machineId}) async {+ if (deleteFailure case final failure?) throw failure;+ deleted.add(machineId);+ }+}++/// Whether the phone is signed in, as the viewer's session store would say.+class FakeSignIn implements SignInClient {+ FakeSignIn({this.signedIn = true});++ bool signedIn;++ /// Thrown by [checkStatus] when set: a session store that could not be read.+ Object? statusFailure;++ /// Held open until the test completes it.+ Completer<void>? statusGate;+ int cancels = 0;+ int logouts = 0;++ @override+ Future<CliAuthStatus> checkStatus() async {+ await statusGate?.future;+ if (statusFailure case final failure?) throw failure;+ return CliAuthStatus(loggedIn: signedIn);+ }++ @override+ Future<void> login({+ required void Function(String url) onAuthorizeUrl,+ }) async {}++ @override+ void cancel() => cancels++;++ @override+ Future<void> logout() async => logouts++;+}++/// The emailed-code and scanned-QR sign-in, with no service behind it.+class FakeEmailLogin implements EmailCodeLogin {+ final List<String> codesSent = [];+ final List<(String, String)> signIns = [];+ final List<(String, String)> scans = [];++ /// Thrown by the next sign-in when set: a wrong or expired code.+ Object? failure;++ /// Held open until the test completes it.+ Completer<void>? gate;++ @override+ DirectAuth get auth => throw UnimplementedError();++ @override+ Future<void> sendCode(String email) async => codesSent.add(email);++ @override+ Future<void> signIn({required String email, required String code}) async {+ signIns.add((email, code));+ await gate?.future;+ if (failure case final error?) throw error;+ }++ @override+ Future<void> signInWithScan(String code, {required String label}) async {+ scans.add((code, label));+ await gate?.future;+ if (failure case final error?) throw error;+ }+}++/// A viewer's services with every wire faked — see the note at the top.+class FakeViewer implements ViewerServices {+ FakeViewer(AuthSession session)+ : keys = ViewerKeyStore(storage: MemoryKeyValueStore()),+ auth = DirectAuth(+ session: session,+ api: DirectAuthApi(config: AppConfig.dev, dio: FakeHttp({}).dio()),+ emailCodes: EmailCodeApi(+ config: AppConfig.dev,+ dio: FakeHttp({}).dio(),+ ),+ );++ @override+ final ViewerKeyStore keys;++ @override+ final DirectAuth auth;++ @override+ final FakeEmailLogin emailLogin = FakeEmailLogin();++ @override+ DirectLogin get login => throw UnimplementedError('pass a FakeSignIn');++ @override+ DirectLink get links => throw UnimplementedError('pass FakeLinks');++ @override+ RelayCodecFactory get relayCodecs =>+ (_) => throw UnimplementedError('nothing dials');++ @override+ TerminalTransportPluginFactory? get transportPlugins => null;+}++/// Links to machines, answered by the test.+class FakeLinks implements PeerLinkClient {+ CliLinkConnectResult connectResult = const CliLinkConnectResult();+ CliLinkConnectResult codeResult = const CliLinkConnectResult();+ CliLinkListResult listResult = const CliLinkListResult();+ String? unlinkError;++ final List<(String, String)> passwords = [];+ final List<(String, String, String)> codes = [];+ final List<String> unlinked = [];+ int lists = 0;++ @override+ Future<CliLinkConnectResult> connect(+ String machineId,+ String password, {+ void Function(String stage)? onProgress,+ String? displayName,+ }) async {+ passwords.add((machineId, password));+ onProgress?.call('connecting');+ return connectResult;+ }++ @override+ Future<CliLinkConnectResult> connectWithCode(+ String machineId,+ String code, {+ required String label,+ String? displayName,+ }) async {+ codes.add((machineId, code, label));+ return codeResult;+ }++ @override+ Future<CliLinkListResult> list() async {+ lists++;+ return listResult;+ }++ @override+ Future<String?> unlink(String machineId) async {+ unlinked.add(machineId);+ return unlinkError;+ }+}++/// A remote machine as `/api/machines` lists it.+Machine remoteMachine(String id, {String? status = 'online', String? name}) =>+ Machine(+ machineId: id,+ authMode: MachineAuthMode.remote,+ name: name ?? 'Machine $id',+ status: status,+ );++/// An agent as a daemon sends it.+Map<String, dynamic> agentJson(+ String id, {+ String? name,+ String engine = 'claude',+ String? sessionId,+ bool terminal = true,+ String status = 'active',+ String? updatedAt,+ Map<String, dynamic>? extra,+}) => {+ 'id': id,+ 'name': name ?? id,+ 'engine': engine,+ 'sessionId': ?sessionId,+ 'status': status,+ 'updatedAt': ?updatedAt,+ 'project': <String, dynamic>{'name': 'work', 'cwd': '/work'},+ 'terminal': <String, dynamic>{'available': terminal},+ ...?extra,+};++/// What a daemon on a current CLI answers to `terminal_capabilities`.+Map<String, dynamic> capabilities({bool noTakeover = true}) => {+ 'protocolVersion': 3,+ 'backend': 'tmux',+ 'available': true,+ 'features': {+ 'pasteRaw': true,+ 'imagePaste': true,+ 'pasteFile': true,+ 'mediaPreview': true,+ 'projectFolder': true,+ 'noTakeover': noTakeover,+ },+};++/// Everything a [viewerApp] test reaches for.+class ViewerRig {+ ViewerRig({+ required this.app,+ required this.api,+ required this.signIn,+ required this.viewer,+ required this.links,+ required this.conns,+ });++ final AppNotifier app;+ final FakeApi api;+ final FakeSignIn signIn;+ final FakeViewer viewer;+ final FakeLinks links;++ /// One socket per machine id, made the first time the app asks for it.+ final Map<String, ScriptedConn> conns;++ ScriptedConn conn(String machineId) =>+ conns.putIfAbsent(machineId, ScriptedConn.new);+}++/// A phone app — a VIEWER, with no CLI beside it — signed out, on an account+/// whose machines [FakeApi.onMachines] lists.+ViewerRig viewerApp({+ bool signedIn = true,+ MachineCache? machineCache,+ Duration turnActivityTimeout = const Duration(seconds: 12),+}) {+ final session = AuthSession(storage: MemoryKeyValueStore());+ final viewer = FakeViewer(session);+ final signIn = FakeSignIn(signedIn: signedIn);+ final links = FakeLinks();+ final conns = <String, ScriptedConn>{};+ final app = AppNotifier(+ config: AppConfig.dev,+ authSession: session,+ configStore: null,+ cliLogin: signIn,+ cliLink: CliLink(),+ peerLinks: links,+ viewer: viewer,+ machineCache: machineCache,+ turnActivityTimeout: turnActivityTimeout,+ connectionForTest: (machineId) =>+ conns.putIfAbsent(machineId, ScriptedConn.new),+ );+ final api = FakeApi();+ app.api = api;+ return ViewerRig(+ app: app,+ api: api,+ signIn: signIn,+ viewer: viewer,+ links: links,+ conns: conns,+ );+}++/// Lets every pending microtask and zero-length timer run.+Future<void> settle() async {+ for (var i = 0; i < 20; i++) {+ await Future<void>.delayed(Duration.zero);+ }+}