use std::{collections::HashSet, sync::Arc, time::Duration}; use astrbot_desktop_lib::networking::{GatewayClient, GatewayClientConfig, SlotKind}; use desktop_protocol::{ AuthLoginRequest, AuthLoginResponse, ClientCapabilities, ConnectionState, EventMetadata, GatewayEvent, GatewayEventBody, HeartbeatPayload, PROTOCOL_VERSION, }; use mock_gateway::{MockGatewayConfig, MockInstanceKind, MockScenario, spawn_mock_gateway}; use tokio::sync::mpsc; use tokio_util::sync::CancellationToken; async fn login(base_url: &str) -> String { let response = reqwest::Client::new() .post(format!("{base_url}/desktop/v1/auth/login")) .json(&AuthLoginRequest { client_id: "integration-client".into(), device_id: "integration-device".into(), credential: "fixture-only-not-a-real-secret".into(), capabilities: ClientCapabilities { protocol_version: PROTOCOL_VERSION.into(), app_version: "0.1.0-alpha.0".into(), platform: "windows".into(), features: vec!["sse".into()], }, }) .send() .await .expect("login request") .error_for_status() .expect("login status") .json::() .await .expect("login response"); response.access_token } fn heartbeat(event_id: &str, server_instance_id: &str) -> GatewayEvent { GatewayEvent::new( EventMetadata::new(event_id, server_instance_id, "2026-07-18T00:00:00Z", 1), GatewayEventBody::Heartbeat(HeartbeatPayload { interval_ms: 1_000 }), ) } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn dual_sse_streams_bind_local_profiles_and_isolate_deduplication() { let companion = spawn_mock_gateway(MockGatewayConfig::for_test(MockInstanceKind::Companion)) .await .expect("companion mock"); let operations = spawn_mock_gateway(MockGatewayConfig::for_test(MockInstanceKind::Operations)) .await .expect("operations mock"); let companion_client = Arc::new( GatewayClient::new(GatewayClientConfig { profile_id: "profile-companion".into(), slot: SlotKind::Companion, base_url: companion.base_url(), expected_server_instance_id: companion.server_instance_id().into(), bearer_token: Some(login(&companion.base_url()).await.into()), }) .expect("companion client"), ); let operations_client = Arc::new( GatewayClient::new(GatewayClientConfig { profile_id: "profile-operations".into(), slot: SlotKind::Operations, base_url: operations.base_url(), expected_server_instance_id: operations.server_instance_id().into(), bearer_token: Some(login(&operations.base_url()).await.into()), }) .expect("operations client"), ); let (sender, mut receiver) = mpsc::channel(16); let companion_cancel = CancellationToken::new(); let operations_cancel = CancellationToken::new(); let companion_task = { let client = companion_client.clone(); let sender = sender.clone(); let cancellation = companion_cancel.clone(); tokio::spawn(async move { client.stream_once(None, &sender, &cancellation).await }) }; let operations_task = { let client = operations_client.clone(); let sender = sender.clone(); let cancellation = operations_cancel.clone(); tokio::spawn(async move { client.stream_once(None, &sender, &cancellation).await }) }; drop(sender); tokio::time::sleep(Duration::from_millis(100)).await; let shared_id = "shared-event-id"; let companion_event = heartbeat(shared_id, companion.server_instance_id()); let operations_event = heartbeat(shared_id, operations.server_instance_id()); companion .emit_event(companion_event.clone()) .await .expect("emit companion"); operations .emit_event(operations_event) .await .expect("emit operations"); let first = tokio::time::timeout(Duration::from_secs(3), receiver.recv()) .await .expect("first timeout") .expect("first event"); let second = tokio::time::timeout(Duration::from_secs(3), receiver.recv()) .await .expect("second timeout") .expect("second event"); let bindings = HashSet::from([ (first.profile_id.as_str(), first.slot), (second.profile_id.as_str(), second.slot), ]); assert!(bindings.contains(&("profile-companion", SlotKind::Companion))); assert!(bindings.contains(&("profile-operations", SlotKind::Operations))); assert_eq!(first.event_id, shared_id); assert_eq!(second.event_id, shared_id); companion .emit_event(companion_event) .await .expect("replay duplicate"); operations .emit_event(heartbeat( "operations-after-companion-duplicate", operations.server_instance_id(), )) .await .expect("emit operations follow-up"); let follow_up = tokio::time::timeout(Duration::from_secs(3), receiver.recv()) .await .expect("follow-up timeout") .expect("follow-up event"); assert_eq!(follow_up.profile_id, "profile-operations"); assert_eq!(follow_up.event_id, "operations-after-companion-duplicate"); companion.disconnect_streams(); operations_cancel.cancel(); companion_cancel.cancel(); companion_task .await .expect("companion task") .expect("companion stream"); operations_task .await .expect("operations task") .expect("operations stream"); companion.shutdown().await.expect("companion shutdown"); operations.shutdown().await.expect("operations shutdown"); } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn reconnects_one_slot_without_interrupting_the_other() { let mut companion_config = MockGatewayConfig::for_test(MockInstanceKind::Companion); companion_config.scenario = MockScenario::DisconnectOnce; companion_config.heartbeat_interval = Some(Duration::from_millis(50)); let mut operations_config = MockGatewayConfig::for_test(MockInstanceKind::Operations); operations_config.heartbeat_interval = Some(Duration::from_millis(50)); let companion = spawn_mock_gateway(companion_config) .await .expect("companion reconnect mock"); let operations = spawn_mock_gateway(operations_config) .await .expect("operations steady mock"); let companion_client = Arc::new( GatewayClient::new(GatewayClientConfig { profile_id: "profile-companion-reconnect".into(), slot: SlotKind::Companion, base_url: companion.base_url(), expected_server_instance_id: companion.server_instance_id().into(), bearer_token: Some(login(&companion.base_url()).await.into()), }) .expect("companion reconnect client"), ); let operations_client = Arc::new( GatewayClient::new(GatewayClientConfig { profile_id: "profile-operations-steady".into(), slot: SlotKind::Operations, base_url: operations.base_url(), expected_server_instance_id: operations.server_instance_id().into(), bearer_token: Some(login(&operations.base_url()).await.into()), }) .expect("operations steady client"), ); let (sender, mut receiver) = mpsc::channel(64); let companion_cancel = CancellationToken::new(); let operations_cancel = CancellationToken::new(); let companion_task = { let client = companion_client.clone(); let sender = sender.clone(); let cancellation = companion_cancel.clone(); tokio::spawn(async move { client.run_reconnecting(&sender, &cancellation).await }) }; let operations_task = { let client = operations_client.clone(); let sender = sender.clone(); let cancellation = operations_cancel.clone(); tokio::spawn(async move { client.run_reconnecting(&sender, &cancellation).await }) }; drop(sender); let (companion_events, operations_events) = tokio::time::timeout(Duration::from_secs(5), async { let mut companion_events = 0_usize; let mut operations_events = 0_usize; while companion_events < 8 || operations_events < 8 { let event = receiver.recv().await.expect("reconnect event channel"); match event.profile_id.as_str() { "profile-companion-reconnect" => companion_events += 1, "profile-operations-steady" => operations_events += 1, unexpected => panic!("unexpected local profile binding: {unexpected}"), } } (companion_events, operations_events) }) .await .expect("both slots continue after one disconnect"); assert!(companion_events >= 8); assert!(operations_events >= 8); companion_cancel.cancel(); operations_cancel.cancel(); companion_task .await .expect("companion reconnect task") .expect("companion reconnect result"); operations_task .await .expect("operations steady task") .expect("operations steady result"); assert_eq!( *companion_client.state_receiver().borrow(), ConnectionState::Disconnected ); assert_eq!( *operations_client.state_receiver().borrow(), ConnectionState::Disconnected ); companion.shutdown().await.expect("companion shutdown"); operations.shutdown().await.expect("operations shutdown"); }