Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Load the workspace independently of account details

dee1c535b3e841e
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index c5d710034..79169d0fb 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -302,6 +302,20 @@ class AppNotifier extends ChangeNotifier {
final Set<String> _offlineRecoveryInFlight = {};
bool _disposed = false;
+ // Account and inventory replies belong to the session that requested them.
+ // Signing out invalidates them before asynchronous connection cleanup.
+ int _authRevision = 0;
+ Future<void>? _profileInFlight;
+
+ bool _authWorkCurrent(int revision) => !_disposed && revision == _authRevision;
+
+ int _invalidateAuthWork() {
+ _profileInFlight = null;
+ _retryInFlight = null;
+ machinesLoading = false;
+ return ++_authRevision;
+ }
+
WsPool? _pool;
late String _autonomousEnv;
String? _lastError;
@@ -1472,6 +1486,8 @@ class AppNotifier extends ChangeNotifier {
/// [recheckEnvironmentStep] can reach the same destination without repeating `bootstrap()`'s config
/// load and update-check startup, which already ran on the launch that got stuck here.
Future<void> _continueAfterEnvironmentReady() async {
+ final revision = _authRevision;
+ if (!_authWorkCurrent(revision)) return;
_cancelEnvironmentRecheckTimer();
status = AppStatus.checkingEnvironment;
notifyListeners();
@@ -1480,6 +1496,7 @@ class AppNotifier extends ChangeNotifier {
// asks the CLI whether this computer is currently signed in.
try {
final authStatus = await cliLogin.checkStatus();
+ if (!_authWorkCurrent(revision)) return;
if (!authStatus.loggedIn) {
currentUser = null;
status = AppStatus.unauthenticated;
@@ -1490,6 +1507,7 @@ class AppNotifier extends ChangeNotifier {
notifyListeners();
await _finishBootstrapSignedIn();
} catch (error, stack) {
+ if (!_authWorkCurrent(revision)) return;
debugPrint(
'continueAfterEnvironmentReady: fallback to login after error: '
'$error\n$stack',
@@ -1698,8 +1716,10 @@ class AppNotifier extends ChangeNotifier {
/// Both `bootstrap()` (already signed in) and `login()` (just finished signing in) land here once
/// the CLI confirms a session exists — ensure the local daemon is actually up first (it does not
/// start on its own, and every call below is a local-CLI-proxied request that needs it), then fetch
- /// the profile and load the machine list over it.
+ /// the profile and machine list independently over it.
Future<void> _finishBootstrapSignedIn() async {
+ final revision = _authRevision;
+ if (!_authWorkCurrent(revision)) return;
// Stays on the pre-navigation `bootstrapping` screen (main.dart) until the daemon is
// confirmed reachable — flipping to `authenticated` any earlier is what let the home UI
// race `harness start`'s own backend handshake and surface a bogus 30s "Could not load
@@ -1713,11 +1733,14 @@ class AppNotifier extends ChangeNotifier {
// for as long as the slowest one takes, and would hand the first-run
// auto-pick a window in which the grid still looks empty.
await _restorePaneLayout();
+ if (!_authWorkCurrent(revision)) return;
await dial.restore();
+ if (!_authWorkCurrent(revision)) return;
_ensurePool();
try {
await ensureCliDaemonReady();
} catch (error) {
+ if (!_authWorkCurrent(revision)) return;
_bootStatusMessage = null;
status = AppStatus.authenticated;
_lastError = '$error';
@@ -1725,19 +1748,24 @@ class AppNotifier extends ChangeNotifier {
notifyListeners();
return;
}
+ if (!_authWorkCurrent(revision)) return;
_bootStatusMessage = null;
// `ensureCliDaemonReady` may have signed the app out instead of succeeding (daemon absent AND
// the saved session gone) — that already routed to the login screen, so don't clobber it.
if (status == AppStatus.unauthenticated) return;
status = AppStatus.authenticated;
- await _loadProfile();
+ notifyListeners();
+ // The CLI has confirmed sign-in and daemon readiness. Display-name/avatar
+ // metadata is independent of machine discovery and must not delay work.
+ unawaited(_loadProfile());
try {
await refreshMachines();
} catch (error) {
+ if (!_authWorkCurrent(revision)) return;
_lastError = 'Could not load machines: $error';
_lastErrorRetryable = true;
}
- notifyListeners();
+ if (_authWorkCurrent(revision)) notifyListeners();
}
/// The local daemon (`harness start`) must be up before any local REST/WS call can work — unlike
@@ -1748,9 +1776,24 @@ class AppNotifier extends ChangeNotifier {
/// retry path, because a boot that found the daemon still connecting now
/// finishes THROUGH the retry path — and a session that never learns its
/// own account has an empty footer and unattributed analytics.
- Future<void> _loadProfile() async {
+ Future<void> _loadProfile() {
+ final pending = _profileInFlight;
+ if (pending != null) return pending;
+ final revision = _authRevision;
+ late final Future<void> load;
+ load = _readProfile(revision).whenComplete(() {
+ if (identical(_profileInFlight, load)) _profileInFlight = null;
+ });
+ _profileInFlight = load;
+ return load;
+ }
+
+ Future<void> _readProfile(int revision) async {
try {
final me = await api.me();
+ if (!_authWorkCurrent(revision) || status != AppStatus.authenticated) {
+ return;
+ }
if (me != null) {
final profile = CurrentUserProfile.fromMe(me);
currentUser = profile;
@@ -1758,15 +1801,20 @@ class AppNotifier extends ChangeNotifier {
// queued while this call was still in flight — the queue reads the
// account per event, not per launch.
analyticsAccount.set(id: profile.id, email: profile.email);
+ notifyListeners();
}
} catch (error) {
- debugPrint('bootstrap: profile unavailable: $error');
+ if (_authWorkCurrent(revision)) {
+ debugPrint('bootstrap: profile unavailable: $error');
+ }
}
}
Future<void> ensureCliDaemonReady() async {
+ final revision = _authRevision;
final discovery = _discovery;
final probe = await discovery.ensureRunning();
+ if (!_authWorkCurrent(revision)) return;
switch (probe.state) {
case LocalCliProbeState.ready:
_cliEndpoint = probe.endpoint;
@@ -1789,7 +1837,9 @@ class AppNotifier extends ChangeNotifier {
// out. "Try running `harness start` yourself" is advice that cannot work in that case — the
// session file is gone, so every start exits again — and it is the advice this branch used to
// give unconditionally.
- if (!(await cliLogin.checkStatus()).loggedIn) {
+ final authStatus = await cliLogin.checkStatus();
+ if (!_authWorkCurrent(revision)) return;
+ if (!authStatus.loggedIn) {
_signedOutAtRuntime(_signedOutMessage);
return;
}
@@ -1880,6 +1930,12 @@ class AppNotifier extends ChangeNotifier {
if (status == AppStatus.unauthenticated) {
return; // idempotent: several sources can race here
}
+ _invalidateAuthWork();
+ currentUser = null;
+ signingIn = false;
+ pendingAuthorizeUrl = null;
+ _awaitingFirstMessage = null;
+ analyticsAccount.clear();
_daemonSupervisionTimer?.cancel();
_daemonSupervisionTimer = null;
_cliEndpoint = null;
@@ -1985,6 +2041,8 @@ class AppNotifier extends ChangeNotifier {
}
Future<void> login() async {
+ if (_disposed || signingIn) return;
+ final revision = _invalidateAuthWork();
_closedHistory.clear();
_lastError = null;
status = AppStatus.bootstrapping;
@@ -1994,6 +2052,7 @@ class AppNotifier extends ChangeNotifier {
try {
await cliLogin.login(
onAuthorizeUrl: (url) {
+ if (!_authWorkCurrent(revision)) return;
pendingAuthorizeUrl = url;
notifyListeners();
// Must be the system browser, not an embedded webview: this SSO page's Google button uses
@@ -2004,13 +2063,16 @@ class AppNotifier extends ChangeNotifier {
);
},
);
+ if (!_authWorkCurrent(revision)) return;
await _finishBootstrapSignedIn();
+ if (!_authWorkCurrent(revision) || status != AppStatus.authenticated) return;
analytics.signedIn();
// Restarts the clock even if `_trackAppOpened` already started one: this
// person met the login screen, so their wait begins where the launch's
// did not.
_armFirstMessage('sign_in');
} catch (error) {
+ if (!_authWorkCurrent(revision)) return;
status = AppStatus.unauthenticated;
_lastError = error.toString();
_lastErrorRetryable = true;
@@ -2023,18 +2085,23 @@ class AppNotifier extends ChangeNotifier {
error is CliNotAvailableException ? 'cli_missing' : 'failed',
);
} finally {
- pendingAuthorizeUrl = null;
// Cleared last, and only here: everything above may still be running when the URL goes, and
// dropping the flag any earlier is what put a bare spinner over the user's own screen.
- signingIn = false;
+ if (_authWorkCurrent(revision)) {
+ pendingAuthorizeUrl = null;
+ signingIn = false;
+ }
}
- notifyListeners();
+ if (_authWorkCurrent(revision)) notifyListeners();
}
/// Aborts an in-flight [login] — the embedded sign-in webview's close button calls this.
void cancelLogin() => cliLogin.cancel();
Future<void> logout() async {
+ final revision = _invalidateAuthWork();
+ signingIn = false;
+ pendingAuthorizeUrl = 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
@@ -2046,8 +2113,10 @@ class AppNotifier extends ChangeNotifier {
// Tiles go, the saved layout stays: signing out and back in is the same
// person at the same desk, and the file is only read once machines exist.
await _closeAllPanes(persist: false);
+ if (!_authWorkCurrent(revision)) return;
_closedHistory.clear();
await _pool?.closeAll();
+ if (!_authWorkCurrent(revision)) return;
_pool = null;
_cliEndpoint = null;
// Nothing to supervise for a signed-out app — and a daemon started by hand
@@ -2184,6 +2253,8 @@ class AppNotifier extends ChangeNotifier {
bool machinesLoading = false;
Future<void> refreshMachines() async {
+ final revision = _authRevision;
+ if (!_authWorkCurrent(revision)) return;
if (localManualFixture != null) {
notifyListeners();
return;
@@ -2193,25 +2264,27 @@ class AppNotifier extends ChangeNotifier {
notifyListeners();
}
try {
- await _refreshMachines();
+ await _refreshMachines(revision);
} finally {
// Said out loud: the list's own notify fires before this, so a flag
// dropped silently here would leave the rail on its placeholders.
- if (machinesLoading) {
+ if (_authWorkCurrent(revision) && machinesLoading) {
machinesLoading = false;
notifyListeners();
}
}
}
- Future<void> _refreshMachines() async {
+ Future<void> _refreshMachines(int revision) async {
final discovery = _discovery;
// The CLI computer id is the local identity source of truth. The loopback
// status endpoint is trusted only when it advertises that same identity.
final localComputerId = await discovery.computerId();
+ if (!_authWorkCurrent(revision)) return;
final localFuture = discovery.discover(expectedComputerId: localComputerId);
final list = await _fetchMachines();
final localEndpoint = await localFuture;
+ if (!_authWorkCurrent(revision)) return;
machines = list
.where((machine) => machine.authMode == MachineAuthMode.remote)
.toList();
@@ -2576,13 +2649,14 @@ class AppNotifier extends ChangeNotifier {
Future<void>? _retryInFlight;
Future<void> retryMachines() {
+ if (_disposed) return Future<void>.value();
final inFlight = _retryInFlight;
if (inFlight != null) return inFlight;
late final Future<void> run;
run = _performRetryMachines().whenComplete(() {
if (identical(_retryInFlight, run)) {
_retryInFlight = null;
- notifyListeners();
+ if (!_disposed) notifyListeners();
}
});
_retryInFlight = run;
@@ -2591,29 +2665,34 @@ class AppNotifier extends ChangeNotifier {
}
Future<void> _performRetryMachines() async {
+ final revision = _authRevision;
+ if (!_authWorkCurrent(revision)) return;
// Re-verify the daemon first: a retry that skips straight to `refreshMachines()` can hit
// the exact same "daemon not connected yet" timeout the button was pressed to escape.
try {
await ensureCliDaemonReady();
} catch (error) {
+ if (!_authWorkCurrent(revision)) return;
_lastError = '$error';
_lastErrorRetryable = true;
notifyListeners();
return;
}
- if (status == AppStatus.unauthenticated) return;
- if (currentUser == null) await _loadProfile();
+ if (!_authWorkCurrent(revision) || status == AppStatus.unauthenticated) return;
+ if (currentUser == null) unawaited(_loadProfile());
try {
await refreshMachines();
+ if (!_authWorkCurrent(revision)) return;
_lastError = null;
} catch (error) {
+ if (!_authWorkCurrent(revision)) return;
_lastError = 'Could not load machines: $error';
_lastErrorRetryable = true;
notifyListeners();
return;
}
await Future.wait(expandedMachines.toList().map(reloadMachineData));
- notifyListeners();
+ if (_authWorkCurrent(revision)) notifyListeners();
}
void toggleExpand(String machineId) {
@@ -2744,6 +2823,7 @@ class AppNotifier extends ChangeNotifier {
MachineState machine, {
bool force = false,
}) async {
+ if (!_machineWorkCurrent(machine, _authRevision)) return;
if (machine.agentLoadStatus == AgentLoadStatus.loaded && !force) return;
if (machine.isLocalMachine && !machine.usesLocalTransport) {
machine.transportMode = MachineTransportMode.localOffline;
@@ -2769,6 +2849,7 @@ class AppNotifier extends ChangeNotifier {
}
Future<void> _performMachineDataLoad(MachineState machine) async {
+ final revision = _authRevision;
final hadAgents = machine.agents.isNotEmpty;
machine.agentsRefreshing = hadAgents;
if (!hadAgents) machine.agentLoadStatus = AgentLoadStatus.loading;
@@ -2781,6 +2862,7 @@ class AppNotifier extends ChangeNotifier {
'agents_list',
timeout: const Duration(seconds: 10),
);
+ if (!_machineWorkCurrent(machine, revision)) return;
final agents = (response['agents'] as List<dynamic>? ?? [])
.map((item) => Agent.fromJson(item as Map<String, dynamic>))
.toList();
@@ -2792,8 +2874,9 @@ class AppNotifier extends ChangeNotifier {
'agents_list success: ${machine.machine.machineId} '
'(${machine.agents.length} agents)',
);
- await _loadTerminalCapabilities(machine, connection);
+ await _loadTerminalCapabilities(machine, connection, revision);
} catch (error) {
+ if (!_machineWorkCurrent(machine, revision)) return;
machine.agentsRefreshing = false;
// A request timing out while the local relay session still nominally reports "connected" means
// the remote node itself has stopped answering — exactly what a REST-status flip to offline
@@ -2824,6 +2907,7 @@ class AppNotifier extends ChangeNotifier {
}
debugPrint('agents_list failed: ${machine.machine.machineId}: $error');
}
+ if (!_machineWorkCurrent(machine, revision)) return;
// Order matters: a restored tile for THIS machine claims its agent before
// the first-run convenience gets to look, so the two can never both open.
_attachPendingPanes(machine);
@@ -2831,6 +2915,10 @@ class AppNotifier extends ChangeNotifier {
notifyListeners();
}
+ bool _machineWorkCurrent(MachineState machine, int revision) =>
+ _authWorkCurrent(revision) &&
+ identical(machineStates[machine.machine.machineId], machine);
+
/// Whether the app has already opened a terminal on its own.
///
/// Once, at startup, and never again: a later refresh must not reopen a
@@ -2920,6 +3008,7 @@ class AppNotifier extends ChangeNotifier {
Future<void> _loadTerminalCapabilities(
MachineState machine,
WsConn connection,
+ int revision,
) async {
try {
final result = await connection.request(
@@ -2927,6 +3016,7 @@ class AppNotifier extends ChangeNotifier {
payload: {'protocolVersion': TerminalSession.protocolVersion},
timeout: const Duration(seconds: 8),
);
+ if (!_machineWorkCurrent(machine, revision)) return;
machine.terminalCapabilityLoaded = true;
machine.terminalCapabilityAvailable =
result['protocolVersion'] == TerminalSession.protocolVersion &&
@@ -2945,6 +3035,7 @@ class AppNotifier extends ChangeNotifier {
machine.mediaPreviewAvailable =
features is Map && features['mediaPreview'] == true;
} catch (_) {
+ if (!_machineWorkCurrent(machine, revision)) return;
machine.terminalCapabilityLoaded = true;
machine.terminalCapabilityAvailable = false;
machine.terminalCapabilityError = 'Could not negotiate terminal protocol';
diff --git a/desktop/test/profile_startup_test.dart b/desktop/test/profile_startup_test.dart
new file mode 100644
index 000000000..35babe4bc
--- /dev/null
+++ b/desktop/test/profile_startup_test.dart
@@ -0,0 +1,423 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/analytics/analytics.dart';
+import 'package:harness/api/api_client.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/auth/cli_login.dart';
+import 'package:harness/bootstrap/environment_provisioner.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/ws/local_cli_discovery.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+class _Api extends ApiClient {
+ _Api() : super(config: AppConfig.dev, session: AuthSession());
+ final profiles = <Completer<Map<String, dynamic>?>>[];
+ final lists = <Completer<List<Machine>>>[];
+
+ @override
+ Future<Map<String, dynamic>?> me() {
+ final result = Completer<Map<String, dynamic>?>();
+ profiles.add(result);
+ return result.future;
+ }
+
+ @override
+ Future<List<Machine>> machines() {
+ final result = Completer<List<Machine>>();
+ lists.add(result);
+ return result.future;
+ }
+}
+
+class _Cli extends CliLogin {
+ @override
+ Future<CliAuthStatus> checkStatus() async =>
+ const CliAuthStatus(loggedIn: true);
+
+ @override
+ Future<void> login({void Function(String url)? onAuthorizeUrl}) async {}
+
+ @override
+ Future<void> logout() async {}
+}
+
+class _Environment extends EnvironmentProvisioner {
+ @override
+ Future<EnvironmentReadiness> ensureReady({
+ required void Function(EnvironmentReadiness value) onProgress,
+ EnvironmentReadiness? resumeFrom,
+ bool install = true,
+ EnvironmentSetupMode? mode,
+ }) async {
+ expect(install, isFalse);
+ final ready = EnvironmentReadiness(
+ steps: {
+ for (final step in EnvironmentStep.values)
+ step: EnvironmentStepStatus.ready,
+ },
+ systemReady: true,
+ phase: EnvironmentSetupPhase.ready,
+ );
+ onProgress(ready);
+ return ready;
+ }
+}
+
+class _Discovery extends LocalCliDiscovery {
+ _Discovery() : super(config: AppConfig.dev);
+ @override
+ Future<String?> computerId() async => null;
+ @override
+ Future<LocalCliEndpoint?> discover({String? expectedComputerId}) async =>
+ null;
+}
+
+class _Connection extends WsConn {
+ _Connection()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'fixture',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ Completer<Map<String, dynamic>>? agents;
+ Completer<Map<String, dynamic>>? capabilities;
+ final requests = <String>[];
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ requests.add(type);
+ return switch (type) {
+ 'agents_list' => await agents?.future ?? _agents,
+ 'terminal_capabilities' => await capabilities?.future ?? _capabilities,
+ _ => throw StateError('Unexpected fixture request: $type'),
+ };
+ }
+}
+
+class _App extends AppNotifier {
+ _App(_Api api, _Connection connection)
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ cliLogin: _Cli(),
+ environmentProvisioner: _Environment(),
+ localCliDiscovery: _Discovery(),
+ connectionForTest: (_) => connection,
+ ) {
+ this.api = api;
+ }
+ int daemonChecks = 0;
+ Completer<void>? daemon;
+ @override
+ Future<void> ensureCliDaemonReady() async {
+ daemonChecks++;
+ await daemon?.future;
+ }
+}
+
+const _machine = Machine(
+ machineId: 'fixture',
+ name: 'Test computer',
+ authMode: MachineAuthMode.remote,
+ status: 'online',
+);
+
+const _agents = {
+ 'agents': [
+ {'id': 'synthetic-agent', 'name': 'Synthetic task', 'engine': 'codex'},
+ ],
+};
+const _capabilities = {
+ 'protocolVersion': 3,
+ 'backend': 'tmux',
+ 'available': true,
+};
+
+Map<String, dynamic> _profile(String id) => {
+ 'user': {'id': id, 'email': '[email protected]'},
+};
+
+Future<void> _tick() => Future<void>.delayed(Duration.zero);
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late _Api api;
+ late _App app;
+ late _Connection connection;
+ var disposed = false;
+ void disposeApp() {
+ if (disposed) return;
+ disposed = true;
+ app.dispose();
+ }
+
+ setUp(() {
+ disposed = false;
+ api = _Api();
+ connection = _Connection();
+ app = _App(api, connection);
+ analyticsAccount.clear();
+ });
+ tearDown(() {
+ disposeApp();
+ analyticsAccount.clear();
+ });
+
+ for (final signingIn in [false, true]) {
+ test(
+ '${signingIn ? 'sign-in' : 'launch'} loads agents while profile is pending',
+ () async {
+ var finished = false;
+ var sawWorkspace = false;
+ app.addListener(() {
+ if (app.status == AppStatus.authenticated) sawWorkspace = true;
+ });
+ final start = (signingIn ? app.login() : app.bootstrap()).then(
+ (_) => finished = true,
+ );
+ await Future<void>.delayed(Duration.zero);
+ final startedMachinesBeforeProfile = api.lists.isNotEmpty;
+ if (api.lists.isNotEmpty) api.lists.single.complete([_machine]);
+ await Future<void>.delayed(Duration.zero);
+ final machine = app.machineStates['fixture'];
+ final agentsBeforeProfile = machine?.agents.length ?? 0;
+ final capabilitiesBeforeProfile = machine?.terminalCapabilityAvailable;
+ final finishedBeforeProfile = finished;
+ final workspaceBeforeProfile = sawWorkspace;
+ api.profiles.single.complete(null);
+ await Future<void>.delayed(Duration.zero);
+ for (final list in api.lists.where((c) => !c.isCompleted)) {
+ list.complete([_machine]);
+ }
+ await start;
+ await Future<void>.delayed(Duration.zero);
+ expect(app.daemonChecks, 1);
+ expect(startedMachinesBeforeProfile, isTrue);
+ expect(agentsBeforeProfile, 1);
+ expect(capabilitiesBeforeProfile, isTrue);
+ expect(workspaceBeforeProfile, isTrue);
+ expect(finishedBeforeProfile, isTrue);
+ },
+ );
+ }
+
+ test('refresh recovery does not wait for the account profile', () async {
+ app.status = AppStatus.authenticated;
+ var finished = false;
+ final refresh = app.retryMachines().then((_) => finished = true);
+ await Future<void>.delayed(Duration.zero);
+ final started = api.lists.isNotEmpty;
+ if (started) api.lists.single.complete([]);
+ await Future<void>.delayed(Duration.zero);
+ final finishedBeforeProfile = finished;
+ api.profiles.single.complete(null);
+ await Future<void>.delayed(Duration.zero);
+ for (final list in api.lists.where((c) => !c.isCompleted)) {
+ list.complete([]);
+ }
+ await refresh;
+ expect(started, isTrue);
+ expect(finishedBeforeProfile, isTrue);
+ expect(app.machinesRefreshing, isFalse);
+ });
+
+ test('a late profile response cannot restore a signed-out account', () async {
+ final start = app.login();
+ await Future<void>.delayed(Duration.zero);
+ await app.logout();
+ api.profiles.single.complete(_profile('old-account'));
+ await Future<void>.delayed(Duration.zero);
+ for (final list in api.lists.where((c) => !c.isCompleted)) {
+ list.complete([_machine]);
+ }
+ await start;
+ expect(app.status, AppStatus.unauthenticated);
+ expect(app.currentUser, isNull);
+ expect(analyticsAccount.current.id, isNull);
+ expect(app.machines, isEmpty);
+ expect(connection.requests, isEmpty);
+ });
+
+ test(
+ 'a late profile publishes account details without reloading agents',
+ () async {
+ final start = app.login();
+ await _tick();
+ api.lists.single.complete([_machine]);
+ await start;
+ await _tick();
+ expect(app.currentUser, isNull);
+ expect(app.machineStates['fixture']!.agents, hasLength(1));
+ var profileNotifications = 0;
+ app.addListener(() {
+ if (app.currentUser != null) profileNotifications++;
+ });
+ api.profiles.single.complete(_profile('current'));
+ await _tick();
+ expect(profileNotifications, 1);
+ expect(app.currentUser!.id, 'current');
+ expect(analyticsAccount.current.id, 'current');
+ expect(api.lists, hasLength(1));
+ expect(
+ connection.requests.where((r) => r == 'agents_list'),
+ hasLength(1),
+ );
+ },
+ );
+
+ test(
+ 'repeated refreshes share a pending profile and retry a failed one',
+ () async {
+ app.status = AppStatus.authenticated;
+ for (var i = 0; i < 2; i++) {
+ final refresh = app.retryMachines();
+ await _tick();
+ expect(api.profiles, hasLength(1));
+ api.lists[i].complete([]);
+ await refresh;
+ }
+ api.profiles.single.completeError(StateError('Profile unavailable'));
+ await _tick();
+ expect(app.currentUser, isNull);
+ expect(app.lastError, isNull);
+ final recovery = app.retryMachines();
+ await _tick();
+ expect(api.profiles, hasLength(2));
+ api.profiles.last.complete(_profile('recovered'));
+ api.lists.last.complete([]);
+ await recovery;
+ await _tick();
+ expect(app.currentUser!.id, 'recovered');
+ },
+ );
+
+ test(
+ 'old sign-in completion cannot replace a new account or its loading state',
+ () async {
+ final oldLogin = app.login();
+ await _tick();
+ await app.logout();
+ final newLogin = app.login();
+ await _tick();
+ expect(api.profiles, hasLength(2));
+ expect(api.lists, hasLength(2));
+ api.profiles.first.complete(_profile('old'));
+ api.lists.first.complete([_machine]);
+ await oldLogin;
+ expect(app.signingIn, isTrue);
+ expect(app.machinesLoading, isTrue);
+ expect(app.currentUser, isNull);
+ expect(app.machines, isEmpty);
+ api.profiles.last.complete(_profile('new'));
+ api.lists.last.complete([]);
+ await newLogin;
+ await _tick();
+ expect(app.currentUser!.id, 'new');
+ expect(analyticsAccount.current.id, 'new');
+ expect(app.signingIn, isFalse);
+ expect(app.machinesLoading, isFalse);
+ },
+ );
+
+ test(
+ 'signing out during daemon readiness prevents workspace loading',
+ () async {
+ app.daemon = Completer<void>();
+ final start = app.login();
+ await _tick();
+ expect(app.daemonChecks, 1);
+ await app.logout();
+ app.daemon!.complete();
+ await start;
+ expect(app.status, AppStatus.unauthenticated);
+ expect(api.profiles, isEmpty);
+ expect(api.lists, isEmpty);
+ },
+ );
+
+ test(
+ 'closing the app discards pending profile and machine responses',
+ () async {
+ final start = app.login();
+ await _tick();
+ disposeApp();
+ api.profiles.single.complete(_profile('closed'));
+ api.lists.single.complete([_machine]);
+ await start;
+ await _tick();
+ expect(app.currentUser, isNull);
+ expect(app.machines, isEmpty);
+ expect(analyticsAccount.current.id, isNull);
+ expect(connection.requests, isEmpty);
+ },
+ );
+
+ test(
+ 'closing the app during refresh does not publish its completion',
+ () async {
+ app.status = AppStatus.authenticated;
+ final refresh = app.retryMachines();
+ await _tick();
+ disposeApp();
+ api.profiles.single.complete(null);
+ api.lists.single.complete([_machine]);
+ await refresh;
+ expect(app.machines, isEmpty);
+ expect(app.machinesRefreshing, isFalse);
+ expect(connection.requests, isEmpty);
+ },
+ );
+
+ for (final closeApp in [false, true]) {
+ for (final request in ['agents_list', 'terminal_capabilities']) {
+ test(
+ '${closeApp ? 'close' : 'sign-out'} discards a late $request reply',
+ () async {
+ final pending = Completer<Map<String, dynamic>>();
+ if (request == 'agents_list') {
+ connection.agents = pending;
+ } else {
+ connection.capabilities = pending;
+ }
+ final start = app.login();
+ await _tick();
+ api.profiles.single.complete(null);
+ api.lists.single.complete([_machine]);
+ await start;
+ await _tick();
+ expect(connection.requests, contains(request));
+ final machine = app.machineStates['fixture']!;
+ final load = machine.agentsLoadInFlight!;
+ if (closeApp) {
+ disposeApp();
+ } else {
+ await app.logout();
+ }
+ pending.complete(request == 'agents_list' ? _agents : _capabilities);
+ await load;
+ expect(machine.terminalCapabilityLoaded, isFalse);
+ expect(app.panes, isEmpty);
+ if (request == 'agents_list') {
+ expect(machine.agents, isEmpty);
+ expect(
+ connection.requests,
+ isNot(contains('terminal_capabilities')),
+ );
+ }
+ },
+ );
+ }
+ }
+}
diff --git a/docs/harness-v2-appearance-onboarding.md b/docs/harness-v2-appearance-onboarding.md
index 69ef0abee..b8015c6e9 100644
--- a/docs/harness-v2-appearance-onboarding.md
+++ b/docs/harness-v2-appearance-onboarding.md
@@ -28,6 +28,14 @@ New swarm and Search remain disabled until the workspace enables them. Repeated
The window setup future now awaits configure, show and focus requests directly. The installed window library's callback is synchronous and previously allowed that future to report completion before its async native work finished. Delayed-reply checks reproduced the issue; error responses now reach the awaited setup call. These checks exercise actual Dart request ordering and a hidden AppKit window. Live first-frame presentation and macOS foreground activation remain unmeasured.
+## Reaching the workspace while account details load
+
+The startup audit found that both sign-in and refresh waited for `/api/auth/me` before requesting machines. That profile supplies display identity; CLI authentication and daemon readiness are already confirmed separately. Account details now load alongside machine discovery. The workspace can show available agents and their terminal capability state while the profile remains pending, and the account updates when its response arrives.
+
+Repeated refreshes share a pending profile request, and a failed profile can be retried without holding up machine recovery. Session ownership checks discard late responses after sign-out, replacement sign-in or disposal. They also cover downstream agent and capability loading, so an old request cannot reattach an agent after its workspace has gone.
+
+Fourteen isolated profile/startup lifecycle checks and the existing first-run/machine suites pass: 118 focused tests in total. These establish request independence, notification and recovery behavior with synthetic data. They do not measure real sign-in duration, network latency or user activation.
+
## Onboarding evidence and direction
| Primary source | Observed behavior | Harness adaptation |
diff --git a/docs/harness-v2-performance.md b/docs/harness-v2-performance.md
index 61ffefe70..39a495daa 100644
--- a/docs/harness-v2-performance.md
+++ b/docs/harness-v2-performance.md
@@ -10,6 +10,14 @@ flutter test --no-pub --reporter expanded test/benchmarks/swarm_benchmark.dart
It prints `SWARM_BENCH` JSON records. Its filename deliberately does not end in `_test.dart`, so ordinary correctness runs do not include timing measurements.
+## Workspace discovery without a profile dependency (2026-09-13)
+
+After CLI sign-in and daemon readiness, machine discovery used to wait for the account profile. Refresh recovery repeated that dependency whenever no profile was known. The requests now run independently; only one profile request is kept in flight, and a completed response updates the account separately. A failed profile does not delay machine error recovery or require another sign-in.
+
+The regression fixture leaves the profile unresolved and verifies that launch/sign-in finish, machine inventory and agent capabilities arrive, and refresh completes. It also verifies late account notification, a subsequent profile retry and discarded responses after sign-out/disposal. The initial four regressions failed against the previous code; all 118 affected startup and workspace checks now pass. Logs: `/private/tmp/harness-v2-profile-startup-{before,tests}.log`.
+
+This removes a serial dependency; it is not a timed benchmark or a claim of a fixed amount saved. The production API's existing receive timeout is 30 seconds, but the fixture does not simulate that as an observed user delay. Real native launch, provider sign-in and time to first useful agent remain separate measurements.
+
## Persisted settings initialization (2026-09-13)
The font and appearance stores previously restored five keys with five separate file-lock, permission-check and JSON-read cycles. Each group now uses one requested-key snapshot, reducing that work to two cycles. File locking, private permissions, corrupt-file quarantine and future-schema protection remain in the same storage path. Snapshots are not cached; an intervening write is visible to the next read, including writes through another store instance. No unrelated credential keys are returned to the preference stores.
diff --git a/docs/harness-v2-progress.md b/docs/harness-v2-progress.md
index 25a8c3595..639e918c9 100644
--- a/docs/harness-v2-progress.md
+++ b/docs/harness-v2-progress.md
@@ -2,6 +2,15 @@
Updated 2026-09-13 with coordinated palettes, Models, combined closed-work History and faster unified search. This is a working preview, not a release.
+## Workspace startup and profile checkpoint
+
+- Launch, sign-in and Cmd-R recovery now load machines independently of account display metadata. The CLI still confirms authentication and daemon readiness first. A pending profile no longer holds the workspace or refresh future; a successful profile publishes its account details when it arrives.
+- Concurrent refreshes reuse one pending profile request. Profile failure leaves machine loading/recovery available, and a subsequent refresh can retry missing account details. No extra polling or automatic agent input was added.
+- Signing out invalidates pending account and inventory work before asynchronous cleanup. Late sign-in, profile, machine and terminal-capability replies cannot restore the old account, open old agents, clear a newer session's loading state or notify a disposed app. Runtime sign-out clears displayed account identity as well.
+- The original four profile/startup regressions failed before the fix (`/private/tmp/harness-v2-profile-startup-before.log`). A separate refresh-after-close check reproduced a disposed-notifier error (`/private/tmp/harness-v2-profile-refresh-close-before.log`). **118 focused tests now pass**, including 14 profile/startup lifecycle checks and existing daemon, environment, login, first-workspace, machine refresh and closed-work restoration coverage (`/private/tmp/harness-v2-profile-startup-tests.log`).
+- Analyzer has zero errors/warnings and the existing 12 vendored infos (`/private/tmp/harness-v2-profile-startup-analyze.log`). Fixtures use pending scripted responses, synthetic accounts and an isolated transport. This verifies removal of a dependency, not a measured reduction in cold launch or first-agent latency. No provider sign-in or real agent input was used.
+- Public-origin approval is still pending. Preserve the unrelated first-agent naming edits, collaboration draft and native benchmark directory. Native foreground/capture validation still needs new access evidence; do not retry the same failed calibration.
+
## Native startup appearance checkpoint
- The loaded palette now reaches native titlebar configuration before the explicit show request, including startup and sign-in where no Swarm screen exists yet. Native New swarm and Search controls begin disabled; a palette update neither creates tabs nor enables workspace actions.