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.

Merge branch 'main' into feat/mobile-ios-android

Dev jacob7dc68ee3b1a9
diff --cc cli/src/lib/e2ee/core.test.ts
index b9441a126,2e53a2808..341c8461a
--- a/cli/src/lib/e2ee/core.test.ts
+++ b/cli/src/lib/e2ee/core.test.ts
@@@ -137,11 -137,10 +137,14 @@@ describe('e2ee core — codes + fingerp
// A machine's account usage names what the person spends and on whose subscription. Missing from
// either list the request would not fail — it would time out, which is harder to find.
expect(C.isEncryptedDownType('usage_read')).toBe(true)
+ // The whole p2p signaling exchange, cutover included — see the set's own comment.
+ for (const type of ['p2p_offer', 'p2p_answer', 'p2p_ice_candidate', 'p2p_abort', 'p2p_promote']) {
+ expect(C.isEncryptedDownType(type)).toBe(true)
+ }
expect(C.isEncryptedRpcResultType('usage_read_result')).toBe(true)
+ // The desktop's pane colours ride the same path; a miss here is the same silent timeout.
+ expect(C.isEncryptedDownType('theme_set')).toBe(true)
+ expect(C.isEncryptedRpcResultType('theme_set_result')).toBe(true)
expect(C.ENCRYPTED_RPC_RESULT_TYPES.has('session_get_result')).toBe(true)
expect(C.ENCRYPTED_RPC_RESULT_TYPES.has('agents_list_result')).toBe(true)
expect(C.ENCRYPTED_RPC_RESULT_TYPES.has('agent_update_result')).toBe(true)
@@@ -207,6 -206,6 +210,6 @@@ describe('e2ee core — interop keyston
it('core.ts still hashes to the pinned value shared with the other implementations', () => {
const here = dirname(fileURLToPath(import.meta.url))
const actual = createHash('sha256').update(readFileSync(join(here, 'core.ts'))).digest('hex')
- expect(actual).toBe('d3c8e0a38615d188502946d10330884eb2ca85a10f0d1f5ecb1f74a5fa2af1fe')
- expect(actual).toBe('84cb86ec25470ed2a573f13381f077f2b27a56f4396eccf5a0408d1a2266d476')
++ expect(actual).toBe('8ddeee04b79ee06a99bbdc18855404cc74b2caaa59b06d8b028c1acfbd2623ab')
})
})
diff --cc desktop/lib/api/api_client.dart
index cd17ca6a5,46a895236..b3b5178b9
--- a/desktop/lib/api/api_client.dart
+++ b/desktop/lib/api/api_client.dart
@@@ -52,9 -50,16 +52,16 @@@ class ApiClient
}
// -- machines (control plane, proxied by the local CLI) --
+ /// Whether the last [machines] answer came from the daemon's cache rather than the backend.
+ ///
+ /// The daemon answers 200 with the last known-good list when the backend leg is unreachable, so a
+ /// caller that only checked the status code would mistake an outage for a healthy, current read.
+ bool lastMachinesStale = false;
+
Future<List<Machine>> machines() async {
final res = await _dio.get('/api/machines');
- final data = _unwrap(res) as Map<String, dynamic>;
+ final data = unwrapApiResponse(res) as Map<String, dynamic>;
+ lastMachinesStale = data['stale'] == true;
final list = data['machines'] as List<dynamic>? ?? [];
return list
.map((e) => Machine.fromJson(e as Map<String, dynamic>))
@@@ -95,24 -100,21 +102,39 @@@ bool isUnauthorizedError(Object error)
error is DioException && error.response?.statusCode == 401 ||
error is ApiException && error.status == 401;
+/// Unwraps the backend's `{success, data, error}` envelope, which both legs
+/// speak: the CLI's loopback server mirrors it, and the viewer's own auth calls
+/// (`viewer/direct_auth_api.dart`) read it straight from the backend.
+dynamic unwrapApiResponse(Response res) {
+ final body = res.data;
+ if (body is Map && body['success'] == true) {
+ return body['data'];
+ }
+ final error = body is Map ? body['error'] : null;
+ final serverMessage = error is Map ? error['message'] : null;
+ throw ApiException(
+ serverMessage is String && serverMessage.isNotEmpty
+ ? serverMessage
+ : 'Request failed (${res.statusCode})',
+ status: res.statusCode,
+ );
+}
+
+ /// The local daemon can answer normally while its separate backend request fails.
+ /// Those gateway errors need recovery just as a broken loopback connection does.
+ bool isTransientApiError(Object error) {
+ if (error is ApiException) {
+ return const {502, 503, 504}.contains(error.status);
+ }
+ return error is DioException &&
+ const {
+ DioExceptionType.connectionError,
+ DioExceptionType.connectionTimeout,
+ DioExceptionType.sendTimeout,
+ DioExceptionType.receiveTimeout,
+ }.contains(error.type);
+ }
+
/// The sentence a failed local-CLI call earns on an error strip. A raw
/// `DioException` is a paragraph about `RequestOptions.receiveTimeout` — true,
/// and useless to the person reading it: what they need is which leg failed.
diff --cc desktop/lib/state/app_state.dart
index 285c099a6,fb7f75297..adee97154
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@@ -3,8 -3,12 +3,11 @@@ import 'dart:io' show exit, pid
import 'dart:math' show Random;
import 'package:dio/dio.dart';
+
+ import 'dart:ui' show Color;
+
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
-import 'package:url_launcher/url_launcher.dart';
import '../analytics/analytics.dart';
import '../api/api_client.dart';
@@@ -1087,29 -1086,35 +1103,48 @@@ class AppNotifier extends ChangeNotifie
// without one (the tests) nothing is written anywhere.
dial = DialState(paneLayoutStore?.storage),
agentPreference = AgentPreference(paneLayoutStore?.storage),
+ projectHistory = ProjectHistory(paneLayoutStore?.storage),
session = authSession,
_store = configStore,
- cliLogin = cliLogin ?? CliLogin(),
cliLink = cliLink ?? CliLink(),
- config = configStore?.config ?? config {
+ config = configStore?.config ?? config,
+ viewer =
+ viewer ??
+ (kViewerMode
+ ? ViewerServices(
+ config: configStore?.config ?? config,
+ session: authSession,
+ )
+ : null) {
+ this.cliLogin = cliLogin ?? this.viewer?.login ?? CliLogin();
+ this.peerLinks = peerLinks ?? this.viewer?.links ?? this.cliLink;
_autonomousEnv = this.config.autonomousEnv;
- api = ApiClient(config: this.config, session: session);
+ api = _newApiClient();
+ // `grid.AppTheme.palette`, not the prefs store: main.dart copies the saved
+ // choice into the palette notifier while rebuilding, so the store fires
+ // before the colours the panes actually use have moved.
+ grid.AppTheme.palette.addListener(_announceTerminalThemeEverywhere);
+ terminalThemeStore.addListener(_announceTerminalThemeEverywhere);
}
+ /// Through the local CLI in a desktop build; straight to the backend, signed, in a viewer.
+ ApiClient _newApiClient() =>
+ ApiClient(config: config, session: session, auth: viewer?.auth);
+
String? get lastError => _lastError;
+
+ /// The machine list's own failure, separate from [lastError] — that slot is shared with agent-launch
+ /// and other one-off errors, and is cleared by [dismissError]. A pane asking "is this machine missing
+ /// because we could not read the list?" needs the narrower question.
+ String? get machineListError => _machineLoadError;
+
+ /// True when the machine list on screen came from the daemon's cache because the backend could not be
+ /// reached. The rows are the last known-good ones, not current.
+ bool machinesAreStale = false;
+
+ /// Whether a machine-list recovery is armed. Mirrors [environmentRecheckPending] — the honest way for a
+ /// test to ask "is this still trying?" without reaching into a private timer.
+ bool get machineRecoveryPending => _machineRecoveryTimer != null;
bool get lastErrorRetryable => _lastErrorRetryable;
String? get bootStatusMessage => _bootStatusMessage;
@@@ -2655,20 -2714,122 +2784,127 @@@
}
}
+ void _stopMachineRecovery() {
+ _machineRecoveryTimer?.cancel();
+ _machineRecoveryTimer = null;
+ _machineRecoveryAttempts = 0;
+ }
+
+ void _scheduleMachineRecovery(int revision) {
+ if (!_authWorkCurrent(revision) ||
+ status != AppStatus.authenticated ||
+ _machineRecoveryTimer != null) {
+ return;
+ }
+ const seconds = [2, 4, 8, 16, 30];
+ final delay = seconds[_machineRecoveryAttempts];
+ if (_machineRecoveryAttempts < seconds.length - 1) {
+ _machineRecoveryAttempts++;
+ }
+ _machineRecoveryTimer = Timer(Duration(seconds: delay), () {
+ _machineRecoveryTimer = null;
+ if (_authWorkCurrent(revision) && status == AppStatus.authenticated) {
+ unawaited(
+ _retryMachines(automatic: true).whenComplete(() {
+ // A timer can join a manual retry already in progress. Keep recovering if that run
+ // stopped at the daemon gate; success and non-transient errors reset the counter.
+ if (_machineRecoveryAttempts > 0) {
+ _scheduleMachineRecovery(revision);
+ }
+ }),
+ );
+ }
+ });
+ }
+
+ void _reportMachineLoadError(Object error, {bool automatic = false}) {
+ final message = 'Could not load machines: ${describeApiError(error)}';
+ // A recovery must not replace a later agent error or redisplay a dismissed strip.
+ if (!automatic || (_lastError != null && _lastError == _machineLoadError)) {
+ _lastError = message;
+ _lastErrorRetryable = true;
+ }
+ _machineLoadError = message;
+ }
+
+ /// What the loopback probe means for one machine's transport.
+ ///
+ /// Written once because two callers need the same answer: the refresh loop, and the failure path that
+ /// keeps this computer usable when the backend list could not be read.
+ void _applyLocalTransport(
+ MachineState state,
+ LocalCliEndpoint? localEndpoint,
+ String? localComputerId,
+ ) {
+ if (state.localOnly && localEndpoint?.computerId == localComputerId) {
+ state.localEndpoint = localEndpoint;
+ state.transportMode = state.connectionStatus == ConnectionStatus.connected
+ ? MachineTransportMode.localPlaintext
+ : MachineTransportMode.localOffline;
+ } else if (state.localOnly) {
+ // The token still identifies this as local, but the CLI is offline or
+ // failed its identity/capability check. Never fall back to cloud E2EE.
+ state.localEndpoint = null;
+ state.transportMode = MachineTransportMode.localOffline;
+ state.nodeOnline = false;
+ _startOfflineRetry(state);
+ } else {
+ state.localEndpoint = null;
+ state.transportMode = MachineTransportMode.cloudE2ee;
+ }
+ }
+
Future<void> _refreshMachines(int revision) async {
- final discovery = _discovery;
+ // No machine is "this computer" to a viewer, which has no local CLI: every one — even the one
+ // it runs on — is reached through the relay.
+ final discovery = viewer == null ? _discovery : null;
// 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();
+ final localComputerId = await discovery?.computerId();
if (!_authWorkCurrent(revision)) return;
- final localFuture = discovery.discover(expectedComputerId: localComputerId);
++ // Null in a viewer build, which has no local CLI to probe — see `discovery` above.
+ final localFuture =
+ discovery?.discover(expectedComputerId: localComputerId) ??
+ Future<LocalCliEndpoint?>.value();
- final list = await _fetchMachines();
- final localEndpoint = await localFuture;
+ // The two legs stay independent. The loopback probe reads a local file and asks 127.0.0.1, so it
+ // cannot fail for a network reason — but awaiting it BEHIND the backend call meant a cloud outage
+ // threw first and threw away an answer that was already correct, while awaiting it FIRST would let a
+ // slow probe hold up the list. Latch it as it lands instead, and use it on both paths.
+ LocalCliEndpoint? probed;
+ final localSettled = localFuture.then((value) => probed = value).catchError(
+ (Object error) {
+ // A probe that fails is the CLI being unreachable, which the transport decision below already
+ // handles — but swallowing it silently leaves nothing to diagnose from.
+ debugPrint('local CLI probe failed: $error');
+ return null;
+ },
+ );
+ final List<Machine> list;
+ try {
+ list = await _fetchMachines();
+ machinesAreStale = api.lastMachinesStale;
+ } catch (_) {
+ // A backend outage must not cost this computer its own transport. Without this the probe result
+ // stayed unapplied, so `usesLocalTransport` went false and `_connectMachine` skipped the local
+ // machine — while relayed machines, which never consult it, kept streaming. That asymmetry was the
+ // bug: the local terminal stopped rendering and the relayed ones did not.
+ await localSettled;
+ if (_authWorkCurrent(revision)) {
+ final endpoint = probed;
+ for (final state in machineStates.values) {
+ _applyLocalTransport(state, endpoint, localComputerId);
+ _connectMachine(state);
+ }
+ if (endpoint != null) _updateLocalProjectSnapshot(endpoint);
+ notifyListeners();
+ }
+ rethrow; // the recovery timer owns the retry; this only protects what already works
+ }
+ await localSettled;
+ // Both legs are in: this is the one gate that decides whether a result that arrived after a
+ // sign-out or a dispose may still be published.
if (!_authWorkCurrent(revision)) return;
+ final localEndpoint = probed;
machines = list
.where((machine) => machine.authMode == MachineAuthMode.remote)
.toList();