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
diffwireauto 1 month ago committed by Strycher
parent bd6b578136
commit 3e40979e94

@ -3252,6 +3252,11 @@ class MeshCoreConnector extends ChangeNotifier {
(activeTransport != MeshCoreTransportType.tcp || !tcpManagerConnected);
}
/// Sets the self public key so tests can drive the incoming-message path,
/// which bails when no self identity is known.
@visibleForTesting
void setSelfPublicKeyForTest(Uint8List key) => _selfPublicKey = key;
@visibleForTesting
static bool shouldResetStateAfterTcpConnectAbort({
required MeshCoreConnectionState state,
@ -8742,6 +8747,16 @@ class MeshCoreConnector extends ChangeNotifier {
return;
}
// CLI traffic stays in the CLI console only. A CLI reply (type-1) or an
// inbound CLI command (type-3) is correlated by the console through the
// receivedFrames listener; it must never enter the chat thread, bump the
// contact's last-message, or raise unread. CLI and chat are separate
// surfaces - drop CLI out of the message pipeline here (#999).
if (message.isCli || message.isCliCommand) {
_handleQueuedMessageReceived();
return;
}
final contact = _contacts.cast<Contact?>().firstWhere(
(c) => c?.publicKeyHex == message!.senderKeyHex,
orElse: () => null,

@ -1048,7 +1048,17 @@ const int msgTextOffset = 38;
class ParsedContactText {
final Uint8List senderPrefix;
final String text;
const ParsedContactText({required this.senderPrefix, required this.text});
/// The raw TXT type byte (plain 0, CLI_DATA 1, signed 2, CLI_COMMAND 3).
/// Some layouts carry it shifted left by 2; compare with both the raw value
/// and `txtType >> 2`, as the receive path does.
final int txtType;
const ParsedContactText({
required this.senderPrefix,
required this.text,
required this.txtType,
});
}
ParsedContactText? parseContactMessageText(Uint8List frame) {
@ -1081,7 +1091,11 @@ ParsedContactText? parseContactMessageText(Uint8List frame) {
final text = message.readCString();
if (text.isEmpty) return null;
return ParsedContactText(senderPrefix: senderPrefix, text: text);
return ParsedContactText(
senderPrefix: senderPrefix,
text: text,
txtType: textType,
);
} catch (e) {
debugPrint('Error parsing contact message text: $e');
return null;

@ -184,6 +184,10 @@
"device_quickSwitch": "Quick switch",
"device_meshcore": "MeshCore",
"deviceCli_title": "Device CLI",
"deviceCli_remoteTitle": "Remote CLI",
"@deviceCli_remoteTitle": {
"description": "Title of the CLI console when it targets a remote companion contact (#999); the contact's name is the subtitle."
},
"deviceCli_entrySubtitle": "Run commands on the connected radio",
"deviceCli_nameRejected": "Not sent - name can't contain: {chars}",
"@deviceCli_nameRejected": {
@ -795,6 +799,10 @@
"contact_teleEnvSubtitle": "Allow sharing environment sensor data",
"contact_remoteCli": "Remote CLI",
"contact_remoteCliSubtitle": "Let this contact run CLI commands on your radio",
"contact_cliConsole": "CLI console",
"@contact_cliConsole": {
"description": "Chat app-bar menu action on a companion contact that opens the remote CLI console targeting that contact (#999)."
},
"channels_title": "Channels",
"channels_noChannelsConfigured": "No channels configured",
"channels_addPublicChannel": "Add Public Channel",
@ -930,7 +938,6 @@
"channels_enterHashtag": "Enter hashtag",
"channels_hashtagHint": "e.g. #team",
"chat_noMessages": "No messages yet",
"chat_remoteCliCommand": "Command for your radio",
"chat_sendMessage": "Send message",
"chat_sendMessageTo": "Send a message to {contactName}",
"@chat_sendMessageTo": {

@ -730,6 +730,12 @@ abstract class AppLocalizations {
/// **'Device CLI'**
String get deviceCli_title;
/// Title of the CLI console when it targets a remote companion contact (#999); the contact's name is the subtitle.
///
/// In en, this message translates to:
/// **'Remote CLI'**
String get deviceCli_remoteTitle;
/// No description provided for @deviceCli_entrySubtitle.
///
/// In en, this message translates to:
@ -2758,6 +2764,12 @@ abstract class AppLocalizations {
/// **'Let this contact run CLI commands on your radio'**
String get contact_remoteCliSubtitle;
/// Chat app-bar menu action on a companion contact that opens the remote CLI console targeting that contact (#999).
///
/// In en, this message translates to:
/// **'CLI console'**
String get contact_cliConsole;
/// No description provided for @channels_title.
///
/// In en, this message translates to:

@ -346,6 +346,9 @@ class AppLocalizationsBg extends AppLocalizations {
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@ -1543,6 +1546,9 @@ class AppLocalizationsBg extends AppLocalizations {
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Канали';

@ -349,6 +349,9 @@ class AppLocalizationsDe extends AppLocalizations {
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@ -1537,6 +1540,9 @@ class AppLocalizationsDe extends AppLocalizations {
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Kanäle';

@ -343,6 +343,9 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@ -1519,6 +1522,9 @@ class AppLocalizationsEn extends AppLocalizations {
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Channels';

@ -347,6 +347,9 @@ class AppLocalizationsEs extends AppLocalizations {
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@ -1538,6 +1541,9 @@ class AppLocalizationsEs extends AppLocalizations {
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Canales';

@ -349,6 +349,9 @@ class AppLocalizationsFr extends AppLocalizations {
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@ -1543,6 +1546,9 @@ class AppLocalizationsFr extends AppLocalizations {
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Canaux';

@ -346,6 +346,9 @@ class AppLocalizationsHu extends AppLocalizations {
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@ -1544,6 +1547,9 @@ class AppLocalizationsHu extends AppLocalizations {
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Csatornák';

@ -349,6 +349,9 @@ class AppLocalizationsIt extends AppLocalizations {
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@ -1539,6 +1542,9 @@ class AppLocalizationsIt extends AppLocalizations {
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Canali';

@ -336,6 +336,9 @@ class AppLocalizationsJa extends AppLocalizations {
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@ -1487,6 +1490,9 @@ class AppLocalizationsJa extends AppLocalizations {
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'チャンネル';

@ -335,6 +335,9 @@ class AppLocalizationsKo extends AppLocalizations {
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@ -1482,6 +1485,9 @@ class AppLocalizationsKo extends AppLocalizations {
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => '채널';

@ -345,6 +345,9 @@ class AppLocalizationsNl extends AppLocalizations {
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@ -1530,6 +1533,9 @@ class AppLocalizationsNl extends AppLocalizations {
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Kanaal';

@ -350,6 +350,9 @@ class AppLocalizationsPl extends AppLocalizations {
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@ -1549,6 +1552,9 @@ class AppLocalizationsPl extends AppLocalizations {
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Kanały';

@ -348,6 +348,9 @@ class AppLocalizationsPt extends AppLocalizations {
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@ -1539,6 +1542,9 @@ class AppLocalizationsPt extends AppLocalizations {
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Canais';

@ -348,6 +348,9 @@ class AppLocalizationsRu extends AppLocalizations {
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@ -1540,6 +1543,9 @@ class AppLocalizationsRu extends AppLocalizations {
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Каналы';

@ -347,6 +347,9 @@ class AppLocalizationsSk extends AppLocalizations {
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@ -1530,6 +1533,9 @@ class AppLocalizationsSk extends AppLocalizations {
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Kanály';

@ -345,6 +345,9 @@ class AppLocalizationsSl extends AppLocalizations {
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@ -1527,6 +1530,9 @@ class AppLocalizationsSl extends AppLocalizations {
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Kanali';

@ -344,6 +344,9 @@ class AppLocalizationsSv extends AppLocalizations {
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@ -1521,6 +1524,9 @@ class AppLocalizationsSv extends AppLocalizations {
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Kanaler';

@ -347,6 +347,9 @@ class AppLocalizationsUk extends AppLocalizations {
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@ -1535,6 +1538,9 @@ class AppLocalizationsUk extends AppLocalizations {
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Канали';

@ -333,6 +333,9 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@ -1468,6 +1471,9 @@ class AppLocalizationsZh extends AppLocalizations {
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => '频道';

@ -123,6 +123,11 @@ class Contact {
bool get isFavorite => (flags & contactFlagFavorite) != 0;
/// A chat node (phone/radio companion), as opposed to a repeater, room
/// server or sensor. Remote CLI (#999) targets companions; repeaters and
/// room servers have their own CLI via the repeater hub.
bool get isCompanion => type == advTypeChat;
Contact copyWith({
Uint8List? publicKey,
String? receivedName,

@ -38,6 +38,7 @@ import '../widgets/elements_ui.dart';
import '../widgets/mention_autocomplete.dart';
import '../helpers/emoji_shortcodes.dart';
import 'channel_message_path_screen.dart';
import 'device_cli_screen.dart';
import 'map_screen.dart';
import '../utils/emoji_utils.dart';
import '../widgets/emoji_picker.dart';
@ -353,6 +354,15 @@ class _ChatScreenState extends State<ChatScreen> {
),
);
}
if (value == 'cliConsole') {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
DeviceCliScreen(remoteContact: widget.contact),
),
);
}
if (value == 'clearChat') {
connector.clearMessagesForContact(widget.contact);
}
@ -402,6 +412,19 @@ class _ChatScreenState extends State<ChatScreen> {
],
),
),
// Remote CLI is a companion feature (#999): repeaters and
// room servers have their own CLI via the repeater hub.
if (widget.contact.isCompanion)
PopupMenuItem(
value: 'cliConsole',
child: Row(
children: [
const Icon(Icons.terminal, size: 20),
const SizedBox(width: 12),
Text(context.l10n.contact_cliConsole),
],
),
),
PopupMenuItem(
value: 'clearChat',
child: Row(
@ -1822,24 +1845,6 @@ class _MessageBubble extends StatelessWidget {
),
if (gifUrl == null) const SizedBox(height: 4),
],
if (message.isCliCommand) ...[
Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.terminal, size: 13, color: metaColor),
const SizedBox(width: 4),
Text(
context.l10n.chat_remoteCliCommand,
style: TextStyle(
fontSize: 11,
fontStyle: FontStyle.italic,
color: metaColor,
),
),
],
),
const SizedBox(height: 4),
],
if (poi != null)
_buildPoiMessage(
context,

@ -1,17 +1,19 @@
// Device CLI console (#883, interop plan F2/E2.1) - the local-device
// counterpart of RepeaterCliScreen, built to the owner-approved mockup on
// issue #883. Same console pattern, minus everything mesh-specific: no
// path/flood selection, no retries - one frame-66 send per command with a
// frame-level timeout surfaced as its own transcript row.
// CLI console (#883 local, #999 remote; interop plan F2/E2.1 + F3/E3.1). The
// local-device counterpart of RepeaterCliScreen, built to the owner-approved
// mockup on #883, and - with a [remoteContact] - the surface for remote CLI to
// a companion over the mesh. One console, one transcript; the transport
// ([CliConsoleTransport]) is what differs (local frame 66/29 vs remote TXT
// type-3). Same pattern, minus path/flood selection and retries: one send per
// command, a timeout surfaced as its own transcript row.
//
// Secrecy rule (W3/F4, applied here from day one): a reply to a command that
// names a secret (anything containing "pwd"/"password") renders masked and is
// only recoverable via long-press-to-copy; its cleartext never enters the
// widget tree as selectable text and is never logged by this screen.
//
// Population gating is NOT here: offering this screen only where the
// classifier allows frame 66 is #884 (entry point + gate). Until #884 lands,
// nothing navigates to this screen.
// Population gating is NOT here: offering the local console only where the
// classifier allows frame 66 is #884; offering the remote console only on a
// companion contact is the entry point in chat_screen (#999).
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
@ -20,7 +22,8 @@ import '../connector/meshcore_connector.dart';
import '../helpers/device_name_validator.dart';
import '../helpers/snack_bar_builder.dart';
import '../l10n/l10n.dart';
import '../services/local_cli_service.dart';
import '../models/contact.dart';
import '../services/cli_console_transport.dart';
enum _EntryKind { command, reply, timeout, sendFailed }
@ -67,12 +70,17 @@ class _ConsoleEntry {
}
class DeviceCliScreen extends StatefulWidget {
const DeviceCliScreen({super.key, this.commandTimeout});
const DeviceCliScreen({super.key, this.commandTimeout, this.remoteContact});
/// Per-command reply window; null uses [LocalCliService.defaultTimeout].
/// Tests shrink it so a timeout row renders without a 10 s pump.
/// Per-command reply window; null uses the transport's default. Tests shrink
/// it so a timeout row renders without a 10 s pump. The remote transport
/// computes its own mesh window and ignores this.
final Duration? commandTimeout;
/// When set, the console runs CLI on this remote contact over the mesh
/// (type-3 for a companion, #999) instead of the connected device.
final Contact? remoteContact;
@override
State<DeviceCliScreen> createState() => _DeviceCliScreenState();
}
@ -83,18 +91,22 @@ class _DeviceCliScreenState extends State<DeviceCliScreen> {
final ScrollController _scrollController = ScrollController();
final List<_ConsoleEntry> _entries = [];
int _historyIndex = -1;
LocalCliService? _cliService;
CliConsoleTransport? _transport;
bool get _isRemote => widget.remoteContact != null;
@override
void initState() {
super.initState();
final connector = Provider.of<MeshCoreConnector>(context, listen: false);
_cliService = LocalCliService(connector);
_transport = widget.remoteContact == null
? LocalCliTransport(connector)
: RemoteCliTransport(connector, widget.remoteContact!);
}
@override
void dispose() {
_cliService?.dispose();
_transport?.dispose();
_commandController.dispose();
_commandFocusNode.dispose();
_scrollController.dispose();
@ -131,8 +143,8 @@ class _DeviceCliScreenState extends State<DeviceCliScreen> {
Future<void> _sendCommand() async {
final command = _commandController.text.trim();
if (command.isEmpty) return;
final service = _cliService;
if (service == null) return;
final transport = _transport;
if (transport == null) return;
// Mirror the firmware's `set name` character rejection locally: show the
// typed command and a rejection row, and never send the frame (#885).
@ -168,7 +180,10 @@ class _DeviceCliScreenState extends State<DeviceCliScreen> {
final stopwatch = Stopwatch()..start();
_ConsoleEntry entry;
try {
final reply = await service.run(command, timeout: widget.commandTimeout);
final reply = await transport.run(
command,
timeout: widget.commandTimeout,
);
stopwatch.stop();
entry = _ConsoleEntry.reply(
reply.text,
@ -177,7 +192,7 @@ class _DeviceCliScreenState extends State<DeviceCliScreen> {
secret: secret,
isError: looksLikeErrorReply(reply.text),
);
} on LocalCliTimeout catch (e) {
} on CliConsoleTimeout catch (e) {
if (!mounted) return;
entry = _ConsoleEntry.timeout(
context.l10n.deviceCli_noReply(command, e.secondsText),
@ -257,12 +272,20 @@ class _DeviceCliScreenState extends State<DeviceCliScreen> {
Widget build(BuildContext context) {
final l10n = context.l10n;
final connector = context.watch<MeshCoreConnector>();
final name = connector.selfName;
final version = connector.firmwareVersion;
final subtitle = [
if (name != null && name.isNotEmpty) name,
if (version != null && version.isNotEmpty) '($version)',
].join(' ');
final String title;
final String subtitle;
if (_isRemote) {
title = l10n.deviceCli_remoteTitle;
subtitle = widget.remoteContact!.name;
} else {
title = l10n.deviceCli_title;
final name = connector.selfName;
final version = connector.firmwareVersion;
subtitle = [
if (name != null && name.isNotEmpty) name,
if (version != null && version.isNotEmpty) '($version)',
].join(' ');
}
return Scaffold(
appBar: AppBar(
@ -270,7 +293,7 @@ class _DeviceCliScreenState extends State<DeviceCliScreen> {
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(l10n.deviceCli_title),
Text(title),
if (subtitle.isNotEmpty)
Text(
subtitle,

@ -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();
}
}

@ -90,6 +90,13 @@ class RepeaterCommandService {
/// them in front of users (#589).
void Function(UnmatchedRepeaterResponse)? onUnmatchedResponse;
/// When set, the late/unmatched log withholds the reply text and the command
/// string, logging only lengths. The remote CLI console sets this so a
/// slow `get wifi.pwd` reply never writes the password to the app log, the
/// same guarantee [LocalCliService] gives (#999 review). Default false keeps
/// the repeater path's existing diagnostics.
bool redactUnmatchedReplyText = false;
RepeaterCommandService(this._connector);
/// Send a CLI command to a contact (a repeater/room server OR a companion)
@ -255,16 +262,25 @@ class RepeaterCommandService {
: DateTime.now().difference(expired.expiredAt);
if (expired != null) {
final commandText = redactUnmatchedReplyText
? '(withheld)'
: '"${expired.command}"';
final payloadText = redactUnmatchedReplyText
? '${responsePayload.length} chars, text withheld'
: responsePayload;
appLogger.warn(
'Late reply to "${expired.command}" from $repeaterKey arrived '
'Late reply to $commandText from $repeaterKey arrived '
'${sinceTimeout!.inMilliseconds}ms after its window closed: '
'$responsePayload',
'$payloadText',
tag: 'RepeaterCommand',
);
} else {
final payloadText = redactUnmatchedReplyText
? '${responsePayload.length} chars, text withheld'
: responsePayload;
appLogger.warn(
'Reply from $repeaterKey matched no pending or recently expired '
'command (prefix: ${prefix ?? 'none'}): $responsePayload',
'command (prefix: ${prefix ?? 'none'}): $payloadText',
tag: 'RepeaterCommand',
);
}

@ -263,7 +263,7 @@ void main() {
test('Contact.remoteCliAllowed reflects the 0x10 bit', () {
Contact withFlags(int flags) => Contact(
publicKey: Uint8List(32),
name: 'X',
receivedName: 'X',
type: 1,
pathLength: 0,
path: Uint8List(0),

@ -49,7 +49,7 @@ void main() {
connector.contactsForTest.add(
Contact(
publicKey: pubKey,
name: 'Sender',
receivedName: 'Sender',
type: advTypeChat,
pathLength: 0,
path: Uint8List(0),
@ -90,4 +90,48 @@ void main() {
expect(msg!.isCli, isFalse);
expect(msg.isCliCommand, isFalse);
});
group('CLI traffic stays out of the chat thread (#999)', () {
// CLI and chat are separate surfaces: a CLI reply (type-1) or an inbound
// CLI command (type-3) is the CLI console's concern, correlated via the
// receivedFrames listener. It must never land in the contact's
// conversation. The console is tested in cli_console_transport_test.
setUp(() {
// The incoming-message path bails without a self identity; set one
// distinct from the sender so nothing is mistaken for an echo of self.
connector.setSelfPublicKeyForTest(
Uint8List.fromList(List<int>.filled(32, 0xAA)),
);
});
Iterable<dynamic> allMessages() =>
connector.conversationsForTest.values.expand((m) => m);
test('a type-1 CLI reply does not enter the conversation', () async {
connector.handleFrameForTest(
_frame(txtType: txtTypeCliData, pubKey: pubKey, text: 'A1|radio ok'),
);
await Future<void>.delayed(Duration.zero);
expect(allMessages(), isEmpty);
});
test(
'an inbound type-3 CLI command does not enter the conversation',
() async {
connector.handleFrameForTest(
_frame(txtType: txtTypeCliCommand, pubKey: pubKey, text: 'reboot'),
);
await Future<void>.delayed(Duration.zero);
expect(allMessages(), isEmpty);
},
);
test('a plain message does enter the conversation', () async {
connector.handleFrameForTest(
_frame(txtType: txtTypePlain, pubKey: pubKey, text: 'hi there'),
);
await Future<void>.delayed(Duration.zero);
expect(allMessages(), isNotEmpty);
});
});
}

@ -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);
});
}

@ -15,7 +15,9 @@ import 'package:flutter/services.dart';
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/l10n/app_localizations.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/screens/device_cli_screen.dart';
import 'package:meshcore_open/storage/drift/blob_store.dart';
import 'package:meshcore_open/storage/drift/offband_database.dart';
@ -264,4 +266,45 @@ void main() {
final field = tester.widget<TextField>(find.byType(TextField));
expect(field.controller?.text, 'get radio');
});
group('remote companion target (#999)', () {
Contact companion() => Contact(
publicKey: Uint8List.fromList(List<int>.generate(32, (i) => i + 1)),
receivedName: 'Pocket Radio',
type: advTypeChat,
pathLength: 0,
path: Uint8List(0),
lastSeen: DateTime.fromMillisecondsSinceEpoch(0),
);
Future<void> pumpRemote(WidgetTester tester, Contact target) async {
connector.contactsForTest.add(target);
await tester.pumpWidget(
ChangeNotifierProvider<MeshCoreConnector>.value(
value: connector,
child: MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: DeviceCliScreen(remoteContact: target),
),
),
);
await tester.pumpAndSettle();
}
testWidgets('titles with the remote variant and the contact name', (
tester,
) async {
await pumpRemote(tester, companion());
// Remote mode titles "Remote CLI" with the contact as the subtitle,
// rather than the local "Device CLI" + self name/version. The send and
// reply correlation over the mesh are covered in
// cli_console_transport_test; the entry-point gating in
// contact_is_companion_test.
expect(find.text('Remote CLI'), findsOneWidget);
expect(find.text('Pocket Radio'), findsOneWidget);
expect(find.text('Device CLI'), findsNothing);
});
});
}

@ -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…
Cancel
Save

Powered by TurnKey Linux.