feat(#999): remote-CLI console for a companion, kept out of chat
Extend the one CLI console (device_cli_screen, F2 #883/#884) to target a permitted companion over the mesh (TXT type 3, #888/#889), reusing the console rather than adding a screen or a chat-borne command path. Opened from a "CLI console" action on a companion contact; command and reply both live in the console. - cli_console_transport.dart: CliConsoleTransport with a local and a remote implementation, and one CliConsoleTimeout the console catches. The remote transport sends with retries: 1 (no auto-retry - an unpermitted companion queues the command and never replies, so a retry only spams the mesh) and correlates the reply via the receivedFrames listener, gated to CLI_DATA so a chat message or inbound command from the same contact can't complete it (Sonnet review). - device_cli_screen: optional remoteContact; "Remote CLI" + contact name. - chat_screen: companion-only "CLI console" entry (Contact.isCompanion). Also corrects #890: CLI and chat are separate surfaces. The receive pipeline filed every contact frame into the conversation regardless of TXT type, so a companion's CLI reply (type 1) and an inbound command (type 3) leaked into the chat thread. A guard now drops CLI-typed messages from the message pipeline - the console is their only surface - and #890's in-chat command bubble is removed. Review (Sonnet, one-off, Gemini budget down): redact secret reply text in the remote path's late/unmatched log, matching LocalCliService; dispose cancels the subscription; document that remote truncation is not detectable post-reassembly. Tests: transport round-trip / sender-filter / timeout / no-retry / CLI_DATA gate; Contact.isCompanion; remote console title; and the pipeline keeping CLI (type 1 and 3) out of the conversation while a plain message still enters. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>pull/1004/head
parent
bd6b578136
commit
3e40979e94
@ -0,0 +1,165 @@
|
||||
// What the CLI console (device_cli_screen) talks to (#999, plan F3/E3.1). The
|
||||
// console renders the same transcript whether the CLI runs on the connected
|
||||
// radio (local frame 66/29) or on a remote contact over the mesh (TXT type
|
||||
// chosen by role, #888/#889). This abstracts the two transports behind one
|
||||
// run()->CliReply call and one timeout type, so the screen holds no
|
||||
// transport-specific branches.
|
||||
//
|
||||
// No auto-retry on the remote leg: a companion that has not granted us remote
|
||||
// CLI (contact flag 0x10 on its side) queues our command as a plain message and
|
||||
// never replies, so retrying only spams the mesh. One send, then a timeout the
|
||||
// console explains (#891). Repeaters use their own screen and keep their retry
|
||||
// behavior there.
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import '../connector/cli_command_codec.dart';
|
||||
import '../connector/meshcore_connector.dart';
|
||||
import '../connector/meshcore_protocol.dart';
|
||||
import '../models/contact.dart';
|
||||
import 'local_cli_service.dart';
|
||||
import 'repeater_command_service.dart';
|
||||
|
||||
/// A CLI command's window closed with no reply, regardless of transport. Both
|
||||
/// underlying services carry their own timeout type; the console catches only
|
||||
/// this one so its handling reads the same for a local or a remote command.
|
||||
class CliConsoleTimeout implements Exception {
|
||||
const CliConsoleTimeout({required this.command, required this.secondsText});
|
||||
|
||||
final String command;
|
||||
|
||||
/// The armed window in seconds to one decimal, e.g. `10.0`.
|
||||
final String secondsText;
|
||||
|
||||
@override
|
||||
String toString() => 'CLI command timed out after $secondsText s';
|
||||
}
|
||||
|
||||
/// One CLI transport for the console: the connected device, or a remote contact.
|
||||
abstract class CliConsoleTransport {
|
||||
/// Runs [command] and completes with the correlated reply, or throws
|
||||
/// [CliConsoleTimeout] when the window closes with no answer. Other failures
|
||||
/// (codec rejection, send error) surface as their own exceptions.
|
||||
Future<CliReply> run(String command, {Duration? timeout});
|
||||
|
||||
void dispose();
|
||||
}
|
||||
|
||||
/// CLI on the connected radio, over frame 66/29.
|
||||
class LocalCliTransport implements CliConsoleTransport {
|
||||
LocalCliTransport(MeshCoreConnector connector, {LocalCliService? service})
|
||||
: _service = service ?? LocalCliService(connector);
|
||||
|
||||
final LocalCliService _service;
|
||||
|
||||
@override
|
||||
Future<CliReply> run(String command, {Duration? timeout}) async {
|
||||
try {
|
||||
return await _service.run(command, timeout: timeout);
|
||||
} on LocalCliTimeout catch (e) {
|
||||
throw CliConsoleTimeout(command: command, secondsText: e.secondsText);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() => _service.dispose();
|
||||
}
|
||||
|
||||
/// CLI on a remote contact over the mesh. The txt type is chosen by the
|
||||
/// target's role (#888/#889): a companion gets TXT_TYPE_CLI_COMMAND, a
|
||||
/// repeater/room server the universal CLI_DATA. The reply returns as a contact
|
||||
/// message carrying the reflected `cc|` prefix; this listens for it and feeds it
|
||||
/// to the shared correlation in [RepeaterCommandService].
|
||||
class RemoteCliTransport implements CliConsoleTransport {
|
||||
RemoteCliTransport(
|
||||
this._connector,
|
||||
this._target, {
|
||||
RepeaterCommandService? service,
|
||||
}) : _service = service ?? RepeaterCommandService(_connector) {
|
||||
// A companion is a human chat node, so a late/unmatched reply must never
|
||||
// log its text: a slow `get wifi.pwd` round trip would otherwise write the
|
||||
// password to the app log, which the console's masking cannot undo. Match
|
||||
// LocalCliService, which always withholds (#999 review).
|
||||
_service.redactUnmatchedReplyText = true;
|
||||
_sub = _connector.receivedFrames.listen(_onFrame);
|
||||
}
|
||||
|
||||
final MeshCoreConnector _connector;
|
||||
final Contact _target;
|
||||
final RepeaterCommandService _service;
|
||||
StreamSubscription<Uint8List>? _sub;
|
||||
bool _disposed = false;
|
||||
|
||||
void _onFrame(Uint8List frame) {
|
||||
if (_disposed || frame.isEmpty) return;
|
||||
if (frame[0] != respCodeContactMsgRecv &&
|
||||
frame[0] != respCodeContactMsgRecvV3) {
|
||||
return;
|
||||
}
|
||||
final parsed = parseContactMessageText(frame);
|
||||
if (parsed == null) return;
|
||||
if (!_matchesTargetPrefix(parsed.senderPrefix)) return;
|
||||
// Only a CLI_DATA reply answers a command. A plain chat message, or an
|
||||
// inbound type-3 command, from the SAME companion must not complete our
|
||||
// pending command - without this it would hit handleResponse's unprefixed
|
||||
// sole-pending fallback and render "hey, you there?" as the CLI reply
|
||||
// (#999 review). Some layouts carry the type shifted; check both.
|
||||
final t = parsed.txtType;
|
||||
if (t != txtTypeCliData && (t >> 2) != txtTypeCliData) return;
|
||||
// Routes to the waiting command's future (or is logged if its window
|
||||
// already closed, #589). handleResponse resolves the target from its key,
|
||||
// so the possibly-stale [_target] is fine here.
|
||||
_service.handleResponse(_resolveTarget(), parsed.text);
|
||||
}
|
||||
|
||||
bool _matchesTargetPrefix(Uint8List prefix) {
|
||||
final key = _target.publicKey;
|
||||
if (key.length < 6 || prefix.length < 6) return false;
|
||||
for (var i = 0; i < 6; i++) {
|
||||
if (prefix[i] != key[i]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// The contact's path can be updated after this transport is built, so re-read
|
||||
/// the live contact by key at send time and fall back to the original.
|
||||
Contact _resolveTarget() {
|
||||
for (final c in _connector.contacts) {
|
||||
if (c.publicKeyHex == _target.publicKeyHex) return c;
|
||||
}
|
||||
return _target;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<CliReply> run(String command, {Duration? timeout}) async {
|
||||
// retries: 1 - one send, no auto-retry. See the file header.
|
||||
try {
|
||||
final text = await _service.sendCommand(
|
||||
_resolveTarget(),
|
||||
command,
|
||||
retries: 1,
|
||||
);
|
||||
// payloadLength drives CliReply.atReplyBound (the local 165-byte device
|
||||
// bound). A remote reply is a reassembled mesh message, so that bound is
|
||||
// not meaningful and truncation cannot be detected here; the stripped
|
||||
// text length keeps atReplyBound false rather than faking a cut (#999).
|
||||
return CliReply(
|
||||
prefix: null,
|
||||
text: text,
|
||||
payloadLength: utf8.encode(text).length,
|
||||
);
|
||||
} on RepeaterCommandTimeout catch (e) {
|
||||
throw CliConsoleTimeout(command: command, secondsText: e.secondsText);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
_sub?.cancel();
|
||||
_sub = null;
|
||||
_service.dispose();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,31 @@
|
||||
// #999: remote CLI is a companion-only feature, and the chat-screen entry point
|
||||
// gates on Contact.isCompanion. These pin that only a chat node reads as a
|
||||
// companion - a repeater, room server or sensor must not, or the CLI-console
|
||||
// action would appear where it does not belong.
|
||||
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_protocol.dart';
|
||||
import 'package:meshcore_open/models/contact.dart';
|
||||
|
||||
Contact _of(int type) => Contact(
|
||||
publicKey: Uint8List.fromList(List<int>.generate(32, (i) => i)),
|
||||
receivedName: 'X',
|
||||
type: type,
|
||||
pathLength: 0,
|
||||
path: Uint8List(0),
|
||||
lastSeen: DateTime.fromMillisecondsSinceEpoch(0),
|
||||
);
|
||||
|
||||
void main() {
|
||||
test('a chat node is a companion', () {
|
||||
expect(_of(advTypeChat).isCompanion, isTrue);
|
||||
});
|
||||
|
||||
test('a repeater, room server or sensor is not a companion', () {
|
||||
expect(_of(advTypeRepeater).isCompanion, isFalse);
|
||||
expect(_of(advTypeRoom).isCompanion, isFalse);
|
||||
expect(_of(advTypeSensor).isCompanion, isFalse);
|
||||
});
|
||||
}
|
||||
@ -0,0 +1,262 @@
|
||||
// #999: the CLI console must drive a remote companion the same way it drives
|
||||
// the local device - one run()->CliReply call, one timeout type. These pin the
|
||||
// remote transport's wiring (send type-3, correlate the reflected-prefix
|
||||
// reply), its sender filtering (another contact's reply must not complete our
|
||||
// command), and that both transports map their service's timeout to the single
|
||||
// CliConsoleTimeout the console catches.
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/connector/cli_command_codec.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_connector.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_protocol.dart';
|
||||
import 'package:meshcore_open/models/contact.dart';
|
||||
import 'package:meshcore_open/services/cli_console_transport.dart';
|
||||
import 'package:meshcore_open/services/local_cli_service.dart';
|
||||
import 'package:meshcore_open/services/repeater_command_service.dart';
|
||||
import 'package:meshcore_open/storage/prefs_manager.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
Contact _companion() => Contact(
|
||||
publicKey: Uint8List.fromList(List<int>.generate(32, (i) => i + 1)),
|
||||
receivedName: 'Companion',
|
||||
type: advTypeChat,
|
||||
pathLength: 0,
|
||||
path: Uint8List(0),
|
||||
lastSeen: DateTime.fromMillisecondsSinceEpoch(0),
|
||||
);
|
||||
|
||||
/// A contact-message reply frame carrying [text] from [senderPrefix]:
|
||||
/// [respCodeContactMsgRecv][prefix x6][path_len][txt_type][ts x4][text][0].
|
||||
Uint8List _replyFrame({
|
||||
required Uint8List senderPrefix,
|
||||
required String text,
|
||||
int txtType = txtTypeCliData,
|
||||
}) {
|
||||
final b = BytesBuilder();
|
||||
b.addByte(respCodeContactMsgRecv);
|
||||
b.add(senderPrefix.sublist(0, 6));
|
||||
b.addByte(0); // path_len
|
||||
b.addByte(txtType); // CLI_DATA is the reply type a companion answers with
|
||||
b.add([0, 0, 0, 0]); // timestamp
|
||||
b.add(ascii.encode(text));
|
||||
b.addByte(0);
|
||||
return b.toBytes();
|
||||
}
|
||||
|
||||
/// Throws a timeout from sendCommand so the mapping can be tested without
|
||||
/// waiting out a real mesh window.
|
||||
class _TimingOutRemoteService extends RepeaterCommandService {
|
||||
_TimingOutRemoteService(super.connector);
|
||||
|
||||
@override
|
||||
Future<String> sendCommand(
|
||||
Contact repeater,
|
||||
String command, {
|
||||
Function(String)? onResponse,
|
||||
Function(int)? onAttempt,
|
||||
int retries = RepeaterCommandService.maxRetries,
|
||||
}) async {
|
||||
throw RepeaterCommandTimeout(command: command, timeoutMs: 4300);
|
||||
}
|
||||
}
|
||||
|
||||
/// Throws a local timeout from run() so LocalCliTransport's mapping can be
|
||||
/// tested in isolation.
|
||||
class _TimingOutLocalService extends LocalCliService {
|
||||
_TimingOutLocalService(super.connector);
|
||||
|
||||
@override
|
||||
Future<CliReply> run(String command, {Duration? timeout}) async {
|
||||
throw LocalCliTimeout(
|
||||
command: command,
|
||||
timeout: const Duration(seconds: 10),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
});
|
||||
|
||||
group('RemoteCliTransport', () {
|
||||
test(
|
||||
'sends a type-3 command and completes with the correlated reply',
|
||||
() async {
|
||||
final connector = MeshCoreConnector();
|
||||
final companion = _companion();
|
||||
final sent = <Uint8List>[];
|
||||
final cliSent = Completer<Uint8List>();
|
||||
connector.sendFrameOverrideForTest = (f) {
|
||||
sent.add(f);
|
||||
if (!cliSent.isCompleted && f.isNotEmpty && f[0] == cmdSendTxtMsg) {
|
||||
cliSent.complete(f);
|
||||
}
|
||||
};
|
||||
connector.setConnectedForTest();
|
||||
connector.contactsForTest.add(companion);
|
||||
|
||||
final transport = RemoteCliTransport(connector, companion);
|
||||
final future = transport.run('get radio');
|
||||
|
||||
final frame = await cliSent.future;
|
||||
// Frame: [cmd][type][attempt][ts x4][pubKey x6][cc| prefix ...].
|
||||
expect(frame[1], txtTypeCliCommand, reason: 'a companion gets type 3');
|
||||
final prefix = ascii.decode(frame.sublist(13, 16));
|
||||
|
||||
connector.handleFrameForTest(
|
||||
_replyFrame(
|
||||
senderPrefix: companion.publicKey,
|
||||
text: '${prefix}radio ok',
|
||||
),
|
||||
);
|
||||
|
||||
final reply = await future;
|
||||
expect(reply.text, 'radio ok');
|
||||
// No auto-retry: exactly one CLI send frame went out (#999/#891).
|
||||
expect(
|
||||
sent.where((f) => f.isNotEmpty && f[0] == cmdSendTxtMsg),
|
||||
hasLength(1),
|
||||
);
|
||||
transport.dispose();
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'a plain or type-3 message from the target does not complete the command',
|
||||
() async {
|
||||
final connector = MeshCoreConnector();
|
||||
final companion = _companion();
|
||||
final cliSent = Completer<Uint8List>();
|
||||
connector.sendFrameOverrideForTest = (f) {
|
||||
if (!cliSent.isCompleted && f.isNotEmpty && f[0] == cmdSendTxtMsg) {
|
||||
cliSent.complete(f);
|
||||
}
|
||||
};
|
||||
connector.setConnectedForTest();
|
||||
connector.contactsForTest.add(companion);
|
||||
|
||||
final transport = RemoteCliTransport(connector, companion);
|
||||
final future = transport.run('get radio');
|
||||
final frame = await cliSent.future;
|
||||
final prefix = ascii.decode(frame.sublist(13, 16));
|
||||
|
||||
// A companion is a human chat node. A plain chat message (no prefix)
|
||||
// must NOT complete the command via the unprefixed sole-pending
|
||||
// fallback, and neither must an inbound type-3 command from them.
|
||||
connector.handleFrameForTest(
|
||||
_replyFrame(
|
||||
senderPrefix: companion.publicKey,
|
||||
text: 'hey, you there?',
|
||||
txtType: txtTypePlain,
|
||||
),
|
||||
);
|
||||
connector.handleFrameForTest(
|
||||
_replyFrame(
|
||||
senderPrefix: companion.publicKey,
|
||||
text: 'run this on me',
|
||||
txtType: txtTypeCliCommand,
|
||||
),
|
||||
);
|
||||
// Only the real CLI_DATA reply completes it.
|
||||
connector.handleFrameForTest(
|
||||
_replyFrame(
|
||||
senderPrefix: companion.publicKey,
|
||||
text: '${prefix}radio ok',
|
||||
),
|
||||
);
|
||||
|
||||
final reply = await future;
|
||||
expect(reply.text, 'radio ok');
|
||||
transport.dispose();
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'a reply from another contact does not complete our command',
|
||||
() async {
|
||||
final connector = MeshCoreConnector();
|
||||
final companion = _companion();
|
||||
final cliSent = Completer<Uint8List>();
|
||||
connector.sendFrameOverrideForTest = (f) {
|
||||
if (!cliSent.isCompleted && f.isNotEmpty && f[0] == cmdSendTxtMsg) {
|
||||
cliSent.complete(f);
|
||||
}
|
||||
};
|
||||
connector.setConnectedForTest();
|
||||
connector.contactsForTest.add(companion);
|
||||
|
||||
final transport = RemoteCliTransport(connector, companion);
|
||||
final future = transport.run('get radio');
|
||||
final frame = await cliSent.future;
|
||||
final prefix = ascii.decode(frame.sublist(13, 16));
|
||||
|
||||
// A different contact reflects the same prefix - must be ignored.
|
||||
final otherKey = Uint8List.fromList(List<int>.filled(32, 0xEE));
|
||||
connector.handleFrameForTest(
|
||||
_replyFrame(senderPrefix: otherKey, text: '${prefix}WRONG'),
|
||||
);
|
||||
// The real target's reply must be the one that completes it.
|
||||
connector.handleFrameForTest(
|
||||
_replyFrame(
|
||||
senderPrefix: companion.publicKey,
|
||||
text: '${prefix}RIGHT',
|
||||
),
|
||||
);
|
||||
|
||||
final reply = await future;
|
||||
expect(reply.text, 'RIGHT');
|
||||
transport.dispose();
|
||||
},
|
||||
);
|
||||
|
||||
test('a timed-out send surfaces as CliConsoleTimeout', () async {
|
||||
final connector = MeshCoreConnector();
|
||||
final transport = RemoteCliTransport(
|
||||
connector,
|
||||
_companion(),
|
||||
service: _TimingOutRemoteService(connector),
|
||||
);
|
||||
await expectLater(
|
||||
transport.run('get radio'),
|
||||
throwsA(
|
||||
isA<CliConsoleTimeout>().having(
|
||||
(e) => e.secondsText,
|
||||
'secondsText',
|
||||
'4.3',
|
||||
),
|
||||
),
|
||||
);
|
||||
transport.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
group('LocalCliTransport', () {
|
||||
test('a local timeout surfaces as CliConsoleTimeout', () async {
|
||||
final connector = MeshCoreConnector();
|
||||
final transport = LocalCliTransport(
|
||||
connector,
|
||||
service: _TimingOutLocalService(connector),
|
||||
);
|
||||
await expectLater(
|
||||
transport.run('get radio'),
|
||||
throwsA(
|
||||
isA<CliConsoleTimeout>().having(
|
||||
(e) => e.secondsText,
|
||||
'secondsText',
|
||||
'10.0',
|
||||
),
|
||||
),
|
||||
);
|
||||
transport.dispose();
|
||||
});
|
||||
});
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
Loading…
Reference in new issue