fix(studio): connect to the active channel, not hard-coded :50051
Some checks failed
Security / Security check (push) Failing after 1s

Studio defaulted its endpoint to the local channel's port (:50051), but
a curl|sh user is on the production channel (:50071) — so the sidebar
probed a different daemon than the Diagnose page reported, showing
'connected' next to 'production daemon stopped'. On first run Studio now
reads ~/.chain/current-channel (+ run/<ch>.endpoint) and follows the
active channel; an explicit Settings endpoint still wins and persists,
auto-discovery does not (re-follows the channel each launch). The
connection caption now names the channel ('Connected · production') so
it can never look contradictory again.

Signed-off-by: flemming-it <stefan.a.flemming@googlemail.com>
This commit is contained in:
flemming-it 2026-06-18 13:52:05 +02:00
parent 5f56abcf5f
commit cb130b2f03
2 changed files with 121 additions and 17 deletions

View file

@ -5,6 +5,7 @@
// Methods return UI-friendly types so pages stay free of // Methods return UI-friendly types so pages stay free of
// protobuf imports. // protobuf imports.
import 'dart:io';
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:chain_client_sdk/chain_client_sdk.dart'; import 'package:chain_client_sdk/chain_client_sdk.dart';
@ -28,10 +29,79 @@ class HubService {
HubEndpoint get currentEndpoint => _client.endpoint; HubEndpoint get currentEndpoint => _client.endpoint;
/// The channel Studio is connected to, discovered from
/// `~/.chain/current-channel` when no explicit endpoint was set.
/// Shown next to the connection caption so "connected" names which
/// daemon never contradicting the Diagnose page again.
String? activeChannel;
/// Best-effort name of the channel the current endpoint targets,
/// matched by its well-known port (50071 production). Falls back to
/// the auto-discovered channel. `null` for a custom host/port.
String? get connectedChannelName {
final port = _client.endpoint.port;
for (final e in _channelPorts.entries) {
if (e.value == port) return e.key;
}
return activeChannel;
}
static const _kHostKey = 'hub.host'; static const _kHostKey = 'hub.host';
static const _kPortKey = 'hub.port'; static const _kPortKey = 'hub.port';
static const _kSecureKey = 'hub.secure'; static const _kSecureKey = 'hub.secure';
/// gRPC default ports per channel (mirror of the Rust
/// `Channel::default_port`). Used as the fallback when the daemon
/// has not written its `run/<channel>.endpoint` file yet.
static const _channelPorts = {
'local': 50051,
'dev': 50041,
'beta': 50061,
'production': 50071,
};
/// The endpoint of the channel the operator is actually on, read
/// from `~/.chain` (the hub writes `current-channel` and, when a
/// daemon is up, `run/<channel>.endpoint`). Lets a fresh Studio
/// follow the installed channel a `curl | sh` user lands on
/// `production` (:50071), not the hard-coded local :50051. Returns
/// null when it cannot be determined (then we keep the default).
static ({String channel, HubEndpoint endpoint})? _discoverActiveChannel() {
try {
final home = Platform.environment['HOME'] ??
Platform.environment['USERPROFILE'];
if (home == null || home.isEmpty) return null;
final sep = Platform.pathSeparator;
final base = '$home$sep.chain';
final ccFile = File('$base${sep}current-channel');
final channel =
ccFile.existsSync() ? ccFile.readAsStringSync().trim() : 'local';
if (channel.isEmpty) return null;
// Prefer the actual bound endpoint the daemon wrote.
final epFile = File('$base${sep}run$sep$channel.endpoint');
if (epFile.existsSync()) {
final raw =
epFile.readAsStringSync().trim().replaceFirst(RegExp(r'^\w+://'), '');
final i = raw.lastIndexOf(':');
if (i > 0) {
final host = raw.substring(0, i);
final port = int.tryParse(raw.substring(i + 1));
if (port != null) {
return (channel: channel, endpoint: HubEndpoint(host: host, port: port));
}
}
}
// Fall back to the channel's well-known default port.
return (
channel: channel,
endpoint:
HubEndpoint(host: '127.0.0.1', port: _channelPorts[channel] ?? 50051),
);
} catch (_) {
return null;
}
}
/// Sentinel distinguishing "caller did not pass authToken" /// Sentinel distinguishing "caller did not pass authToken"
/// from "caller passed null to drop the token". /// from "caller passed null to drop the token".
static const Object _unset = Object(); static const Object _unset = Object();
@ -45,32 +115,59 @@ class HubService {
final port = prefs.getInt(_kPortKey); final port = prefs.getInt(_kPortKey);
final secure = prefs.getBool(_kSecureKey); final secure = prefs.getBool(_kSecureKey);
final token = await HubAuthToken.read(); final token = await HubAuthToken.read();
if (host == null && token == null) return;
final endpoint = HubEndpoint( // 1) An endpoint the operator explicitly chose in Settings wins.
host: host ?? _client.endpoint.host, if (host != null) {
port: port ?? _client.endpoint.port, await reconnect(
secure: secure ?? _client.endpoint.secure, HubEndpoint(
); host: host,
await reconnect(endpoint, authToken: token); port: port ?? _client.endpoint.port,
secure: secure ?? false,
),
authToken: token,
);
return;
}
// 2) Otherwise follow the active channel from ~/.chain, so Studio
// connects to the daemon the operator installed (e.g. production
// :50071) instead of the hard-coded local :50051. Not persisted,
// so Studio re-discovers each launch and tracks channel switches.
final discovered = _discoverActiveChannel();
if (discovered != null) {
activeChannel = discovered.channel;
await reconnect(discovered.endpoint, authToken: token, persist: false);
return;
}
// 3) Nothing to discover: keep the default client, apply any token.
if (token != null) {
await reconnect(_client.endpoint, authToken: token, persist: false);
}
} }
/// Reconnect to a new endpoint and persist for next launch. /// Reconnect to a new endpoint. With [persist] (the default) the
/// [authToken] is read from `~/.chain/hub-auth-token` by /// endpoint is saved for next launch that is an explicit operator
/// default pass `null` to drop a previously-loaded token, /// choice. Auto-discovery passes `persist: false` so it never
/// or omit the parameter to keep the current value. /// overwrites a real choice and keeps re-following the active channel.
/// [authToken] is read from `~/.chain/hub-auth-token` by default
/// pass `null` to drop a token, or omit to keep the current value.
Future<void> reconnect( Future<void> reconnect(
HubEndpoint endpoint, { HubEndpoint endpoint, {
Object? authToken = _unset, Object? authToken = _unset,
bool persist = true,
}) async { }) async {
await _client.close(); await _client.close();
final token = identical(authToken, _unset) final token = identical(authToken, _unset)
? await HubAuthToken.read() ? await HubAuthToken.read()
: authToken as String?; : authToken as String?;
_client = HubClient(endpoint: endpoint, authToken: token); _client = HubClient(endpoint: endpoint, authToken: token);
final prefs = await SharedPreferences.getInstance(); if (persist) {
await prefs.setString(_kHostKey, endpoint.host); final prefs = await SharedPreferences.getInstance();
await prefs.setInt(_kPortKey, endpoint.port); await prefs.setString(_kHostKey, endpoint.host);
await prefs.setBool(_kSecureKey, endpoint.secure); await prefs.setInt(_kPortKey, endpoint.port);
await prefs.setBool(_kSecureKey, endpoint.secure);
}
} }
/// Reload the token from disk and reconnect using the current /// Reload the token from disk and reconnect using the current

View file

@ -763,8 +763,11 @@ class _SidebarState extends State<_Sidebar>
Builder( Builder(
builder: (context) { builder: (context) {
final l = AppLocalizations.of(context)!; final l = AppLocalizations.of(context)!;
final ch = HubService.instance.connectedChannelName;
final caption = widget.connected == true final caption = widget.connected == true
? l.connectionConnected ? (ch != null
? '${l.connectionConnected} · $ch'
: l.connectionConnected)
: widget.connected == false : widget.connected == false
? l.connectionTapToStart ? l.connectionTapToStart
: l.connectionConnecting; : l.connectionConnecting;
@ -1127,8 +1130,12 @@ class _ConnectionLabel extends StatelessWidget {
final captionColor = connected == false final captionColor = connected == false
? theme.colorScheme.error ? theme.colorScheme.error
: theme.colorScheme.onSurface; : theme.colorScheme.onSurface;
// Name the channel the connection is on (production / local / ) so
// "connected" can never look like it contradicts the Diagnose page,
// which reports the *active* channel's daemon.
final ch = HubService.instance.connectedChannelName;
final caption = connected == true final caption = connected == true
? l.connectionConnected ? (ch != null ? '${l.connectionConnected} · $ch' : l.connectionConnected)
: connected == false : connected == false
? l.connectionTapToStart ? l.connectionTapToStart
: l.connectionConnecting; : l.connectionConnecting;