From dd1a36ceb4bf67f38d1ecd0cf3a719a268d4e0f5 Mon Sep 17 00:00:00 2001 From: OrientCOMPASS <316423573+OrientCOMPASS@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:34:09 +0800 Subject: [PATCH 01/12] feat(protocol): report phone battery to the desktop --- tauri-app/crates/micyou-cli/src/events.rs | 14 +++- tauri-app/crates/micyou-core/src/events.rs | 5 +- tauri-app/crates/micyou-core/src/settings.rs | 7 +- tauri-app/crates/micyou-core/src/stats.rs | 68 ++++++++++++++++++- .../crates/micyou-core/src/transport/tcp.rs | 24 +++++++ .../micyou-protocol/proto/network.proto | 10 +++ tauri-app/crates/micyou-tui/src/events.rs | 8 ++- tauri-app/crates/micyou-tui/src/i18n.rs | 7 ++ tauri-app/crates/micyou-tui/src/tui.rs | 32 ++++++++- tauri-app/src-tauri/src/events.rs | 5 +- 10 files changed, 173 insertions(+), 7 deletions(-) diff --git a/tauri-app/crates/micyou-cli/src/events.rs b/tauri-app/crates/micyou-cli/src/events.rs index 2a91e294..7d6b05d0 100644 --- a/tauri-app/crates/micyou-cli/src/events.rs +++ b/tauri-app/crates/micyou-cli/src/events.rs @@ -14,7 +14,7 @@ */ use micyou_core::events::{AecStatus, DownloadProgress, ServerEvents, SpectrumPayload}; -use micyou_core::stats::AudioMetrics; +use micyou_core::stats::{AudioMetrics, BatteryStatus}; use micyou_core::transport::tcp::DeviceInfo; /// Log-mode events: print a compact line per event. @@ -40,6 +40,18 @@ impl ServerEvents for CliEventSink { println!("[mic] disconnected"); } + fn client_battery(&self, battery: Option) { + // Only the reported state is worth a line; clearing on disconnect is + // already covered by [mic] disconnected. + if let Some(battery) = battery { + println!( + "[mic] battery {}%{}", + battery.level, + if battery.charging { " (charging)" } else { "" } + ); + } + } + fn audio_metrics(&self, metrics: AudioMetrics) { // 每秒触发一次的高频统计:静默模式(-q)下与 [level] 一并屏蔽 if self.quiet { diff --git a/tauri-app/crates/micyou-core/src/events.rs b/tauri-app/crates/micyou-core/src/events.rs index dc8fcd8c..25d16f6b 100644 --- a/tauri-app/crates/micyou-core/src/events.rs +++ b/tauri-app/crates/micyou-core/src/events.rs @@ -13,7 +13,7 @@ * GNU General Public License for more details. */ -use crate::stats::AudioMetrics; +use crate::stats::{AudioMetrics, BatteryStatus}; use crate::transport::tcp::DeviceInfo; use std::sync::Arc; @@ -25,6 +25,9 @@ use std::sync::Arc; pub trait ServerEvents: Send + Sync + 'static { fn device_connected(&self, info: DeviceInfo); fn device_disconnected(&self); + /// Battery reported by the connected phone. `None` clears it (device + /// disconnected, or the phone could not read its charge). + fn client_battery(&self, battery: Option); fn audio_metrics(&self, metrics: AudioMetrics); fn udp_audio_warning(&self); fn mute_state_changed(&self, is_muted: bool); diff --git a/tauri-app/crates/micyou-core/src/settings.rs b/tauri-app/crates/micyou-core/src/settings.rs index 328b959e..932d455a 100644 --- a/tauri-app/crates/micyou-core/src/settings.rs +++ b/tauri-app/crates/micyou-core/src/settings.rs @@ -106,6 +106,9 @@ pub struct StreamingStatus { pub is_connected: bool, pub is_muted: bool, pub platform: crate::transport::tcp::ClientPlatform, + /// Battery reported by the connected phone. `None` when nothing is + /// connected, the client is legacy, or it could not read its charge. + pub battery: Option, } /// Handles on the live server state that runtime controls act on. @@ -301,6 +304,7 @@ impl ServerState { is_connected: control_platform.is_some() || audio_active || web_connected, is_muted: self.network_stats.is_muted(), platform: control_platform.unwrap_or_default(), + battery: self.network_stats.battery(), } } } @@ -310,7 +314,7 @@ mod tests { use crate::events::{AecStatus, DownloadProgress, ServerEvents, SpectrumPayload}; use crate::host::{HostIntegration, HotkeyCallback}; use crate::server::ServerState; - use crate::stats::AudioMetrics; + use crate::stats::{AudioMetrics, BatteryStatus}; use crate::transport::tcp::{ActiveConnection, DeviceInfo}; use std::sync::Arc; use std::time::Duration; @@ -321,6 +325,7 @@ mod tests { impl ServerEvents for NoEvents { fn device_connected(&self, _: DeviceInfo) {} fn device_disconnected(&self) {} + fn client_battery(&self, _: Option) {} fn audio_metrics(&self, _: AudioMetrics) {} fn udp_audio_warning(&self) {} fn mute_state_changed(&self, _: bool) {} diff --git a/tauri-app/crates/micyou-core/src/stats.rs b/tauri-app/crates/micyou-core/src/stats.rs index 1102a9e9..87752911 100644 --- a/tauri-app/crates/micyou-core/src/stats.rs +++ b/tauri-app/crates/micyou-core/src/stats.rs @@ -14,9 +14,18 @@ */ use serde::Serialize; -use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicI32, AtomicI64, AtomicU32, AtomicU64, Ordering}; use std::sync::Arc; +/// Battery state reported by the connected phone. `level` is 0-100, or a +/// negative value when the client could not read its charge. +#[derive(Serialize, Clone, Copy, Debug, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct BatteryStatus { + pub level: i32, + pub charging: bool, +} + #[derive(Serialize, Clone, Debug)] #[serde(rename_all = "camelCase")] pub struct AudioMetrics { @@ -47,6 +56,11 @@ pub struct NetworkStats { pub channels: AtomicU32, pub input_level_bits: AtomicU32, pub processed_level_bits: AtomicU32, + /// Battery reported by the phone (`ClientStatusMessage`); -1 = unknown. + /// Cleared on every session boundary so a reconnect never inherits the + /// previous device's charge. + pub battery_level: AtomicI32, + pub battery_charging: AtomicBool, } impl Default for NetworkStats { @@ -64,6 +78,8 @@ impl Default for NetworkStats { channels: AtomicU32::new(0), input_level_bits: AtomicU32::new(0f32.to_bits()), processed_level_bits: AtomicU32::new(0f32.to_bits()), + battery_level: AtomicI32::new(-1), + battery_charging: AtomicBool::new(false), } } } @@ -116,6 +132,7 @@ impl NetworkStats { self.tcp_connected_time_ms.store(time_ms, Ordering::Relaxed); self.last_udp_packet_time_ms.store(0, Ordering::Relaxed); self.last_audio_packet_time_ms.store(0, Ordering::Relaxed); + self.clear_battery(); } pub fn mark_tcp_disconnected(&self) { self.tcp_connected_time_ms.store(0, Ordering::Relaxed); @@ -124,6 +141,7 @@ impl NetworkStats { self.loss_rate_bits.store(0f64.to_bits(), Ordering::Relaxed); self.jitter_bits.store(0f64.to_bits(), Ordering::Relaxed); self.rtt_ms.store(0, Ordering::Relaxed); + self.clear_battery(); } pub fn get_tcp_connected_time(&self) -> u64 { self.tcp_connected_time_ms.load(Ordering::Relaxed) @@ -154,6 +172,25 @@ impl NetworkStats { self.processed_level_bits.store(processed.to_bits(), Ordering::Relaxed); } + pub fn set_battery(&self, level: i32, charging: bool) { + self.battery_level.store(level, Ordering::Relaxed); + self.battery_charging.store(charging, Ordering::Relaxed); + } + + /// Battery reported by the phone, or `None` until it sends a usable level. + pub fn battery(&self) -> Option { + let level = self.battery_level.load(Ordering::Relaxed); + (0..=100).contains(&level).then(|| BatteryStatus { + level, + charging: self.battery_charging.load(Ordering::Relaxed), + }) + } + + pub fn clear_battery(&self) { + self.battery_level.store(-1, Ordering::Relaxed); + self.battery_charging.store(false, Ordering::Relaxed); + } + pub fn to_metrics(&self, buffer_duration: i64) -> AudioMetrics { let rtt = self.get_rtt(); AudioMetrics { @@ -356,4 +393,33 @@ mod tests { assert_eq!(stats.get_loss_rate(), 0.0); assert_eq!(stats.get_jitter(), 0.0); } + + #[test] + fn battery_reports_valid_levels_and_resets_between_sessions() { + let stats = NetworkStats::default(); + assert_eq!(stats.battery(), None, "no report yet"); + + stats.set_battery(78, true); + assert_eq!( + stats.battery(), + Some(BatteryStatus { + level: 78, + charging: true + }) + ); + + // A nonsense level stays "unknown" instead of being clamped into a lie. + stats.set_battery(120, false); + assert_eq!(stats.battery(), None); + + stats.set_battery(4, false); + assert_eq!(stats.battery().map(|b| b.level), Some(4)); + + stats.mark_tcp_disconnected(); + assert_eq!(stats.battery(), None, "cleared on disconnect"); + + stats.set_battery(40, true); + stats.mark_tcp_connected(1); + assert_eq!(stats.battery(), None, "cleared on connect"); + } } diff --git a/tauri-app/crates/micyou-core/src/transport/tcp.rs b/tauri-app/crates/micyou-core/src/transport/tcp.rs index 3f030848..41c8f6b6 100644 --- a/tauri-app/crates/micyou-core/src/transport/tcp.rs +++ b/tauri-app/crates/micyou-core/src/transport/tcp.rs @@ -677,6 +677,7 @@ async fn handle_client( pong: None, plugin_message: None, stats: None, + client_status: None, }; if tx_ping.send(ping_msg).await.is_err() { break; @@ -773,6 +774,8 @@ async fn handle_client( .unwrap_or_else(|poisoned| poisoned.into_inner()) = ActiveAudioSession::default(); stats.mark_tcp_disconnected(); events.device_disconnected(); + // The charge belongs to the device that just left; the next one starts unknown. + events.client_battery(stats.battery()); plugins.broadcast_event(&micyou_plugin::PluginEvent::DeviceDisconnected); } // Release the plugin sync slot if it still points at this session. @@ -847,6 +850,7 @@ async fn handle_message( }), plugin_message: None, stats: None, + client_status: None, }; let permit = tokio::select! { biased; @@ -894,6 +898,26 @@ async fn handle_message( plugins.bus.handle_incoming(&logical); } } + if let Some(client_status) = msg.client_status { + // Battery report from the phone. A superseded connection must not + // overwrite the live device's charge either. + if is_active(active_connection, takeover_token, connection_id).await { + let battery = clamp_battery(client_status.battery_level, client_status.is_charging); + stats.set_battery( + battery.map_or(-1, |battery| battery.level), + client_status.is_charging, + ); + events.client_battery(battery); + } + } +} + +/// Phone battery report → public status. Out-of-range levels mean "unknown" +/// rather than being clamped into a plausible-looking lie. +fn clamp_battery(level: i32, charging: bool) -> Option { + (0..=100) + .contains(&level) + .then_some(crate::stats::BatteryStatus { level, charging }) } #[cfg(test)] diff --git a/tauri-app/crates/micyou-protocol/proto/network.proto b/tauri-app/crates/micyou-protocol/proto/network.proto index 82045a9f..80813490 100644 --- a/tauri-app/crates/micyou-protocol/proto/network.proto +++ b/tauri-app/crates/micyou-protocol/proto/network.proto @@ -15,6 +15,16 @@ message MessageWrapper { // Desktop to phone once a second while connected, so the phone can show link quality. // Unknown to legacy clients: proto3 skips it, so the wire stays compatible. StatsMessage stats = 8; + // Phone to desktop: battery level and charging state, pushed after the + // handshake and whenever either value changes. Legacy desktops skip it. + ClientStatusMessage clientStatus = 9; +} + +// Client status reported by the phone (currently just its battery), so the +// desktop can show the device's charge next to the connection state. +message ClientStatusMessage { + int32 batteryLevel = 1; // 0-100; -1 means unknown / not available + bool isCharging = 2; } // Receive-side link statistics measured by the desktop. diff --git a/tauri-app/crates/micyou-tui/src/events.rs b/tauri-app/crates/micyou-tui/src/events.rs index b4b02157..02b82aeb 100644 --- a/tauri-app/crates/micyou-tui/src/events.rs +++ b/tauri-app/crates/micyou-tui/src/events.rs @@ -14,7 +14,7 @@ */ use micyou_core::events::{AecStatus, DownloadProgress, ServerEvents, SpectrumPayload}; -use micyou_core::stats::AudioMetrics; +use micyou_core::stats::{AudioMetrics, BatteryStatus}; use micyou_core::transport::tcp::DeviceInfo; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::mpsc::Sender; @@ -25,6 +25,8 @@ use std::time::Instant; pub enum Event { DeviceConnected(DeviceInfo), DeviceDisconnected, + /// Battery reported by the phone; `None` clears it. + Battery(Option), Metrics(AudioMetrics), UdpWarning, MuteChanged(bool), @@ -101,6 +103,10 @@ impl ServerEvents for TuiEventSink { let _ = self.tx.send(Event::DeviceDisconnected); } + fn client_battery(&self, battery: Option) { + let _ = self.tx.send(Event::Battery(battery)); + } + fn audio_metrics(&self, metrics: AudioMetrics) { let _ = self.tx.send(Event::Metrics(metrics)); } diff --git a/tauri-app/crates/micyou-tui/src/i18n.rs b/tauri-app/crates/micyou-tui/src/i18n.rs index 5b4c436a..8911049e 100644 --- a/tauri-app/crates/micyou-tui/src/i18n.rs +++ b/tauri-app/crates/micyou-tui/src/i18n.rs @@ -156,6 +156,7 @@ const ZH: Dict = Dict { ("staged_hint", "更改模式/端口后需重启生效"), ("level_overflow", "电平过高"), ], + ("battery", "电量"), }; const EN: Dict = Dict { @@ -250,6 +251,7 @@ const EN: Dict = Dict { ("staged_hint", "Mode/port changes require a restart"), ("level_overflow", "Level too high"), ], + ("battery", "Battery"), }; const CAT: Dict = Dict { @@ -341,6 +343,7 @@ const CAT: Dict = Dict { ("staged_hint", "更改模式/端口后需重启生效喵~"), ("level_overflow", "电平过高"), ], + ("battery", "Bateria"), }; const LZH: Dict = Dict { @@ -423,6 +426,7 @@ const LZH: Dict = Dict { ("staged_hint", "改模式/端口后需重启"), ("level_overflow", "电平过高"), ], + ("battery", "電量"), }; const ZH_HK: Dict = Dict { @@ -505,6 +509,7 @@ const ZH_HK: Dict = Dict { ("staged_hint", "改模式/埠之後要重啟先得"), ("level_overflow", "電平過高"), ], + ("battery", "電量"), }; const ZH_SS: Dict = Dict { @@ -593,6 +598,7 @@ const ZH_SS: Dict = Dict { ("staged_hint", "更改模式/端口后需重启生效"), ("level_overflow", "电平过高"), ], + ("battery", "电量"), }; const ZH_TW: Dict = Dict { @@ -681,6 +687,7 @@ const ZH_TW: Dict = Dict { ("staged_hint", "變更模式/連接埠後需重新啟動"), ("level_overflow", "電平過高"), ], + ("battery", "電量"), }; fn dict_for(lang: &str) -> &'static Dict { diff --git a/tauri-app/crates/micyou-tui/src/tui.rs b/tauri-app/crates/micyou-tui/src/tui.rs index 10ff9801..a999a3ff 100644 --- a/tauri-app/crates/micyou-tui/src/tui.rs +++ b/tauri-app/crates/micyou-tui/src/tui.rs @@ -38,7 +38,7 @@ use std::time::Instant; use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System}; use micyou_core::config::ServerPrefs; use micyou_core::server::ServerState; -use micyou_core::stats::AudioMetrics; +use micyou_core::stats::{AudioMetrics, BatteryStatus}; use micyou_core::transport::tcp::DeviceInfo; /// Vertical split of the whole screen: [title, tabs, body, footer]. @@ -59,6 +59,8 @@ pub struct TuiApp { pub port: u16, pub mode: String, pub device: Option, + /// Battery reported by the connected phone (None = unknown/unreported). + pub battery: Option, pub metrics: Option, pub level: u32, pub muted: bool, @@ -114,6 +116,7 @@ impl TuiApp { port, mode, device: None, + battery: None, metrics: None, level: 0, muted: false, @@ -194,8 +197,22 @@ impl TuiApp { } Event::DeviceDisconnected => { self.device = None; + self.battery = None; self.log("[warn] mic disconnected".to_string()); } + Event::Battery(battery) => { + let changed = battery != self.battery; + self.battery = battery; + if changed { + if let Some(battery) = battery { + self.log(format!( + "[inf] battery {}%{}", + battery.level, + if battery.charging { " (charging)" } else { "" } + )); + } + } + } Event::Metrics(m) => { let latency = m.latency_ms.max(0) as u64; self.metrics = Some(m); @@ -520,6 +537,19 @@ impl TuiApp { Style::default().fg(theme.tertiary.to_color()), )], )); + if let Some(battery) = self.battery { + rows.push(row( + self.t("battery").as_str(), + vec![Span::styled( + if battery.charging { + format!("{}% ⚡", battery.level) + } else { + format!("{}%", battery.level) + }, + Style::default().fg(theme.tertiary.to_color()), + )], + )); + } } None => { rows.push(row( diff --git a/tauri-app/src-tauri/src/events.rs b/tauri-app/src-tauri/src/events.rs index 399077bb..90e377d3 100644 --- a/tauri-app/src-tauri/src/events.rs +++ b/tauri-app/src-tauri/src/events.rs @@ -16,7 +16,7 @@ //! Forwards core server events to the webview. use micyou_core::events::{AecStatus, DownloadProgress, ServerEvents, SpectrumPayload}; -use micyou_core::stats::AudioMetrics; +use micyou_core::stats::{AudioMetrics, BatteryStatus}; use micyou_core::transport::tcp::DeviceInfo; use serde::Serialize; use tauri::{AppHandle, Emitter, Manager}; @@ -38,6 +38,9 @@ impl ServerEvents for TauriEventSink { fn device_disconnected(&self) { self.emit("device-disconnected", ()); } + fn client_battery(&self, battery: Option) { + self.emit("client-battery", battery); + } fn audio_metrics(&self, metrics: AudioMetrics) { self.emit("audio-metrics", metrics); } From c1a9a71fd50fbfdd57de57964385e84efc807830 Mon Sep 17 00:00:00 2001 From: OrientCOMPASS <316423573+OrientCOMPASS@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:42:23 +0800 Subject: [PATCH 02/12] feat(ui): show the phone battery next to the connection status --- tauri-app/src/App.vue | 16 +++++++++++++++- .../connection/composables/useServer.ts | 17 +++++++++++++++++ tauri-app/src/platform/events.ts | 4 +++- tauri-app/src/platform/types.ts | 8 ++++++++ tauri-app/src/shared/locales/cat.json | 2 ++ tauri-app/src/shared/locales/en.json | 2 ++ tauri-app/src/shared/locales/lzh.json | 2 ++ tauri-app/src/shared/locales/zh-hk.json | 2 ++ tauri-app/src/shared/locales/zh-ss.json | 2 ++ tauri-app/src/shared/locales/zh-tw.json | 2 ++ tauri-app/src/shared/locales/zh.json | 2 ++ 11 files changed, 57 insertions(+), 2 deletions(-) diff --git a/tauri-app/src/App.vue b/tauri-app/src/App.vue index 29d74a99..55c72f0b 100644 --- a/tauri-app/src/App.vue +++ b/tauri-app/src/App.vue @@ -8,7 +8,8 @@ import { useI18n } from 'vue-i18n'; import { Mic, Wifi, RadioTower, Globe, ChevronDown, CheckCircle2, Settings, Link, Unlink, RefreshCw, ActivitySquare as MonitoringIcon, X, Minus, - VolumeX, Volume2, Headphones, QrCode as QrCodeIcon, Loader2 + VolumeX, Volume2, Headphones, QrCode as QrCodeIcon, Loader2, + BatteryCharging, BatteryMedium } from '@lucide/vue'; // Composables managing server connection, audio, theme, window, and system tray @@ -686,6 +687,19 @@ onUnmounted(() => {

{{ server.statusDescription.value }}

+ +
+ + + {{ $t('app.status.battery', { level: server.deviceBattery.value.level }) }} + {{ $t('app.status.charging') }} +
diff --git a/tauri-app/src/features/connection/composables/useServer.ts b/tauri-app/src/features/connection/composables/useServer.ts index 1d23673b..c7bb41e0 100644 --- a/tauri-app/src/features/connection/composables/useServer.ts +++ b/tauri-app/src/features/connection/composables/useServer.ts @@ -11,6 +11,7 @@ import { notify, onEvent, type AdbDevice, + type BatteryStatus, type ClientPlatform, type NetworkInfo, type NetworkInterfaceInfo, @@ -107,6 +108,10 @@ export function useServer(options?: { audioLevel?: Ref; isMuted?: Ref('unknown'); + // Battery the connected phone reported; null when it is unknown or a + // legacy client never sends one. + const deviceBattery = ref(null); + // Computes the display representation of the active bind IP address const displayIp = computed(() => { if (isAutoBind.value) { @@ -250,6 +255,7 @@ export function useServer(options?: { audioLevel?: Ref; isMuted?: Ref null); if (status?.isConnected) { clientPlatform.value = status.platform; + deviceBattery.value = status.battery ?? null; ensureStreamingState(); } else if (serverState.value === 'starting') { serverState.value = 'connecting'; @@ -398,6 +404,8 @@ export function useServer(options?: { audioLevel?: Ref; isMuted?: Ref; isMuted?: Ref { + deviceBattery.value = battery; + if (battery) healPendingStart(); + })), // Stops triggered elsewhere (tray, plugins, another window) track(onEvent('server-stopped', () => { resetToIdle(); + deviceBattery.value = null; if (options?.isMuted) options.isMuted.value = false; })), // Metrics only flow while a TCP session is up @@ -488,6 +502,7 @@ export function useServer(options?: { audioLevel?: Ref; isMuted?: Ref; isMuted?: Ref Date: Wed, 25 Nov 2026 13:47:22 +0800 Subject: [PATCH 03/12] feat(android): report battery and show desktop link quality --- AGENTS.md | 2 +- .../com/lanrhyme/micyou/audio/AudioEngine.kt | 32 +++ .../micyou/audio/BatteryStatusReporter.kt | 86 +++++++ .../com/lanrhyme/micyou/audio/LinkQuality.kt | 32 +++ .../com/lanrhyme/micyou/network/Protocol.kt | 36 ++- .../lanrhyme/micyou/ui/LinkQualityPanel.kt | 225 ++++++++++++++++++ .../com/lanrhyme/micyou/ui/MobileHome.kt | 34 +++ .../micyou/viewmodel/MainViewModel.kt | 22 +- composeApp/src/main/res/values-ca/strings.xml | 11 + composeApp/src/main/res/values-en/strings.xml | 11 + .../src/main/res/values-zh-rHD/strings.xml | 11 + .../src/main/res/values-zh-rHK/strings.xml | 11 + .../src/main/res/values-zh-rTW/strings.xml | 11 + composeApp/src/main/res/values-zh/strings.xml | 11 + composeApp/src/main/res/values/strings.xml | 11 + 15 files changed, 542 insertions(+), 4 deletions(-) create mode 100644 composeApp/src/main/kotlin/com/lanrhyme/micyou/audio/BatteryStatusReporter.kt create mode 100644 composeApp/src/main/kotlin/com/lanrhyme/micyou/audio/LinkQuality.kt create mode 100644 composeApp/src/main/kotlin/com/lanrhyme/micyou/ui/LinkQualityPanel.kt diff --git a/AGENTS.md b/AGENTS.md index 905fbb7f..8f052a1e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,7 +25,7 @@ flowchart LR ## Wire protocol - Source of truth: `tauri-app/crates/micyou-protocol/proto/network.proto` (prost); the Android mirror is `composeApp/.../network/Protocol.kt` and must stay in sync, magics included (`0x4D696359` control, `0x4D696355` audio) -- TCP carries control frames (connect, mute, ping, pong, and desktop-to-phone stats once a second) with a 1 MiB payload cap enforced on both sides; `connect.platform` tells iOS and Android apart +- TCP carries control frames (connect, mute, ping, pong, desktop-to-phone stats once a second, phone-to-desktop battery reports) with a 1 MiB payload cap enforced on both sides; `connect.platform` tells iOS and Android apart - UDP carries audio on TCP port + 1; Opus uses 20 ms frames with one FEC packet per group of 12 - Connection modes: **wifi** (LAN, mDNS `_micyou._tcp.`), **usb** (`adb reverse` for Android; for iOS `platform/usbmux.rs` polls usbmuxd and connects to the app listening on the phone, then splices it into the local server; either way connections arrive on loopback, so USB mode listens on 127.0.0.1 only, ignores the saved bind interface and skips mDNS), **web** (axum TLS WebSocket, feature-gated) diff --git a/composeApp/src/main/kotlin/com/lanrhyme/micyou/audio/AudioEngine.kt b/composeApp/src/main/kotlin/com/lanrhyme/micyou/audio/AudioEngine.kt index 4651ee3d..363d85d1 100644 --- a/composeApp/src/main/kotlin/com/lanrhyme/micyou/audio/AudioEngine.kt +++ b/composeApp/src/main/kotlin/com/lanrhyme/micyou/audio/AudioEngine.kt @@ -364,6 +364,13 @@ class AudioEngine constructor() { ) val pluginMessages: SharedFlow = _pluginMessages.asSharedFlow() + // 桌面端每秒推送的链路质量(MessageWrapper 字段 8);旧桌面不发送, + // 此时保持 null,界面据此隐藏入口。 + private val _linkQuality = MutableStateFlow(null) + val linkQuality: Flow = _linkQuality + + fun currentLinkQuality(): LinkQuality? = _linkQuality.value + private data class StopResources( val sessionJob: Job?, val recorder: AudioRecord?, @@ -498,6 +505,7 @@ class AudioEngine constructor() { lifecycleGeneration++ val sessionGeneration = lifecycleGeneration _state.value = StreamState.Connecting + _linkQuality.value = null val sessionJob = lifecycleScope.launch(start = CoroutineStart.LAZY) { var recorder: AudioRecord? = null var sessionUdpSocket: DatagramSocket? = null @@ -520,6 +528,7 @@ class AudioEngine constructor() { var output: ByteWriteChannel? = null var selectorManager: SelectorManager? = null var closeConnection: () -> Unit = {} + var batteryReporter: BatteryStatusReporter? = null val sessionJobIdentity = requireNotNull(currentCoroutineContext()[Job]) try { @@ -771,6 +780,16 @@ class AudioEngine constructor() { Logger.d("AudioEngine", "Writer loop stopped") } + // 电量上报:注册粘性广播时立刻拿到当前电量并发出首包, + // 之后仅在电量/充电状态变化时推送(field 9)。 + ContextHelper.getContext()?.let { context -> + batteryReporter = BatteryStatusReporter(context).also { reporter -> + reporter.start { status -> + channel.trySend(MessageWrapper(clientStatus = status)) + } + } + } + val readerJob = if (tcpSocket != null) { launch { val inChannel = input ?: throw IllegalStateException("TCP input channel unavailable for reader") @@ -815,6 +834,16 @@ class AudioEngine constructor() { wrapper.pluginMessage?.let { pm -> _pluginMessages.tryEmit(pm) } + + // 桌面端每秒推送的链路质量(field 8) + wrapper.stats?.let { stats -> + _linkQuality.value = LinkQuality( + rttMs = stats.rttMs, + jitterMs = stats.jitterMs, + packetLoss = stats.packetLoss, + latencyMs = stats.latencyMs + ) + } } catch (e: Exception) { Logger.e("AudioEngine", "Error decoding incoming message", e) } @@ -1048,6 +1077,9 @@ class AudioEngine constructor() { } finally { connectionComplete.completeExceptionally(CancellationException("Audio session ended before startup completed")) Logger.d("AudioEngine", "Cleaning up resources for generation $sessionGeneration") + batteryReporter?.stop() + batteryReporter = null + _linkQuality.value = null channel.close() val recorderToRelease = recorder val recorderStopCompletion = stopAndReleaseRecorderAsync(recorderToRelease) diff --git a/composeApp/src/main/kotlin/com/lanrhyme/micyou/audio/BatteryStatusReporter.kt b/composeApp/src/main/kotlin/com/lanrhyme/micyou/audio/BatteryStatusReporter.kt new file mode 100644 index 00000000..63a80f26 --- /dev/null +++ b/composeApp/src/main/kotlin/com/lanrhyme/micyou/audio/BatteryStatusReporter.kt @@ -0,0 +1,86 @@ +/* + * MicYou — Turns your Android device into a high-quality PC microphone. + * Copyright (C) 2026 LanRhyme + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version, with the MicYou Plugin Exception. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +package com.lanrhyme.micyou.audio + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.os.BatteryManager +import android.os.Build +import com.lanrhyme.micyou.network.ClientStatusMessage +import com.lanrhyme.micyou.util.Logger + +/** + * 读取本机电量并监听变化,把结果作为 `ClientStatusMessage` 上报给桌面端。 + * + * 只依赖 `ACTION_BATTERY_CHANGED` 粘性广播:注册时系统立刻回调一次当前值, + * 之后每次电量/充电状态变化再回调,因此调用方无需自己轮询。 + */ +class BatteryStatusReporter(private val context: Context) { + + private var receiver: BroadcastReceiver? = null + + /** + * 开始监听,[onChange] 会在注册时收到一次当前状态,之后仅在变化时回调。 + * 该回调可能运行在主线程,实现必须是快速且非阻塞的。 + */ + fun start(onChange: (ClientStatusMessage) -> Unit) { + if (receiver != null) return + val callback = object : BroadcastReceiver() { + override fun onReceive(receiverContext: Context?, intent: Intent?) { + val status = read(intent) ?: return + onChange(status) + } + } + receiver = callback + try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + context.registerReceiver(callback, IntentFilter(Intent.ACTION_BATTERY_CHANGED), Context.RECEIVER_NOT_EXPORTED) + } else { + @Suppress("UnspecifiedRegisterReceiverFlag") + context.registerReceiver(callback, IntentFilter(Intent.ACTION_BATTERY_CHANGED)) + } + } catch (e: Exception) { + // 电量上报是锦上添花,注册失败不应拖垮音频会话。 + Logger.w("BatteryStatusReporter", "Failed to register battery receiver: ${e.message}") + receiver = null + } + } + + fun stop() { + val callback = receiver ?: return + receiver = null + try { + context.unregisterReceiver(callback) + } catch (e: Exception) { + Logger.w("BatteryStatusReporter", "Failed to unregister battery receiver: ${e.message}") + } + } + + /** 粘性广播的 extras → 协议字段;读不到时返回 null。 */ + private fun read(intent: Intent?): ClientStatusMessage? { + if (intent == null) return null + val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) + val scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1) + if (level < 0 || scale <= 0) return null + val percent = (level * 100 / scale).coerceIn(0, 100) + val status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1) + val charging = status == BatteryManager.BATTERY_STATUS_CHARGING || + status == BatteryManager.BATTERY_STATUS_FULL + return ClientStatusMessage(batteryLevel = percent, isCharging = charging) + } +} diff --git a/composeApp/src/main/kotlin/com/lanrhyme/micyou/audio/LinkQuality.kt b/composeApp/src/main/kotlin/com/lanrhyme/micyou/audio/LinkQuality.kt new file mode 100644 index 00000000..1c600d50 --- /dev/null +++ b/composeApp/src/main/kotlin/com/lanrhyme/micyou/audio/LinkQuality.kt @@ -0,0 +1,32 @@ +/* + * MicYou — Turns your Android device into a high-quality PC microphone. + * Copyright (C) 2026 LanRhyme + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version, with the MicYou Plugin Exception. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +package com.lanrhyme.micyou.audio + +/** + * 桌面端每秒回传一次的链路质量,数据来自桌面接收侧测量 + * (micyou-protocol network.proto 的 `StatsMessage`)。 + * + * @property rttMs 平滑后的 ping/pong 往返时延,首个 pong 之前为 0 + * @property jitterMs 音频包到达抖动(毫秒) + * @property packetLoss 丢包率,0.0 ~ 1.0 + * @property latencyMs 端到端估算(接收缓冲 + RTT) + */ +data class LinkQuality( + val rttMs: Int, + val jitterMs: Float, + val packetLoss: Float, + val latencyMs: Int +) diff --git a/composeApp/src/main/kotlin/com/lanrhyme/micyou/network/Protocol.kt b/composeApp/src/main/kotlin/com/lanrhyme/micyou/network/Protocol.kt index 2522eaa9..51f13535 100644 --- a/composeApp/src/main/kotlin/com/lanrhyme/micyou/network/Protocol.kt +++ b/composeApp/src/main/kotlin/com/lanrhyme/micyou/network/Protocol.kt @@ -186,6 +186,31 @@ data class PluginMessage( } } +/** 桌面端每秒推送的链路质量(接收侧测量),见 micyou-protocol network.proto StatsMessage */ +@OptIn(ExperimentalSerializationApi::class) +@Serializable +data class StatsMessage( + @ProtoNumber(1) + val rttMs: Int = 0, + @ProtoNumber(2) + val jitterMs: Float = 0f, + @ProtoNumber(3) + val packetLoss: Float = 0f, + @ProtoNumber(4) + val latencyMs: Int = 0 +) + +/** 手机上报给桌面的状态(目前只有电量),见 network.proto ClientStatusMessage */ +@OptIn(ExperimentalSerializationApi::class) +@Serializable +data class ClientStatusMessage( + /** 0-100;-1 表示读不到电量 */ + @ProtoNumber(1) + val batteryLevel: Int = -1, + @ProtoNumber(2) + val isCharging: Boolean = false +) + // TCP handshake strings, matching HANDSHAKE_CLIENT_STR / HANDSHAKE_SERVER_STR in micyou-protocol const val HANDSHAKE_CLIENT = "MicYouCheck1" const val HANDSHAKE_SERVER = "MicYouCheck2" @@ -223,7 +248,8 @@ fun calculateUdpPort(tcpPort: Int): Int { /** 判断 MessageWrapper 是否包含控制消息(应通过 TCP 发送) */ fun MessageWrapper.hasControlMessage(): Boolean { - return connect != null || mute != null || ping != null || pong != null || pluginMessage != null + return connect != null || mute != null || ping != null || pong != null || + pluginMessage != null || clientStatus != null } @OptIn(ExperimentalSerializationApi::class) @@ -242,5 +268,11 @@ data class MessageWrapper( // Cross-device plugin messaging (micyou-protocol network.proto field 7). // proto3 skips unknown fields, so legacy desktops simply ignore it. @ProtoNumber(7) - val pluginMessage: PluginMessage? = null + val pluginMessage: PluginMessage? = null, + // 桌面端每秒推送的链路质量(field 8);旧版本不解析,proto3 会跳过 + @ProtoNumber(8) + val stats: StatsMessage? = null, + // 手机上报的电量(field 9);旧桌面同样跳过 + @ProtoNumber(9) + val clientStatus: ClientStatusMessage? = null ) diff --git a/composeApp/src/main/kotlin/com/lanrhyme/micyou/ui/LinkQualityPanel.kt b/composeApp/src/main/kotlin/com/lanrhyme/micyou/ui/LinkQualityPanel.kt new file mode 100644 index 00000000..683094cc --- /dev/null +++ b/composeApp/src/main/kotlin/com/lanrhyme/micyou/ui/LinkQualityPanel.kt @@ -0,0 +1,225 @@ +/* + * MicYou — Turns your Android device into a high-quality PC microphone. + * Copyright (C) 2026 LanRhyme + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version, with the MicYou Plugin Exception. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +package com.lanrhyme.micyou.ui + +import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.core.Spring +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.spring +import androidx.compose.animation.core.tween +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsPressedAsState +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Speed +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.scale +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.lanrhyme.micyou.R +import com.lanrhyme.micyou.audio.LinkQuality +import com.lanrhyme.micyou.ui.background.HazeSurface +import com.lanrhyme.micyou.ui.compose.haze.HazeState +import java.util.Locale + +/** + * 底部栏入口:只在连上桌面端后显示。桌面端每秒回传一次链路质量, + * 因此这个按钮同时是「有实时统计」的指示器。 + */ +@Composable +fun LinkQualityToggleButton( + isActive: Boolean, + rttMs: Int? = null, + onToggle: () -> Unit +) { + val interactionSource = remember { MutableInteractionSource() } + val isPressed by interactionSource.collectIsPressedAsState() + val scale by animateFloatAsState( + targetValue = if (isPressed) 0.9f else 1f, + animationSpec = spring(dampingRatio = Spring.DampingRatioHighBouncy), + label = "linkQualityBtnScale" + ) + val bgColor by animateColorAsState( + targetValue = if (isActive) MaterialTheme.colorScheme.primaryContainer + else MaterialTheme.colorScheme.surfaceContainerHighest, + animationSpec = tween(200), + label = "linkQualityBtnBg" + ) + val contentColor by animateColorAsState( + targetValue = if (isActive) MaterialTheme.colorScheme.onPrimaryContainer + else MaterialTheme.colorScheme.onSurfaceVariant, + animationSpec = tween(200), + label = "linkQualityBtnContent" + ) + + Surface( + shape = MaterialTheme.shapes.small, + color = bgColor, + modifier = Modifier.scale(scale).clickable(interactionSource, null) { onToggle() } + ) { + Row( + modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp) + ) { + Icon( + Icons.Filled.Speed, + contentDescription = stringResource(R.string.linkQualityLabel), + tint = contentColor, + modifier = Modifier.size(18.dp) + ) + Text( + if (rttMs != null) "${stringResource(R.string.linkQualityLabel)} $rttMs ms" + else stringResource(R.string.linkQualityLabel), + style = MaterialTheme.typography.labelMedium, + color = contentColor + ) + } + } +} + +/** + * 链路质量面板:RTT / 抖动 / 丢包 / 端到端延迟,全部由桌面端测量后回传, + * 手机端只负责展示(手机不主动发 ping)。 + */ +@Composable +fun LinkQualityPanel( + quality: LinkQuality?, + cardOpacity: Float = 1f, + hazeState: HazeState? = null, + enableHazeEffect: Boolean = false, + modifier: Modifier = Modifier +) { + HazeSurface( + shape = MaterialTheme.shapes.medium, + color = MaterialTheme.colorScheme.surfaceBright.copy(alpha = cardOpacity), + hazeColor = MaterialTheme.colorScheme.surfaceBright.copy(alpha = cardOpacity * 0.7f), + modifier = modifier.fillMaxWidth(), + hazeState = hazeState, + enabled = enableHazeEffect + ) { + Column( + modifier = Modifier.fillMaxWidth().padding(16.dp), + verticalArrangement = Arrangement.spacedBy(10.dp) + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + Icon( + Icons.Filled.Speed, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(18.dp) + ) + Text( + stringResource(R.string.linkQualityLabel), + style = MaterialTheme.typography.titleSmall, + modifier = Modifier.weight(1f) + ) + if (quality != null) { + GradeBadge(quality) + } + } + + if (quality == null) { + Text( + stringResource(R.string.linkQualityWaiting), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } else { + MetricRow(stringResource(R.string.linkQualityRtt), "${quality.rttMs} ms") + MetricRow( + stringResource(R.string.linkQualityJitter), + String.format(Locale.US, "%.1f ms", quality.jitterMs) + ) + MetricRow( + stringResource(R.string.linkQualityLoss), + String.format(Locale.US, "%.2f%%", quality.packetLoss * 100f) + ) + MetricRow(stringResource(R.string.linkQualityLatency), "${quality.latencyMs} ms") + } + + Text( + stringResource(R.string.linkQualityHint), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } +} + +@Composable +private fun MetricRow(label: String, value: String) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + Text( + label, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Text( + value, + style = MaterialTheme.typography.bodySmall, + fontWeight = FontWeight.SemiBold + ) + } +} + +@Composable +private fun GradeBadge(quality: LinkQuality) { + val (labelRes, color) = when { + quality.rttMs <= 60 && quality.packetLoss <= 0.01f -> + R.string.linkQualityExcellent to MaterialTheme.colorScheme.primary + quality.rttMs <= 150 && quality.packetLoss <= 0.05f -> + R.string.linkQualityGood to MaterialTheme.colorScheme.secondary + quality.rttMs <= 300 && quality.packetLoss <= 0.15f -> + R.string.linkQualityFair to MaterialTheme.colorScheme.tertiary + else -> + R.string.linkQualityPoor to MaterialTheme.colorScheme.error + } + Surface( + shape = MaterialTheme.shapes.extraSmall, + color = color.copy(alpha = 0.15f) + ) { + Text( + stringResource(labelRes), + style = MaterialTheme.typography.labelSmall, + fontWeight = FontWeight.SemiBold, + color = color, + modifier = Modifier.padding(horizontal = 8.dp, vertical = 3.dp) + ) + } +} diff --git a/composeApp/src/main/kotlin/com/lanrhyme/micyou/ui/MobileHome.kt b/composeApp/src/main/kotlin/com/lanrhyme/micyou/ui/MobileHome.kt index 136b5bab..6c12c3eb 100644 --- a/composeApp/src/main/kotlin/com/lanrhyme/micyou/ui/MobileHome.kt +++ b/composeApp/src/main/kotlin/com/lanrhyme/micyou/ui/MobileHome.kt @@ -144,6 +144,8 @@ fun MobileHome(viewModel: MainViewModel) { val state by viewModel.uiState.collectAsState() val audioLevel by viewModel.audioLevels.collectAsState(initial = 0f) val soundPad by viewModel.soundPadState.collectAsState() + val linkQuality by viewModel.linkQuality.collectAsState(initial = null) + val linkPanelOpen by viewModel.linkPanelOpen.collectAsState() // SoundPad 面板展开时收起连接配置卡片,把纵向空间让给音效网格 val soundPadPanelOpen = soundPad.showPanel && soundPad.available @@ -279,6 +281,26 @@ fun MobileHome(viewModel: MainViewModel) { ) } + // 链路质量面板(连接后由底部栏按钮展开,数据来自桌面端回传) + AnimatedVisibility( + visible = linkPanelOpen && state.streamState == StreamState.Streaming && contentVisible, + enter = slideInVertically( + initialOffsetY = { it }, + animationSpec = tween(300, easing = EasingFunctions.EaseOutExpo) + ) + fadeIn(animationSpec = tween(200)), + exit = slideOutVertically( + targetOffsetY = { it }, + animationSpec = tween(250, easing = EasingFunctions.EaseInOutExpo) + ) + fadeOut(animationSpec = tween(150)) + ) { + LinkQualityPanel( + quality = linkQuality, + cardOpacity = state.backgroundSettings.cardOpacity, + hazeState = hazeState, + enableHazeEffect = state.backgroundSettings.enableHazeEffect + ) + } + // Bottom bar (mute + soundpad + status) AnimatedCardVisibility( visible = contentVisible, @@ -288,6 +310,8 @@ fun MobileHome(viewModel: MainViewModel) { state = state, viewModel = viewModel, soundPad = soundPad, + linkQuality = linkQuality, + linkPanelOpen = linkPanelOpen, cardOpacity = state.backgroundSettings.cardOpacity, hazeState = hazeState ) @@ -790,6 +814,8 @@ private fun MobileBottomBar( state: AppUiState, viewModel: MainViewModel, soundPad: SoundPadUiState, + linkQuality: com.lanrhyme.micyou.audio.LinkQuality?, + linkPanelOpen: Boolean, cardOpacity: Float = 1f, hazeState: HazeState? = null ) { @@ -818,6 +844,14 @@ private fun MobileBottomBar( onToggle = { viewModel.toggleSoundPadPanel() } ) } + // 连接后出现:桌面端每秒回传的链路质量 + if (state.streamState == StreamState.Streaming) { + LinkQualityToggleButton( + isActive = linkPanelOpen, + rttMs = linkQuality?.rttMs, + onToggle = { viewModel.toggleLinkPanel() } + ) + } } val dotColor by animateColorAsState( diff --git a/composeApp/src/main/kotlin/com/lanrhyme/micyou/viewmodel/MainViewModel.kt b/composeApp/src/main/kotlin/com/lanrhyme/micyou/viewmodel/MainViewModel.kt index 7e6256b0..7bb0e08e 100644 --- a/composeApp/src/main/kotlin/com/lanrhyme/micyou/viewmodel/MainViewModel.kt +++ b/composeApp/src/main/kotlin/com/lanrhyme/micyou/viewmodel/MainViewModel.kt @@ -154,6 +154,13 @@ class MainViewModel : ViewModel() { private val soundPadController = SoundPadController(audioStreamViewModel.audioEngine, viewModelScope) val soundPadState: StateFlow = soundPadController.state + // 手机端链路质量:桌面端每秒回传一次(StatsMessage),旧桌面不发则为 null + val linkQuality = audioStreamViewModel.audioEngine.linkQuality + + // 链路质量面板是否展开(仅在播放中可用) + private val _linkPanelOpen = MutableStateFlow(false) + val linkPanelOpen: StateFlow = _linkPanelOpen.asStateFlow() + private val _uiState = MutableStateFlow(AppUiState()) val uiState: StateFlow = _uiState.asStateFlow() @@ -185,6 +192,15 @@ class MainViewModel : ViewModel() { } } + // 断流后自动收起链路质量面板 + viewModelScope.launch { + audioStreamViewModel.audioEngine.streamState.collect { streamState -> + if (streamState != StreamState.Streaming && _linkPanelOpen.value) { + _linkPanelOpen.value = false + } + } + } + // Auto-check for updates if (settings.getBoolean("auto_check_update", true)) { updateViewModel.checkUpdateAuto() @@ -345,7 +361,11 @@ class MainViewModel : ViewModel() { // Soundpad methods (delegate to SoundPadController) fun toggleSoundPadPanel() = soundPadController.togglePanel() - fun soundPadPlay(soundId: String) = soundPadController.play(soundId) + + /** 展开/收起手机端的链路质量面板。 */ + fun toggleLinkPanel() { + _linkPanelOpen.value = !_linkPanelOpen.value + } fun soundPadPlay(soundId: String) = soundPadController.play(soundId) fun soundPadStop(sessionId: Long? = null) = soundPadController.stop(sessionId) fun soundPadSeek(sessionId: Long, positionMs: Long) = soundPadController.seek(sessionId, positionMs) fun soundPadSetVolume(sessionId: Long, volume: Float) = soundPadController.setVolume(sessionId, volume) diff --git a/composeApp/src/main/res/values-ca/strings.xml b/composeApp/src/main/res/values-ca/strings.xml index 40aaa0ef..f06ad13d 100644 --- a/composeApp/src/main/res/values-ca/strings.xml +++ b/composeApp/src/main/res/values-ca/strings.xml @@ -400,4 +400,15 @@ Streaming stopped 下载电脑端喵~ 检查系统设置中的应用权限喵~ + Qualitat de l'enllaç + Anada i tornada + Jitter + Pèrdua de paquets + Extrem a extrem + Esperant l'escriptori… + Mesurat per l'escriptori + Excel·lent + Bo + Acceptable + Dolent diff --git a/composeApp/src/main/res/values-en/strings.xml b/composeApp/src/main/res/values-en/strings.xml index 4643c994..ae207c86 100644 --- a/composeApp/src/main/res/values-en/strings.xml +++ b/composeApp/src/main/res/values-en/strings.xml @@ -415,4 +415,15 @@ Volume Back %1$d items + Link quality + RTT + Jitter + Packet loss + End-to-end + Waiting for the desktop… + Measured by the desktop + Excellent + Good + Fair + Poor diff --git a/composeApp/src/main/res/values-zh-rHD/strings.xml b/composeApp/src/main/res/values-zh-rHD/strings.xml index f59e33ab..aabbf58b 100644 --- a/composeApp/src/main/res/values-zh-rHD/strings.xml +++ b/composeApp/src/main/res/values-zh-rHD/strings.xml @@ -390,4 +390,15 @@ 下载电脑终端项 检查系统设定中的应用程式权限项 + 链路质量 + 往返时延 + 抖动 + 丢包 + 端到端延迟 + 桌面端还在算… + 由桌面端测量 + 优秀 + 良好 + 一般 + 较差 diff --git a/composeApp/src/main/res/values-zh-rHK/strings.xml b/composeApp/src/main/res/values-zh-rHK/strings.xml index 8abd1dd7..fcad5325 100644 --- a/composeApp/src/main/res/values-zh-rHK/strings.xml +++ b/composeApp/src/main/res/values-zh-rHK/strings.xml @@ -415,4 +415,15 @@ 音量 返回上層 %1$d 項 + 鏈路質量 + 往返時延 + 抖動 + 丟包 + 端到端延遲 + 等待桌面端數據… + 由桌面端測量 + 優秀 + 良好 + 一般 + 較差 diff --git a/composeApp/src/main/res/values-zh-rTW/strings.xml b/composeApp/src/main/res/values-zh-rTW/strings.xml index 29f9c1bc..d3e0bcf9 100644 --- a/composeApp/src/main/res/values-zh-rTW/strings.xml +++ b/composeApp/src/main/res/values-zh-rTW/strings.xml @@ -415,4 +415,15 @@ 音量 返回上層 %1$d 項 + 鏈路品質 + 往返延遲 + 抖動 + 封包遺失 + 端到端延遲 + 等待桌面端資料… + 由桌面端測量 + 優秀 + 良好 + 一般 + 較差 diff --git a/composeApp/src/main/res/values-zh/strings.xml b/composeApp/src/main/res/values-zh/strings.xml index 09f3ec08..09bf39ea 100644 --- a/composeApp/src/main/res/values-zh/strings.xml +++ b/composeApp/src/main/res/values-zh/strings.xml @@ -415,4 +415,15 @@ 音量 返回上级 %1$d 项 + 链路质量 + 往返时延 + 抖动 + 丢包 + 端到端延迟 + 等待桌面端数据… + 由桌面端测量 + 优秀 + 良好 + 一般 + 较差 diff --git a/composeApp/src/main/res/values/strings.xml b/composeApp/src/main/res/values/strings.xml index 4643c994..ae207c86 100644 --- a/composeApp/src/main/res/values/strings.xml +++ b/composeApp/src/main/res/values/strings.xml @@ -415,4 +415,15 @@ Volume Back %1$d items + Link quality + RTT + Jitter + Packet loss + End-to-end + Waiting for the desktop… + Measured by the desktop + Excellent + Good + Fair + Poor From 5f1d7637ee46241439cb1491dea1fe1392644858 Mon Sep 17 00:00:00 2001 From: OrientCOMPASS <316423573+OrientCOMPASS@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:48:23 +0800 Subject: [PATCH 04/12] fix(tui): keep the battery i18n entry inside the dict table --- tauri-app/crates/micyou-tui/src/i18n.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/tauri-app/crates/micyou-tui/src/i18n.rs b/tauri-app/crates/micyou-tui/src/i18n.rs index 8911049e..a89ee3db 100644 --- a/tauri-app/crates/micyou-tui/src/i18n.rs +++ b/tauri-app/crates/micyou-tui/src/i18n.rs @@ -155,8 +155,8 @@ const ZH: Dict = Dict { ("server_addr_hint", "手机端连接地址"), ("staged_hint", "更改模式/端口后需重启生效"), ("level_overflow", "电平过高"), + ("battery", "电量"), ], - ("battery", "电量"), }; const EN: Dict = Dict { @@ -250,8 +250,8 @@ const EN: Dict = Dict { ("server_addr_hint", "Connect from phone at"), ("staged_hint", "Mode/port changes require a restart"), ("level_overflow", "Level too high"), + ("battery", "Battery"), ], - ("battery", "Battery"), }; const CAT: Dict = Dict { @@ -342,8 +342,8 @@ const CAT: Dict = Dict { ("server_addr_hint", "手机端连接地址"), ("staged_hint", "更改模式/端口后需重启生效喵~"), ("level_overflow", "电平过高"), + ("battery", "Bateria"), ], - ("battery", "Bateria"), }; const LZH: Dict = Dict { @@ -425,8 +425,8 @@ const LZH: Dict = Dict { ("server_addr_hint", "手机端连接地址"), ("staged_hint", "改模式/端口后需重启"), ("level_overflow", "电平过高"), + ("battery", "電量"), ], - ("battery", "電量"), }; const ZH_HK: Dict = Dict { @@ -508,8 +508,8 @@ const ZH_HK: Dict = Dict { ("server_addr_hint", "手機端連接地址"), ("staged_hint", "改模式/埠之後要重啟先得"), ("level_overflow", "電平過高"), + ("battery", "電量"), ], - ("battery", "電量"), }; const ZH_SS: Dict = Dict { @@ -597,8 +597,8 @@ const ZH_SS: Dict = Dict { ("server_addr_hint", "手机端连接地址"), ("staged_hint", "更改模式/端口后需重启生效"), ("level_overflow", "电平过高"), + ("battery", "电量"), ], - ("battery", "电量"), }; const ZH_TW: Dict = Dict { @@ -686,8 +686,8 @@ const ZH_TW: Dict = Dict { ("server_addr_hint", "手機端連線位址"), ("staged_hint", "變更模式/連接埠後需重新啟動"), ("level_overflow", "電平過高"), + ("battery", "電量"), ], - ("battery", "電量"), }; fn dict_for(lang: &str) -> &'static Dict { From cb724d179f4123c146f2878d0d8aa7a1ff33bb71 Mon Sep 17 00:00:00 2001 From: OrientCOMPASS <316423573+OrientCOMPASS@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:58:41 +0800 Subject: [PATCH 05/12] ci: run cargo test and clippy on the runner --- .github/workflows/development.yml | 34 +++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/.github/workflows/development.yml b/.github/workflows/development.yml index b6de55eb..da6140dc 100644 --- a/.github/workflows/development.yml +++ b/.github/workflows/development.yml @@ -8,6 +8,40 @@ on: workflow_dispatch: jobs: + # ----------------- Rust 单元测试 + clippy ----------------- + # 本仓库的验证都在 GitHub runner 上做;下面的构建任务只保证「能编译」, + # 真正的单元测试与 lint 由这个任务负责。 + test-rust: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - name: Setup Rust (stable) + uses: dtolnay/rust-toolchain@stable + with: + components: clippy + - name: Cache Rust + uses: Swatinem/rust-cache@v2 + with: + workspaces: tauri-app -> target + cache-on-failure: true + - name: Install System Dependencies + run: | + sudo apt-get update + sudo apt-get install -y \ + libwebkit2gtk-4.1-dev \ + libayatana-appindicator3-dev \ + librsvg2-dev \ + patchelf \ + libxdo-dev \ + libssl-dev \ + libasound2-dev + - name: cargo test + run: cargo test --workspace + working-directory: tauri-app + - name: cargo clippy + run: cargo clippy --workspace --all-targets + working-directory: tauri-app + # ----------------- Android Debug 构建 ----------------- build-android: runs-on: ubuntu-latest From f7ff63b742d68619c87c90b4d4d5dbb8bef914ec Mon Sep 17 00:00:00 2001 From: OrientCOMPASS <316423573+OrientCOMPASS@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:24:51 +0800 Subject: [PATCH 06/12] ci: build the frontend before cargo test so build.rs finds dist --- .github/workflows/development.yml | 32 +++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/.github/workflows/development.yml b/.github/workflows/development.yml index da6140dc..025bfd23 100644 --- a/.github/workflows/development.yml +++ b/.github/workflows/development.yml @@ -8,13 +8,24 @@ on: workflow_dispatch: jobs: - # ----------------- Rust 单元测试 + clippy ----------------- - # 本仓库的验证都在 GitHub runner 上做;下面的构建任务只保证「能编译」, - # 真正的单元测试与 lint 由这个任务负责。 - test-rust: + # ----------------- 单测 + 类型检查 + lint ----------------- + # 构建任务只保证「能编译」;真正的门禁在这里:前端类型检查(vue-tsc)、 + # web 单测、Rust 单测与 clippy。src-tauri 的 build.rs 需要 dist/, + # 所以先跑一次前端构建。 + test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 + - name: Setup Bun + uses: oven-sh/setup-bun@v2 + with: + bun-version-file: tauri-app/package.json + - name: Cache Bun dependencies + uses: actions/cache@v6 + with: + path: ~/.bun/install/cache + key: ${{ runner.os }}-${{ runner.arch }}-bun-${{ hashFiles('tauri-app/bun.lock') }} + restore-keys: ${{ runner.os }}-${{ runner.arch }}-bun- - name: Setup Rust (stable) uses: dtolnay/rust-toolchain@stable with: @@ -24,6 +35,10 @@ jobs: with: workspaces: tauri-app -> target cache-on-failure: true + - name: Install cargo-about + uses: taiki-e/install-action@v2 + with: + tool: cargo-about@0.9.1 - name: Install System Dependencies run: | sudo apt-get update @@ -35,6 +50,15 @@ jobs: libxdo-dev \ libssl-dev \ libasound2-dev + - name: Install Frontend Dependencies + run: bun install --frozen-lockfile + working-directory: tauri-app + - name: Frontend build (licenses + vue-tsc + vite) + run: bun run build + working-directory: tauri-app + - name: Web tests + run: bun run test:web + working-directory: tauri-app - name: cargo test run: cargo test --workspace working-directory: tauri-app From 5a4a128ec778048825889fce39d7ae7506d4b266 Mon Sep 17 00:00:00 2001 From: OrientCOMPASS <316423573+OrientCOMPASS@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:31:54 +0800 Subject: [PATCH 07/12] ci: prepare sidecars before cargo test --- .github/workflows/development.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/development.yml b/.github/workflows/development.yml index 025bfd23..8d473929 100644 --- a/.github/workflows/development.yml +++ b/.github/workflows/development.yml @@ -59,6 +59,10 @@ jobs: - name: Web tests run: bun run test:web working-directory: tauri-app + # src-tauri 的 build.rs 要求 sidecar 二进制已存在 + - name: Prepare sidecars + run: bun run prepare-sidecars:dev + working-directory: tauri-app - name: cargo test run: cargo test --workspace working-directory: tauri-app From 7e0dc8def1a6c833d63ac0b5b2c43c320055d7d3 Mon Sep 17 00:00:00 2001 From: OrientCOMPASS <316423573+OrientCOMPASS@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:42:04 +0800 Subject: [PATCH 08/12] ci: add a light Verify workflow and keep development.yml untouched --- .github/workflows/development.yml | 62 --------------------- .github/workflows/verify.yml | 89 +++++++++++++++++++++++++++++++ 2 files changed, 89 insertions(+), 62 deletions(-) create mode 100644 .github/workflows/verify.yml diff --git a/.github/workflows/development.yml b/.github/workflows/development.yml index 8d473929..b6de55eb 100644 --- a/.github/workflows/development.yml +++ b/.github/workflows/development.yml @@ -8,68 +8,6 @@ on: workflow_dispatch: jobs: - # ----------------- 单测 + 类型检查 + lint ----------------- - # 构建任务只保证「能编译」;真正的门禁在这里:前端类型检查(vue-tsc)、 - # web 单测、Rust 单测与 clippy。src-tauri 的 build.rs 需要 dist/, - # 所以先跑一次前端构建。 - test: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - - name: Setup Bun - uses: oven-sh/setup-bun@v2 - with: - bun-version-file: tauri-app/package.json - - name: Cache Bun dependencies - uses: actions/cache@v6 - with: - path: ~/.bun/install/cache - key: ${{ runner.os }}-${{ runner.arch }}-bun-${{ hashFiles('tauri-app/bun.lock') }} - restore-keys: ${{ runner.os }}-${{ runner.arch }}-bun- - - name: Setup Rust (stable) - uses: dtolnay/rust-toolchain@stable - with: - components: clippy - - name: Cache Rust - uses: Swatinem/rust-cache@v2 - with: - workspaces: tauri-app -> target - cache-on-failure: true - - name: Install cargo-about - uses: taiki-e/install-action@v2 - with: - tool: cargo-about@0.9.1 - - name: Install System Dependencies - run: | - sudo apt-get update - sudo apt-get install -y \ - libwebkit2gtk-4.1-dev \ - libayatana-appindicator3-dev \ - librsvg2-dev \ - patchelf \ - libxdo-dev \ - libssl-dev \ - libasound2-dev - - name: Install Frontend Dependencies - run: bun install --frozen-lockfile - working-directory: tauri-app - - name: Frontend build (licenses + vue-tsc + vite) - run: bun run build - working-directory: tauri-app - - name: Web tests - run: bun run test:web - working-directory: tauri-app - # src-tauri 的 build.rs 要求 sidecar 二进制已存在 - - name: Prepare sidecars - run: bun run prepare-sidecars:dev - working-directory: tauri-app - - name: cargo test - run: cargo test --workspace - working-directory: tauri-app - - name: cargo clippy - run: cargo clippy --workspace --all-targets - working-directory: tauri-app - # ----------------- Android Debug 构建 ----------------- build-android: runs-on: ubuntu-latest diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml new file mode 100644 index 00000000..0b1e4086 --- /dev/null +++ b/.github/workflows/verify.yml @@ -0,0 +1,89 @@ +name: Verify + +# 轻量门禁:类型检查 + web 单测 + Rust 单测 + clippy + Android Debug 编译。 +# 多平台 Tauri 打包(development.yml / release.yml)耗时十几分钟,不在每次 +# 推送时跑;日常迭代用这个 workflow,`workflow_dispatch` 可指定任意分支。 + +on: + workflow_dispatch: + push: + branches: [ "main", "master", "develop" ] + pull_request: + branches: [ "main", "master", "develop" ] + +jobs: + # ----------------- 前端类型检查 + web 单测 + Rust 单测/clippy ----------------- + verify: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - name: Setup Bun + uses: oven-sh/setup-bun@v2 + with: + bun-version-file: tauri-app/package.json + - name: Cache Bun dependencies + uses: actions/cache@v6 + with: + path: ~/.bun/install/cache + key: ${{ runner.os }}-${{ runner.arch }}-bun-${{ hashFiles('tauri-app/bun.lock') }} + restore-keys: ${{ runner.os }}-${{ runner.arch }}-bun- + - name: Setup Rust (stable) + uses: dtolnay/rust-toolchain@stable + with: + components: clippy + - name: Cache Rust + uses: Swatinem/rust-cache@v2 + with: + workspaces: tauri-app -> target + cache-on-failure: true + - name: Install cargo-about + uses: taiki-e/install-action@v2 + with: + tool: cargo-about@0.9.1 + - name: Install System Dependencies + run: | + sudo apt-get update + sudo apt-get install -y \ + libwebkit2gtk-4.1-dev \ + libayatana-appindicator3-dev \ + librsvg2-dev \ + patchelf \ + libxdo-dev \ + libssl-dev \ + libasound2-dev + - name: Install Frontend Dependencies + run: bun install --frozen-lockfile + working-directory: tauri-app + - name: Frontend type check + build + run: bun run build + working-directory: tauri-app + - name: Web tests + run: bun run test:web + working-directory: tauri-app + # src-tauri 的 build.rs 要求 dist/ 与 sidecar 二进制都已存在 + - name: Prepare sidecars + run: bun run prepare-sidecars:dev + working-directory: tauri-app + - name: Rust tests + run: cargo test --workspace + working-directory: tauri-app + - name: Rust clippy + run: cargo clippy --workspace --all-targets + working-directory: tauri-app + + # ----------------- Android Debug 编译 ----------------- + android: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - name: set up JDK 21 + uses: actions/setup-java@v5 + with: + java-version: '21' + distribution: 'liberica' + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v6 + - name: Grant execute permission for gradlew + run: chmod +x gradlew + - name: Build Android Debug + run: ./gradlew :composeApp:assembleDebug From 49ad0931e6b6aecab7c051bb98577dd608ecfbfb Mon Sep 17 00:00:00 2001 From: OrientCOMPASS <316423573+OrientCOMPASS@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:53:15 +0800 Subject: [PATCH 09/12] fix(android): escape apostrophes in the Catalan strings; ci: cache reuse and native fixture --- .github/workflows/verify.yml | 34 ++++++++++++++++++- composeApp/src/main/res/values-ca/strings.xml | 6 ++-- 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 0b1e4086..6dff4804 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -3,6 +3,13 @@ name: Verify # 轻量门禁:类型检查 + web 单测 + Rust 单测 + clippy + Android Debug 编译。 # 多平台 Tauri 打包(development.yml / release.yml)耗时十几分钟,不在每次 # 推送时跑;日常迭代用这个 workflow,`workflow_dispatch` 可指定任意分支。 +# +# 缓存策略(目标是「第二次推送几乎只跑变更部分」): +# * Bun 依赖缓存 ~/.bun/install/cache,key 由 bun.lock 哈希决定 +# * Rust 用 Swatinem/rust-cache 缓存依赖与 workspace target(含 sidecar 产物) +# * cargo-about 由 taiki-e/install-action 按版本缓存二进制 +# * Gradle 由 gradle/actions/setup-gradle 缓存 ~/.gradle 与配置缓存 +# * 同一分支新推送取消旧运行,避免排队浪费额度 on: workflow_dispatch: @@ -11,6 +18,10 @@ on: pull_request: branches: [ "main", "master", "develop" ] +concurrency: + group: verify-${{ github.ref }} + cancel-in-progress: true + jobs: # ----------------- 前端类型检查 + web 单测 + Rust 单测/clippy ----------------- verify: @@ -26,7 +37,8 @@ jobs: with: path: ~/.bun/install/cache key: ${{ runner.os }}-${{ runner.arch }}-bun-${{ hashFiles('tauri-app/bun.lock') }} - restore-keys: ${{ runner.os }}-${{ runner.arch }}-bun- + restore-keys: | + ${{ runner.os }}-${{ runner.arch }}-bun- - name: Setup Rust (stable) uses: dtolnay/rust-toolchain@stable with: @@ -36,6 +48,9 @@ jobs: with: workspaces: tauri-app -> target cache-on-failure: true + cache-all-crates: true + # 独立前缀,避免和 development.yml 的多平台构建互相挤掉缓存 + prefix-key: verify - name: Install cargo-about uses: taiki-e/install-action@v2 with: @@ -64,6 +79,10 @@ jobs: - name: Prepare sidecars run: bun run prepare-sidecars:dev working-directory: tauri-app + # native 插件测试会 dlopen 这个 fixture,缺了会 panic + - name: Build native plugin test fixture + run: cargo build -p micyou-plugin-fixture-native + working-directory: tauri-app - name: Rust tests run: cargo test --workspace working-directory: tauri-app @@ -83,6 +102,19 @@ jobs: distribution: 'liberica' - name: Setup Gradle uses: gradle/actions/setup-gradle@v6 + with: + cache-read-only: false + gradle-home-cache-cleanup: true + - name: Cache Kotlin/Gradle build outputs + uses: actions/cache@v6 + with: + path: | + ~/.gradle/caches + composeApp/build + build + key: ${{ runner.os }}-gradle-${{ hashFiles('gradle/libs.versions.toml', '**/*.gradle.kts', 'gradle.properties') }} + restore-keys: | + ${{ runner.os }}-gradle- - name: Grant execute permission for gradlew run: chmod +x gradlew - name: Build Android Debug diff --git a/composeApp/src/main/res/values-ca/strings.xml b/composeApp/src/main/res/values-ca/strings.xml index f06ad13d..8608b77f 100644 --- a/composeApp/src/main/res/values-ca/strings.xml +++ b/composeApp/src/main/res/values-ca/strings.xml @@ -400,13 +400,13 @@ Streaming stopped 下载电脑端喵~ 检查系统设置中的应用权限喵~ - Qualitat de l'enllaç + Qualitat de l\'enllaç Anada i tornada Jitter Pèrdua de paquets Extrem a extrem - Esperant l'escriptori… - Mesurat per l'escriptori + Esperant l\'escriptori… + Mesurat per l\'escriptori Excel·lent Bo Acceptable From 521b956b42b19327c3fdf4a612ca87ff0367ea46 Mon Sep 17 00:00:00 2001 From: OrientCOMPASS <316423573+OrientCOMPASS@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:36:48 +0800 Subject: [PATCH 10/12] feat(plugin-api): expose the phone battery in audio_state and device snapshots --- docs/plugins/api-reference.md | 7 +- docs/plugins/development-guide.md | 2 + .../crates/micyou-core/src/plugins/api.rs | 14 +++- tauri-app/crates/micyou-plugin/src/host.rs | 71 +++++++++++++++++++ .../crates/micyou-plugin/tests/boundary.rs | 1 + 5 files changed, 92 insertions(+), 3 deletions(-) diff --git a/docs/plugins/api-reference.md b/docs/plugins/api-reference.md index 25783f20..b7a24a5c 100644 --- a/docs/plugins/api-reference.md +++ b/docs/plugins/api-reference.md @@ -106,15 +106,18 @@ typedef struct mpl_host_api { - `audio_state` 返回 JSON 快照: ```json -{ "streaming": true, "sampleRate": 48000, "channels": 1, "inputLevel": 0.42, "processedLevel": 0.38, "queuedMs": 12.5, "muted": false } +{ "streaming": true, "sampleRate": 48000, "channels": 1, "inputLevel": 0.42, "processedLevel": 0.38, "queuedMs": 12.5, "muted": false, "battery": { "level": 78, "charging": true } } ``` +- `battery` 是手机上报的电量(`level` 0–100,`charging` 是否在充电);无设备、旧版手机不上报或连接的是 web 客户端时,**整个字段被省略**。新增字段是纯增量:旧版宿主不返回它,旧版插件忽略它,双方都不需要重新编译 - `connected_devices` 返回 JSON 数组: ```json -[ { "mode": "wifi", "label": "MicYou Mobile", "audioActive": true } ] +[ { "mode": "wifi", "label": "192.168.1.5", "audioActive": true, "battery": { "level": 78, "charging": true } } ] ``` +- web 客户端的 `battery` 同样省略;判定电量是否需要刷新时请以 `battery` 是否存在为准,不要用 `level: 0` 猜测 + - `host_info` 返回: ```json diff --git a/docs/plugins/development-guide.md b/docs/plugins/development-guide.md index 5bd13eff..06f4d557 100644 --- a/docs/plugins/development-guide.md +++ b/docs/plugins/development-guide.md @@ -343,6 +343,8 @@ WASM 插件是 core wasm 模块(无需 WASI),在 `wasmi` 纯 Rust 解释 | `plugin_dir` | `() -> i32` | -> 插件安装目录绝对路径字符串 | | `register_hotkey` | `(i32) -> i64` | 快捷键字符串指针 -> 句柄 id(0 = 失败) | +> `audio_state` 与 `connected_devices` 里的设备项自 2.2.x 起可能带一个可选的 `battery: { level, charging }`(手机上报的电量)。字段**可能整个缺失**(无设备 / 旧版手机 / web 客户端),解析时按可选字段处理即可;这是纯增量 JSON,旧插件不重新编译也照常工作。字段语义与示例见 [api-reference.md](api-reference.md)。 + ### 完整最小示例(Rust) `micyou-cli plugin create dev.micyou.hello --runtime wasm` 生成完整 Rust 骨架(推荐路径) diff --git a/tauri-app/crates/micyou-core/src/plugins/api.rs b/tauri-app/crates/micyou-core/src/plugins/api.rs index 5385efa8..8e47c3e8 100644 --- a/tauri-app/crates/micyou-core/src/plugins/api.rs +++ b/tauri-app/crates/micyou-core/src/plugins/api.rs @@ -19,7 +19,7 @@ use super::{lock_err, PluginHost}; use crate::transport::udp::ActiveAudioSession; use micyou_plugin::bus::PluginMessage; use micyou_plugin::host::{ - AudioStateSnapshot, DeviceSnapshot, HostApi, MessageTarget, PluginLogLevel, + AudioStateSnapshot, BatterySnapshot, DeviceSnapshot, HostApi, MessageTarget, PluginLogLevel, }; use micyou_plugin::{PluginError, PluginResult}; use std::collections::HashMap; @@ -204,6 +204,7 @@ impl HostApi for PluginHostApi { processed_level: f32::from_bits(stats.processed_level_bits.load(Ordering::Relaxed)), queued_ms, muted: stats.is_muted(), + battery: battery_snapshot(server), } } @@ -399,12 +400,14 @@ impl HostApi for PluginHostApi { mode: mode.to_string(), label: peer_ip.to_string(), audio_active: true, + battery: battery_snapshot(server), } } ActiveAudioSession::Inactive => DeviceSnapshot { mode: "wifi".to_string(), label: "pending...".to_string(), audio_active: false, + battery: battery_snapshot(server), }, }; devices.push(device); @@ -417,8 +420,17 @@ impl HostApi for PluginHostApi { mode: "web".to_string(), label: "web client".to_string(), audio_active: true, + battery: None, })); } devices } } + +/// Battery reported by the connected phone, in the plugin API's shape. +fn battery_snapshot(server: &crate::server::ServerState) -> Option { + server.network_stats.battery().map(|battery| BatterySnapshot { + level: battery.level, + charging: battery.charging, + }) +} diff --git a/tauri-app/crates/micyou-plugin/src/host.rs b/tauri-app/crates/micyou-plugin/src/host.rs index d0b466cf..cb2b6fe1 100644 --- a/tauri-app/crates/micyou-plugin/src/host.rs +++ b/tauri-app/crates/micyou-plugin/src/host.rs @@ -82,6 +82,24 @@ pub struct AudioStateSnapshot { pub queued_ms: f64, /// Whether the mute button is engaged. pub muted: bool, + /// Battery reported by the connected phone. Older hosts omit the field, + /// so consumers must treat it as optional (JSON stays additive). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub battery: Option, +} + +/// Battery of the connected phone, as reported over the control channel. +/// +/// Older plugins that deserialize [`AudioStateSnapshot`] into their own struct +/// simply ignore the extra key; no ABI bump is involved because the host API +/// hands snapshots over as JSON strings. +#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct BatterySnapshot { + /// Charge in percent (0..=100). + pub level: i32, + /// Whether the device reports itself as charging. + pub charging: bool, } /// Snapshot of a connected device (phone / web client). @@ -94,6 +112,10 @@ pub struct DeviceSnapshot { pub label: String, /// Whether the device audio session is active. pub audio_active: bool, + /// Battery reported by this device; `None` for web clients and legacy + /// phones that never send one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub battery: Option, } /// Target of a cross-device plugin message. @@ -253,12 +275,61 @@ pub trait HostApi: Send + Sync { #[cfg(test)] mod tests { use super::sandbox_path; + use super::{AudioStateSnapshot, BatterySnapshot, DeviceSnapshot}; use std::path::Path; fn dir() -> &'static Path { Path::new("/tmp/plugin-dir") } + /// A snapshot serialized by an older host has no `battery` key; plugins + /// (and the host itself) must still deserialize it. + #[test] + fn audio_state_without_battery_still_deserializes() { + let old = r#"{"streaming":true,"sampleRate":48000,"channels":1, + "inputLevel":0.4,"processedLevel":0.3,"queuedMs":12.5,"muted":false}"#; + let snapshot: AudioStateSnapshot = serde_json::from_str(old).expect("old JSON must parse"); + assert_eq!(snapshot.battery, None); + assert!(snapshot.streaming); + } + + #[test] + fn audio_state_serializes_battery_and_round_trips() { + let snapshot = AudioStateSnapshot { + streaming: true, + battery: Some(BatterySnapshot { + level: 78, + charging: true, + }), + ..AudioStateSnapshot::default() + }; + let json = serde_json::to_string(&snapshot).expect("serialize"); + assert!(json.contains(r#""battery":{"level":78,"charging":true}"#), "{json}"); + let back: AudioStateSnapshot = serde_json::from_str(&json).expect("round trip"); + assert_eq!(back.battery, snapshot.battery); + } + + /// The field is additive: an unknown key must not break an older plugin + /// struct that predates it (verified by serde's default behaviour). + #[test] + fn device_snapshot_skips_battery_when_unknown() { + assert_eq!( + serde_json::to_string(&DeviceSnapshot::default()).unwrap(), + r#"{"mode":"","label":"","audioActive":false}"# + ); + let with_battery = DeviceSnapshot { + mode: "wifi".into(), + label: "192.168.1.5".into(), + audio_active: true, + battery: Some(BatterySnapshot { + level: 12, + charging: false, + }), + }; + let json = serde_json::to_string(&with_battery).unwrap(); + assert!(json.contains(r#""battery":{"level":12,"charging":false}"#), "{json}"); + } + #[test] fn sandbox_accepts_normal_relative_paths() { let p = sandbox_path(dir(), "data/file.txt").expect("ok"); diff --git a/tauri-app/crates/micyou-plugin/tests/boundary.rs b/tauri-app/crates/micyou-plugin/tests/boundary.rs index 6882d0d0..c891294e 100644 --- a/tauri-app/crates/micyou-plugin/tests/boundary.rs +++ b/tauri-app/crates/micyou-plugin/tests/boundary.rs @@ -54,6 +54,7 @@ impl HostApi for TestHost { processed_level: 0.0, queued_ms: 0.0, muted: false, + battery: None, } } fn play_sound(&self, _p: &str) -> PluginResult<()> { From 5ce3d56bc3c7442f047746411d36bef33f33983b Mon Sep 17 00:00:00 2001 From: OrientCOMPASS <316423573+OrientCOMPASS@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:41:50 +0800 Subject: [PATCH 11/12] fix(plugin-api): read the battery from ServerHandles, not ServerState --- tauri-app/crates/micyou-core/src/plugins/api.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tauri-app/crates/micyou-core/src/plugins/api.rs b/tauri-app/crates/micyou-core/src/plugins/api.rs index 8e47c3e8..d57b8847 100644 --- a/tauri-app/crates/micyou-core/src/plugins/api.rs +++ b/tauri-app/crates/micyou-core/src/plugins/api.rs @@ -428,7 +428,7 @@ impl HostApi for PluginHostApi { } /// Battery reported by the connected phone, in the plugin API's shape. -fn battery_snapshot(server: &crate::server::ServerState) -> Option { +fn battery_snapshot(server: &crate::plugins::ServerHandles) -> Option { server.network_stats.battery().map(|battery| BatterySnapshot { level: battery.level, charging: battery.charging, From 19ad91c1543b1ef573efecb9721ffee74f5ab20a Mon Sep 17 00:00:00 2001 From: OrientCOMPASS <316423573+OrientCOMPASS@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:39:52 +0800 Subject: [PATCH 12/12] chore: keep workflows out of this PR --- .github/workflows/verify.yml | 121 ----------------------------------- 1 file changed, 121 deletions(-) delete mode 100644 .github/workflows/verify.yml diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml deleted file mode 100644 index 6dff4804..00000000 --- a/.github/workflows/verify.yml +++ /dev/null @@ -1,121 +0,0 @@ -name: Verify - -# 轻量门禁:类型检查 + web 单测 + Rust 单测 + clippy + Android Debug 编译。 -# 多平台 Tauri 打包(development.yml / release.yml)耗时十几分钟,不在每次 -# 推送时跑;日常迭代用这个 workflow,`workflow_dispatch` 可指定任意分支。 -# -# 缓存策略(目标是「第二次推送几乎只跑变更部分」): -# * Bun 依赖缓存 ~/.bun/install/cache,key 由 bun.lock 哈希决定 -# * Rust 用 Swatinem/rust-cache 缓存依赖与 workspace target(含 sidecar 产物) -# * cargo-about 由 taiki-e/install-action 按版本缓存二进制 -# * Gradle 由 gradle/actions/setup-gradle 缓存 ~/.gradle 与配置缓存 -# * 同一分支新推送取消旧运行,避免排队浪费额度 - -on: - workflow_dispatch: - push: - branches: [ "main", "master", "develop" ] - pull_request: - branches: [ "main", "master", "develop" ] - -concurrency: - group: verify-${{ github.ref }} - cancel-in-progress: true - -jobs: - # ----------------- 前端类型检查 + web 单测 + Rust 单测/clippy ----------------- - verify: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - - name: Setup Bun - uses: oven-sh/setup-bun@v2 - with: - bun-version-file: tauri-app/package.json - - name: Cache Bun dependencies - uses: actions/cache@v6 - with: - path: ~/.bun/install/cache - key: ${{ runner.os }}-${{ runner.arch }}-bun-${{ hashFiles('tauri-app/bun.lock') }} - restore-keys: | - ${{ runner.os }}-${{ runner.arch }}-bun- - - name: Setup Rust (stable) - uses: dtolnay/rust-toolchain@stable - with: - components: clippy - - name: Cache Rust - uses: Swatinem/rust-cache@v2 - with: - workspaces: tauri-app -> target - cache-on-failure: true - cache-all-crates: true - # 独立前缀,避免和 development.yml 的多平台构建互相挤掉缓存 - prefix-key: verify - - name: Install cargo-about - uses: taiki-e/install-action@v2 - with: - tool: cargo-about@0.9.1 - - name: Install System Dependencies - run: | - sudo apt-get update - sudo apt-get install -y \ - libwebkit2gtk-4.1-dev \ - libayatana-appindicator3-dev \ - librsvg2-dev \ - patchelf \ - libxdo-dev \ - libssl-dev \ - libasound2-dev - - name: Install Frontend Dependencies - run: bun install --frozen-lockfile - working-directory: tauri-app - - name: Frontend type check + build - run: bun run build - working-directory: tauri-app - - name: Web tests - run: bun run test:web - working-directory: tauri-app - # src-tauri 的 build.rs 要求 dist/ 与 sidecar 二进制都已存在 - - name: Prepare sidecars - run: bun run prepare-sidecars:dev - working-directory: tauri-app - # native 插件测试会 dlopen 这个 fixture,缺了会 panic - - name: Build native plugin test fixture - run: cargo build -p micyou-plugin-fixture-native - working-directory: tauri-app - - name: Rust tests - run: cargo test --workspace - working-directory: tauri-app - - name: Rust clippy - run: cargo clippy --workspace --all-targets - working-directory: tauri-app - - # ----------------- Android Debug 编译 ----------------- - android: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - - name: set up JDK 21 - uses: actions/setup-java@v5 - with: - java-version: '21' - distribution: 'liberica' - - name: Setup Gradle - uses: gradle/actions/setup-gradle@v6 - with: - cache-read-only: false - gradle-home-cache-cleanup: true - - name: Cache Kotlin/Gradle build outputs - uses: actions/cache@v6 - with: - path: | - ~/.gradle/caches - composeApp/build - build - key: ${{ runner.os }}-gradle-${{ hashFiles('gradle/libs.versions.toml', '**/*.gradle.kts', 'gradle.properties') }} - restore-keys: | - ${{ runner.os }}-gradle- - - name: Grant execute permission for gradlew - run: chmod +x gradlew - - name: Build Android Debug - run: ./gradlew :composeApp:assembleDebug