Files
chanora/apps/chanora_flutter/lib/main.dart
T
EdisonJwa 43a3c9ba76 feat(events): A.4 — emit SnapshotChanged from the watchdog probe
Adds a new variant to the lifecycle event catalogue so the UI can
auto-refresh the channel/client tree without an independent polling
timer on the Dart side. The supervisor's existing 5 s snapshot probe
is the source of truth: it already pulls a full snapshot to keep
the watchdog honest, so we piggyback on it.

* `chanora_core::SessionEvent::SnapshotChanged { channels, clients }`
  carries the latest channel and client counts.
* The supervisor compares the probe result to `last_counts` and
  fires the event only when the count actually changes. `last_counts`
  is reset to `None` on a successful reconnect so the freshly
  dialled session re-emits its initial counts.
* `chanora_bridge::api::BridgeEvent::SnapshotChanged` is the
  cross-bridge mirror.
* Flutter routes the event through `_onEvent`, which calls
  `_onRefresh()` to repopulate the snapshot view.

The probe-driven detection has known limits — pure within-channel
client moves do not change the count and so are not surfaced. That
gap will close when the supervisor tracks a content hash in
addition to the count; the count-only signal is sufficient for the
common "someone joined / someone left" case observed on cn.teamspeak.app.
2026-05-15 01:27:57 +08:00

614 lines
18 KiB
Dart

// Chanora Flutter application — Beta build (v0.2.0-beta.1).
//
// Adds voice in/out via push-to-talk on top of the Alpha UI:
// 1. Connect form + channel/client tree (Alpha)
// 2. "Start audio" button after connect → opens the audio engine
// 3. Push-to-talk button: hold to transmit, release to stop
// 4. Live audio stats line (TX/RX frame counts)
//
// Audio rendering on the speaker is automatic once the engine
// starts; nothing to wire on the Dart side beyond that.
import 'dart:async';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'l10n/generated/app_localizations.dart';
import 'src/rust/api.dart' as rust;
import 'src/rust/frb_generated.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await RustLib.init();
// A.2 — wire identity persistence to the platform's app-private
// directory so the same TS3 UID is presented on every restart.
// Beta: stored as a plain 0600 file (RISK-PoC-002).
unawaited(_wireStorage());
// A.6.1 — push the OS-reported connectivity state into the core
// supervisor so reconnects redial promptly when the network
// returns.
unawaited(_wireConnectivity());
runApp(const ChanoraApp());
}
Future<void> _wireStorage() async {
try {
final dir = await getApplicationSupportDirectory();
await rust.initStorage(dir: dir.path);
} catch (_) {
// Storage is best-effort — on failure the app still works but
// each session gets a fresh ephemeral identity.
}
}
/// Map `connectivity_plus`' list-of-results to our coarse tri-state.
/// We consider the device "Online" if any of the reported transports
/// is non-`none`. This is intentionally permissive — the supervisor's
/// watchdog still verifies reachability against the actual server.
rust.BridgeNetworkState _mapConnectivity(List<ConnectivityResult> results) {
if (results.isEmpty) return rust.BridgeNetworkState.unknown;
final allNone = results.every((r) => r == ConnectivityResult.none);
if (allNone) return rust.BridgeNetworkState.offline;
return rust.BridgeNetworkState.online;
}
Future<void> _wireConnectivity() async {
final connectivity = Connectivity();
// Seed with the current value so the supervisor has a real reading
// before the first transition.
try {
final initial = await connectivity.checkConnectivity();
rust.setNetworkState(state: _mapConnectivity(initial));
} catch (_) {
// Best effort; if the plugin isn't available on this platform
// we stay at Unknown and the supervisor falls back to its
// watchdog-only behaviour.
}
connectivity.onConnectivityChanged.listen((results) {
rust.setNetworkState(state: _mapConnectivity(results));
});
}
class ChanoraApp extends StatelessWidget {
const ChanoraApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
onGenerateTitle: (ctx) => AppL10n.of(ctx).appTitle,
theme: ThemeData(
useMaterial3: true,
colorSchemeSeed: const Color(0xFF3F51B5),
),
localizationsDelegates: AppL10n.localizationsDelegates,
supportedLocales: AppL10n.supportedLocales,
home: const _BetaHome(),
);
}
}
enum _Phase { idle, connecting, connected }
class _BetaHome extends StatefulWidget {
const _BetaHome();
@override
State<_BetaHome> createState() => _BetaHomeState();
}
class _BetaHomeState extends State<_BetaHome> {
final _hostCtl = TextEditingController(text: 'cn.teamspeak.app');
final _nickCtl = TextEditingController(text: 'ChanoraBeta');
_Phase _phase = _Phase.idle;
rust.BridgeSnapshot? _snapshot;
String? _error;
bool _audioStarted = false;
rust.BridgeAudioStats? _audioStats;
Timer? _statsTimer;
StreamSubscription<rust.BridgeEvent>? _eventsSub;
// A.6 reconnect banner state.
String? _lostReason;
int? _reconnectAttempt;
int? _reconnectDelay;
@override
void initState() {
super.initState();
_eventsSub = rust.eventsStream().listen(_onEvent);
}
void _onEvent(rust.BridgeEvent evt) {
if (!mounted) return;
switch (evt) {
case rust.BridgeEvent_Connected():
setState(() {
_phase = _Phase.connected;
_lostReason = null;
_reconnectAttempt = null;
_reconnectDelay = null;
});
case rust.BridgeEvent_Lost(:final reason):
setState(() {
_lostReason = reason;
_reconnectAttempt = null;
_reconnectDelay = null;
});
case rust.BridgeEvent_Reconnecting(:final attempt, :final delaySecs):
setState(() {
_reconnectAttempt = attempt;
_reconnectDelay = delaySecs;
});
case rust.BridgeEvent_Disconnected():
setState(() {
_phase = _Phase.idle;
_lostReason = null;
_reconnectAttempt = null;
_reconnectDelay = null;
});
case rust.BridgeEvent_AudioStarted():
setState(() => _audioStarted = true);
case rust.BridgeEvent_AudioStopped():
setState(() => _audioStarted = false);
case rust.BridgeEvent_SnapshotChanged():
// A.4: the supervisor's watchdog observed a tree change.
// Trigger a single async refresh so the channel/client
// list stays current without a polling timer on the Dart
// side.
unawaited(_onRefresh());
}
}
@override
void dispose() {
_eventsSub?.cancel();
_statsTimer?.cancel();
_hostCtl.dispose();
_nickCtl.dispose();
super.dispose();
}
Future<void> _onConnect() async {
setState(() {
_phase = _Phase.connecting;
_error = null;
_snapshot = null;
});
try {
final snap = await rust.connect(
host: _hostCtl.text.trim(),
nickname: _nickCtl.text.trim(),
);
if (!mounted) return;
setState(() {
_phase = _Phase.connected;
_snapshot = snap;
});
} catch (e) {
if (!mounted) return;
setState(() {
_phase = _Phase.idle;
_error = e.toString();
});
}
}
Future<void> _onStartAudio() async {
try {
await rust.startAudio();
if (!mounted) return;
setState(() => _audioStarted = true);
_statsTimer?.cancel();
_statsTimer = Timer.periodic(const Duration(milliseconds: 500), (_) async {
try {
final s = await rust.audioStats();
if (!mounted) return;
setState(() => _audioStats = s);
} catch (_) {}
});
} catch (e) {
if (!mounted) return;
setState(() => _error = e.toString());
}
}
Future<void> _setPtt(bool active) async {
try {
await rust.setPtt(active: active);
} catch (e) {
if (!mounted) return;
setState(() => _error = e.toString());
}
}
Future<void> _onRefresh() async {
try {
final snap = await rust.snapshot();
if (!mounted) return;
setState(() => _snapshot = snap);
} catch (e) {
if (!mounted) return;
setState(() => _error = e.toString());
}
}
Future<void> _onDisconnect() async {
_statsTimer?.cancel();
_statsTimer = null;
try {
await rust.disconnect();
} catch (_) {}
if (!mounted) return;
setState(() {
_phase = _Phase.idle;
_snapshot = null;
_audioStarted = false;
_audioStats = null;
_error = null;
});
}
Future<void> _onShowDiagnostics(BuildContext context) async {
// A.3: user-initiated diagnostic export (DEC-016). Content is
// already redacted on the Rust side; we just present it.
final l10n = AppL10n.of(context);
final text = rust.exportDiagnostics();
if (!mounted) return;
await showDialog<void>(
context: context,
builder: (ctx) => AlertDialog(
title: Text(l10n.diagnosticsAction),
content: SingleChildScrollView(
child: SelectableText(
text,
style: const TextStyle(fontFamily: 'monospace', fontSize: 11),
),
),
actions: [
TextButton(
onPressed: () async {
await Clipboard.setData(ClipboardData(text: text));
if (!ctx.mounted) return;
Navigator.of(ctx).pop();
},
child: Text(l10n.copyAction),
),
TextButton(
onPressed: () => Navigator.of(ctx).pop(),
child: Text(l10n.closeAction),
),
],
),
);
}
@override
Widget build(BuildContext context) {
final l10n = AppL10n.of(context);
final theme = Theme.of(context);
String statusText() {
switch (_phase) {
case _Phase.idle:
return _error != null ? l10n.statusError(_error!) : l10n.statusIdle;
case _Phase.connecting:
return l10n.statusConnecting;
case _Phase.connected:
return l10n.statusConnected(_snapshot?.serverName ?? '');
}
}
return Scaffold(
appBar: AppBar(
title: Text(l10n.appTitle),
actions: [
IconButton(
tooltip: l10n.diagnosticsAction,
icon: const Icon(Icons.bug_report_outlined),
onPressed: () => _onShowDiagnostics(context),
),
if (_phase == _Phase.connected) ...[
IconButton(
tooltip: l10n.refreshAction,
icon: const Icon(Icons.refresh),
onPressed: _onRefresh,
),
IconButton(
tooltip: l10n.disconnectAction,
icon: const Icon(Icons.logout),
onPressed: _onDisconnect,
),
],
],
),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: theme.colorScheme.tertiaryContainer,
borderRadius: BorderRadius.circular(8),
),
child: Text(
l10n.homeNotProductionReadyBanner,
style: TextStyle(color: theme.colorScheme.onTertiaryContainer),
),
),
const SizedBox(height: 12),
Text(statusText(), style: theme.textTheme.titleMedium),
if (_lostReason != null || _reconnectAttempt != null) ...[
const SizedBox(height: 8),
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: theme.colorScheme.errorContainer,
borderRadius: BorderRadius.circular(8),
),
child: Row(
children: [
SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(
strokeWidth: 2,
color: theme.colorScheme.onErrorContainer,
),
),
const SizedBox(width: 10),
Expanded(
child: Text(
_reconnectAttempt != null
? l10n.statusReconnecting(
_reconnectAttempt!,
_reconnectDelay ?? 0,
)
: l10n.statusConnectionLost(_lostReason ?? ''),
style: TextStyle(
color: theme.colorScheme.onErrorContainer,
),
),
),
],
),
),
],
const SizedBox(height: 12),
if (_phase == _Phase.idle) ...[
_ConnectForm(
hostCtl: _hostCtl,
nickCtl: _nickCtl,
onConnect: _onConnect,
),
] else if (_phase == _Phase.connecting) ...[
const Center(
child: Padding(
padding: EdgeInsets.all(32),
child: CircularProgressIndicator(),
),
),
] else if (_phase == _Phase.connected && _snapshot != null) ...[
// Audio row: start button or stats + PTT.
if (!_audioStarted) ...[
FilledButton.icon(
icon: const Icon(Icons.mic_none),
label: Text(l10n.startAudioAction),
onPressed: _onStartAudio,
),
const SizedBox(height: 12),
] else ...[
_AudioControls(
stats: _audioStats,
onPttDown: () => _setPtt(true),
onPttUp: () => _setPtt(false),
),
const SizedBox(height: 12),
],
Expanded(child: _SnapshotView(snapshot: _snapshot!)),
],
],
),
),
);
}
}
class _ConnectForm extends StatelessWidget {
const _ConnectForm({
required this.hostCtl,
required this.nickCtl,
required this.onConnect,
});
final TextEditingController hostCtl;
final TextEditingController nickCtl;
final VoidCallback onConnect;
@override
Widget build(BuildContext context) {
final l10n = AppL10n.of(context);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextField(
controller: hostCtl,
decoration: InputDecoration(
labelText: l10n.fieldServerHost,
border: const OutlineInputBorder(),
),
),
const SizedBox(height: 8),
TextField(
controller: nickCtl,
decoration: InputDecoration(
labelText: l10n.fieldNickname,
border: const OutlineInputBorder(),
),
),
const SizedBox(height: 16),
FilledButton.icon(
icon: const Icon(Icons.login),
label: Text(l10n.connectAction),
onPressed: onConnect,
),
],
);
}
}
class _AudioControls extends StatefulWidget {
const _AudioControls({
required this.stats,
required this.onPttDown,
required this.onPttUp,
});
final rust.BridgeAudioStats? stats;
final VoidCallback onPttDown;
final VoidCallback onPttUp;
@override
State<_AudioControls> createState() => _AudioControlsState();
}
class _AudioControlsState extends State<_AudioControls> {
bool _pressed = false;
@override
Widget build(BuildContext context) {
final l10n = AppL10n.of(context);
final theme = Theme.of(context);
final stats = widget.stats;
final statsText = stats == null
? '—'
: l10n.audioStatsLine(
stats.framesSent,
stats.framesReceived,
stats.pttActive ? 'on' : 'off',
);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Listener(
onPointerDown: (_) {
setState(() => _pressed = true);
widget.onPttDown();
},
onPointerUp: (_) {
setState(() => _pressed = false);
widget.onPttUp();
},
onPointerCancel: (_) {
setState(() => _pressed = false);
widget.onPttUp();
},
child: Container(
padding: const EdgeInsets.symmetric(vertical: 16),
decoration: BoxDecoration(
color: _pressed
? theme.colorScheme.primary
: theme.colorScheme.primaryContainer,
borderRadius: BorderRadius.circular(12),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
_pressed ? Icons.mic : Icons.mic_off,
color: _pressed
? theme.colorScheme.onPrimary
: theme.colorScheme.onPrimaryContainer,
),
const SizedBox(width: 8),
Text(
_pressed ? l10n.pttTransmitting : l10n.pttHoldToTalk,
style: TextStyle(
color: _pressed
? theme.colorScheme.onPrimary
: theme.colorScheme.onPrimaryContainer,
fontWeight: FontWeight.w600,
),
),
],
),
),
),
const SizedBox(height: 6),
Text(statsText, style: theme.textTheme.bodySmall),
],
);
}
}
class _SnapshotView extends StatelessWidget {
const _SnapshotView({required this.snapshot});
final rust.BridgeSnapshot snapshot;
@override
Widget build(BuildContext context) {
final l10n = AppL10n.of(context);
final theme = Theme.of(context);
final channels = [...snapshot.channels]
..sort((a, b) => a.order.compareTo(b.order));
final byChannel = <BigInt, List<rust.BridgeClient>>{};
for (final c in snapshot.clients) {
byChannel.putIfAbsent(c.channel, () => []).add(c);
}
return ListView(
children: [
Text(
l10n.countChannelsAndClients(
snapshot.channels.length,
snapshot.clients.length,
),
style: theme.textTheme.bodyMedium,
),
if (snapshot.welcomeMessage.isNotEmpty) ...[
const SizedBox(height: 8),
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(6),
),
// Server-provided content; preserved verbatim per ADR-008.
child: Text(snapshot.welcomeMessage, style: theme.textTheme.bodySmall),
),
],
const Divider(height: 24),
Text(l10n.channelsHeading, style: theme.textTheme.titleMedium),
const SizedBox(height: 4),
for (final ch in channels) ...[
ListTile(
dense: true,
leading: const Icon(Icons.tag),
title: Text(ch.name),
subtitle: Text('id=${ch.id} parent=${ch.parent}'),
),
for (final cl in byChannel[ch.id] ?? const <rust.BridgeClient>[])
Padding(
padding: const EdgeInsets.only(left: 64),
child: ListTile(
dense: true,
visualDensity: VisualDensity.compact,
leading: const Icon(Icons.person, size: 18),
title: Text(cl.name),
),
),
],
],
);
}
}