Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions integration_test/app_mcp_stdio_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ void main() {
});
await openTestDb();
addTearDown(closeTestDb);
getIt.registerSingleton<SettingStore>(SettingStore.instance);
getIt.registerSingleton<ServerStore>(ServerStore.instance);
getIt.registerSingleton<SettingStore>(SettingStore());
getIt.registerSingleton<ServerStore>(ServerStore());
addTearDown(getIt.unregister<ServerStore>);
addTearDown(getIt.unregister<SettingStore>);
const port = int.fromEnvironment('MCP_SSH_PORT');
Expand Down
2 changes: 1 addition & 1 deletion lib/core/monitor/exec.dart
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ class MonitorExec implements CommandExec {
// a request that errors after the caller walked away is an unhandled
// asynchronous error.
unawaited(request.then((_) {}, onError: (_) {}));
return const ExecResult(exitCode: null, stdout: '', stderr: '');
return const ExecResult(exitCode: null, stdout: '', stderr: '', mayStillRun: true);
}
}

Expand Down
51 changes: 34 additions & 17 deletions lib/core/monitor/terminal.dart
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,19 @@ class MonitorShellBackend implements ShellBackend {
message: 'Monitor terminal backend is closed',
);
}
_session?.close();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
final session = MonitorShellSession._(
MonitorHttpClient(monitor),
MonitorClientLease(monitor),
cols: width,
rows: height,
);
_session = session;
await session._start();
try {
await session._start();
} catch (_) {
if (identical(_session, session)) _session = null;
rethrow;
}
return session;
}

Expand Down Expand Up @@ -109,7 +115,7 @@ class MonitorShellBackend implements ShellBackend {

/// One PTY on the agent, kept alive across reconnects.
class MonitorShellSession implements ShellSession {
MonitorShellSession._(this._client, {required this._cols, required this._rows});
MonitorShellSession._(this._lease, {required this._cols, required this._rows});

/// Missing this much heartbeat means the link is gone. The agent sends one
/// every 15s; three misses rather than one, so a stalled radio isn't
Expand All @@ -124,7 +130,7 @@ class MonitorShellSession implements ShellSession {
/// screen isn't a silent mix of old and new output.
static const _reset = [0x1b, 0x63];

final MonitorHttpClient _client;
final MonitorClientLease _lease;

final _output = StreamController<Uint8List>.broadcast();
final _done = Completer<void>();
Expand Down Expand Up @@ -162,22 +168,33 @@ class MonitorShellSession implements ShellSession {
Future<void> _start() async {
final ready = Completer<void>();
_ready = ready;
await _connect();
await ready.future.timeout(
const Duration(seconds: 20),
onTimeout: () {
close();
throw const MonitorHttpErr(
type: MonitorHttpErrType.net,
message: 'The Monitor did not open a shell in time',
);
},
);
try {
await _connect();
} catch (_) {
_ready = null;
_finish();
rethrow;
}
try {
await ready.future.timeout(
const Duration(seconds: 20),
onTimeout: () {
close();
throw const MonitorHttpErr(
type: MonitorHttpErrType.net,
message: 'The Monitor did not open a shell in time',
);
},
);
} catch (_) {
_finish();
rethrow;
}
}

Future<void> _connect() async {
if (_finished) return;
final socket = await _client.openTerminal();
final socket = await _lease.client.openTerminal();
if (_finished) {
unawaited(socket.close());
return;
Expand Down Expand Up @@ -408,7 +425,7 @@ class MonitorShellSession implements ShellSession {
);
_ready = null;
unawaited(_output.close());
_client.dispose();
_lease.release();
if (!_done.isCompleted) _done.complete();
}
}
47 changes: 36 additions & 11 deletions lib/core/service/app_mcp.dart
Original file line number Diff line number Diff line change
Expand Up @@ -178,12 +178,20 @@ Future<void> configureAppMcp(
} catch (_) {
await replacement?.close(force: true);
if (overlap) {
appMcpListener.value = await bindAppMcp(
previousRegistry,
container,
address: previousEndpoint.host,
port: previousEndpoint.port,
);
try {
appMcpListener.value = await bindAppMcp(
previousRegistry,
container,
address: previousEndpoint.host,
port: previousEndpoint.port,
);
} catch (rollbackErr, rollbackStack) {
_log.warning(
'App MCP listener rollback failed: ${rollbackErr.runtimeType}',
rollbackErr,
rollbackStack,
);
}
}
rethrow;
}
Expand All @@ -203,8 +211,12 @@ Future<void> startAppMcp(ProviderContainer container) async {
return;
}
await configureAppMcp(container, enabled: true, remember: false);
} catch (_) {
_log.warning('Could not start the configured App MCP listener.');
} catch (e, s) {
_log.warning(
'Could not start the configured App MCP listener: ${e.runtimeType}',
e,
s,
);
}
}

Expand Down Expand Up @@ -331,7 +343,8 @@ Future<void> _handle(
_log.info('${call.tool} caller=$callerId host=${call.host ?? '-'}');
}
await answer(response.status, response.body);
} catch (_) {
} catch (e, s) {
_log.warning('App MCP request failed: ${e.runtimeType}', e, s);
try {
await answer(503);
} catch (_) {
Expand Down Expand Up @@ -448,7 +461,18 @@ Future<ffi.AppMcpRan> _run(
};
} on SshInteractionRequired {
return _failed(ffi.AppMcpFailure.needsUser);
} catch (_) {
} on ServerChangedConcurrently {
return _failed(ffi.AppMcpFailure.hostChanged);
} on MonitorHttpErr catch (e, s) {
_log.warning('App MCP command failed on $host: ${e.type.name}', e, s);
final failure = switch (e.type) {
MonitorHttpErrType.certUnconfirmed ||
MonitorHttpErrType.certChanged => ffi.AppMcpFailure.needsUser,
_ => ffi.AppMcpFailure.unavailable,
};
return _failed(failure);
} catch (e, s) {
_log.warning('App MCP command failed on $host: ${e.runtimeType}', e, s);
return _failed(ffi.AppMcpFailure.unavailable);
}
}
Expand Down Expand Up @@ -511,7 +535,8 @@ Future<ffi.AppMcpRan> _bounded(
timedOut:
timedOut || (result is MonitorExecResult && result.timedOut),
);
} catch (e) {
} catch (e, s) {
_log.warning('App MCP command execution error: ${e.runtimeType}', e, s);
return _failed(_failureOf(e));
} finally {
timer.cancel();
Expand Down
1 change: 0 additions & 1 deletion lib/core/service/app_mcp_settings.dart
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ Map<String, McpPreference> mcpPreferences(ProviderContainer container) {
s.serverOverview,
s.serverTabConnBadge,
s.termMetricsBar,
s.serverPageSortAsc,
s.sshPageSortAsc,
s.remoteDesktopSortAsc,
]) {
Expand Down
5 changes: 5 additions & 0 deletions lib/core/service/crash_report.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import 'package:flutter/foundation.dart';
import 'package:server_box/core/service/diagnostics_upload.dart';
import 'package:server_box/core/service/known_identifiers.dart';
import 'package:server_box/core/service/native_exit.dart';
import 'package:server_box/core/service/report_filter.dart';
import 'package:server_box/data/model/file/backend/ssh.dart';
import 'package:server_box/data/res/build_data.dart';
import 'package:server_box/data/store/bmc_target.dart';
Expand Down Expand Up @@ -72,6 +73,10 @@ abstract final class CrashReport {
if (error is SftpUnavailable) return isAppFault(error.cause);
if (error is AsyncError) return isAppFault(error.error);

// Any external/account/sync/MCP failure already excluded from diagnostics
// should never prompt the user to file a crash report either.
if (!ReportFilter.isDefect(error)) return false;

// The whole `dart:io` family: a socket that would not open, a TLS
// handshake that failed, a process that would not start, a file the OS
// refused. `FileSystemException` is in there too, and included
Expand Down
34 changes: 17 additions & 17 deletions lib/core/service/diagnostics_upload.dart
Original file line number Diff line number Diff line change
Expand Up @@ -186,23 +186,6 @@ abstract final class DiagnosticsUpload {
}
}

/// [scrub], with what this install currently knows to be the user's — or
/// null, which drops the event.
///
/// Read per event rather than kept: a server added since launch is one whose
/// name would otherwise still go out. It is a store read on the way to the
/// network, which is not a hot path — an event is a crash.
///
/// **An event this cannot promise to have scrubbed does not go.** The
/// records are the whole of what separates a report from a disclosure, so
/// sending one without them would upload an unaudited string on the single
/// path where nothing was able to check it. The failure is narrow — an error
/// raised from an isolate that never opened a store, or while the app is
/// coming down — and what is given up is one report, while the error is
/// still written to the on-device log by the sink beside this one.
///
/// An install with *no servers* is not this case. It has nothing to
/// substitute, and its events go as they are.
/// Groups a [RangeError] by where it was thrown rather than by its text.
///
/// The message carries the bad value and the bounds, and GlitchTip groups an
Expand All @@ -227,6 +210,23 @@ abstract final class DiagnosticsUpload {
return event;
}

/// [scrub], with what this install currently knows to be the user's — or
/// null, which drops the event.
///
/// Read per event rather than kept: a server added since launch is one whose
/// name would otherwise still go out. It is a store read on the way to the
/// network, which is not a hot path — an event is a crash.
///
/// **An event this cannot promise to have scrubbed does not go.** The
/// records are the whole of what separates a report from a disclosure, so
/// sending one without them would upload an unaudited string on the single
/// path where nothing was able to check it. The failure is narrow — an error
/// raised from an isolate that never opened a store, or while the app is
/// coming down — and what is given up is one report, while the error is
/// still written to the on-device log by the sink beside this one.
///
/// An install with *no servers* is not this case. It has nothing to
/// substitute, and its events go as they are.
@visibleForTesting
static sentry.SentryEvent? scrubWithStoredIdentifiers(
sentry.SentryEvent event,
Expand Down
4 changes: 4 additions & 0 deletions lib/core/service/report_filter.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import 'dart:async';
import 'dart:io';

import 'package:dartssh2/dartssh2.dart';
Expand All @@ -16,6 +17,7 @@ import 'package:fl_lib/fl_lib.dart'
import 'package:fl_pi_llm_ui/fl_pi_llm_ui.dart' show McpTools;
import 'package:icloud_storage_plus/models/exceptions.dart';
import 'package:server_box/data/model/app/error.dart';
import 'package:server_box/data/model/file/backend/ssh.dart' show SftpUnavailable;
import 'package:webdav_client_plus/webdav_client_plus.dart' show WebdavException;

/// Whether an error is a defect in this app, or the network's or the user's
Expand All @@ -34,6 +36,8 @@ import 'package:webdav_client_plus/webdav_client_plus.dart' show WebdavException
/// letting an unknown through costs one report; filtering a real bug hides it.
abstract final class ReportFilter {
static bool isDefect(Object error) => switch (error) {
SftpUnavailable(:final cause) => isDefect(cause),
AsyncError(:final error) => isDefect(error),
// Connecting: nothing listening, nothing answering, a certificate the
// server chose. `HandshakeException` is TLS, to a monitor agent or WebDAV.
// A bare `OSError` is not here: the same class carries file-system errors,
Expand Down
6 changes: 3 additions & 3 deletions lib/core/service/scoped_token.dart
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ Map<String, ScopedToken> reusableScopedTokens({
final reusable = <String, ScopedToken>{};
for (final id in serverIds) {
if (invalidatedIds.contains(id)) continue;
final monitor = lookup(id)?.monitor;
final monitor = lookup(id)?.monitorOn;
final held = existing[id];
if (monitor == null || held == null) continue;
if (held.servesEndpoint(monitor.addr, now)) reusable[id] = held;
Expand Down Expand Up @@ -156,10 +156,10 @@ void revokeScopedTokensLeftBehind(
required void Function(Spi) queueWatchRevoke,
required void Function(Spi) queueWidgetRevoke,
}) {
final previous = old.monitor;
final previous = old.monitorOn;
if (previous == null) return;

final current = next.monitor;
final current = next.monitorOn;
final movedOn =
old.id != next.id ||
current == null ||
Expand Down
6 changes: 3 additions & 3 deletions lib/core/service/watch_sync.dart
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ final class WatchSync {
);
for (final entry in reusable.entries) {
final spi = Stores.server.fetchOneRaw(entry.key);
final monitor = spi?.monitor;
final monitor = spi?.monitorOn;
if (spi == null || monitor == null) continue;
final slot = _slot(entry.key);
// Do not overwrite a slot that has already started revoking or minting.
Expand Down Expand Up @@ -523,7 +523,7 @@ final class WatchSync {
if (_issueToken case final issueToken?) {
return await issueToken(spi, endpoint);
}
final monitor = spi.monitor;
final monitor = spi.monitorOn;
if (monitor == null) return null;
final client = MonitorHttpClient(monitor);
try {
Expand Down Expand Up @@ -692,7 +692,7 @@ final class WatchSync {
final servers = <Map<String, dynamic>>[];
for (final id in selectedIds) {
final spi = lookup(id);
final monitor = spi?.monitor;
final monitor = spi?.monitorOn;
if (spi == null || monitor == null) continue;
final token = tokens[id];
if (token == null || token.isEmpty) continue;
Expand Down
2 changes: 1 addition & 1 deletion lib/core/service/widget_sync.dart
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ final class WidgetSync {
..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
final entries = <Map<String, dynamic>>[];
for (final spi in ordered) {
final monitor = spi.monitor;
final monitor = spi.monitorOn;
if (monitor == null) continue;
final token = tokens[spi.id];
entries.add({
Expand Down
Loading
Loading