test(p00): add frontend browser rust and windows checks
这个提交存在于:
父节点
01607c69ff
当前提交
69b432b6ed
共有 9 个文件被更改,包括 911 次插入 和 0 次删除
|
|
@ -0,0 +1,92 @@
|
||||||
|
use desktop_protocol::{
|
||||||
|
ActiveSlotKind, BoundGatewayEvent, GatewayEventBody, PROTOCOL_VERSION, ProtocolError,
|
||||||
|
RawProtocolEnvelope, RiskLevel, ToolProposal,
|
||||||
|
};
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
fn raw_event(payload: serde_json::Value) -> RawProtocolEnvelope {
|
||||||
|
RawProtocolEnvelope {
|
||||||
|
protocol_version: PROTOCOL_VERSION.to_owned(),
|
||||||
|
event_type: "system.heartbeat".to_owned(),
|
||||||
|
event_id: "shared-event-id".to_owned(),
|
||||||
|
request_id: None,
|
||||||
|
server_profile_hint: Some("spoofed-operations-profile".to_owned()),
|
||||||
|
server_instance_id: "server-companion".to_owned(),
|
||||||
|
conversation_id: Some("same-conversation".to_owned()),
|
||||||
|
message_id: None,
|
||||||
|
session_id: None,
|
||||||
|
timestamp: "2026-01-01T00:00:00Z".to_owned(),
|
||||||
|
sequence: Some(1),
|
||||||
|
payload,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn local_profile_binding_ignores_server_profile_hint() {
|
||||||
|
let bound = BoundGatewayEvent::bind(
|
||||||
|
raw_event(json!({ "intervalMs": 1_000 })),
|
||||||
|
"local-companion-profile",
|
||||||
|
ActiveSlotKind::Companion,
|
||||||
|
"server-companion",
|
||||||
|
)
|
||||||
|
.expect("valid event should bind");
|
||||||
|
|
||||||
|
assert_eq!(bound.profile_id, "local-companion-profile");
|
||||||
|
assert_eq!(bound.slot, ActiveSlotKind::Companion);
|
||||||
|
assert_eq!(
|
||||||
|
bound.event.metadata.server_profile_hint.as_deref(),
|
||||||
|
Some("spoofed-operations-profile")
|
||||||
|
);
|
||||||
|
assert!(matches!(bound.event.body, GatewayEventBody::Heartbeat(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn server_instance_mismatch_is_rejected() {
|
||||||
|
let error = BoundGatewayEvent::bind(
|
||||||
|
raw_event(json!({ "intervalMs": 1_000 })),
|
||||||
|
"local-profile",
|
||||||
|
ActiveSlotKind::Companion,
|
||||||
|
"different-server",
|
||||||
|
)
|
||||||
|
.expect_err("changed server identity must be rejected");
|
||||||
|
|
||||||
|
assert!(matches!(
|
||||||
|
error,
|
||||||
|
ProtocolError::ServerInstanceMismatch { .. }
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unsupported_event_type_is_explicit_and_non_panicking() {
|
||||||
|
let mut raw = raw_event(json!({}));
|
||||||
|
raw.event_type = "future.event".to_owned();
|
||||||
|
|
||||||
|
let error = desktop_protocol::GatewayEvent::try_from(raw)
|
||||||
|
.expect_err("unknown event should be surfaced to the caller");
|
||||||
|
assert!(matches!(error, ProtocolError::UnsupportedEventType { .. }));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tool_proposal_rejects_unknown_outer_fields() {
|
||||||
|
let value = json!({
|
||||||
|
"actionId": "action-1",
|
||||||
|
"toolName": "query_recent_event_logs",
|
||||||
|
"reason": "Inspect an application failure",
|
||||||
|
"riskLevel": "read",
|
||||||
|
"arguments": { "provider": "Application", "maxEntries": 20 },
|
||||||
|
"requestedAt": "2026-01-01T00:00:00Z",
|
||||||
|
"expiresAt": "2026-01-01T00:05:00Z",
|
||||||
|
"requiresApproval": true,
|
||||||
|
"executeCommand": "not-allowed"
|
||||||
|
});
|
||||||
|
|
||||||
|
assert!(serde_json::from_value::<ToolProposal>(value).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tool_risk_level_uses_stable_wire_values() {
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_value(RiskLevel::ReversibleWrite).unwrap(),
|
||||||
|
json!("reversible-write")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,278 @@
|
||||||
|
use std::{
|
||||||
|
net::{IpAddr, Ipv4Addr, SocketAddr},
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
|
||||||
|
use desktop_protocol::{
|
||||||
|
ActiveSlotKind, AuthLoginRequest, AuthLoginResponse, BoundGatewayEvent, ClientCapabilities,
|
||||||
|
EventMetadata, GatewayEvent, GatewayEventBody, HealthResponse, HeartbeatPayload,
|
||||||
|
PROTOCOL_VERSION, RawProtocolEnvelope,
|
||||||
|
};
|
||||||
|
use mock_gateway::{MockGatewayConfig, MockGatewayError, MockInstanceKind, spawn_mock_gateway};
|
||||||
|
use reqwest::{Client, Response, StatusCode};
|
||||||
|
use serde_json::Value;
|
||||||
|
use tokio::time::timeout;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn refuses_non_loopback_bind_addresses() {
|
||||||
|
let mut config = MockGatewayConfig::for_test(MockInstanceKind::Companion);
|
||||||
|
config.bind_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0);
|
||||||
|
let result = spawn_mock_gateway(config).await;
|
||||||
|
assert!(matches!(result, Err(MockGatewayError::NonLoopbackBind(_))));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn companion_and_operations_streams_are_independent_and_replay_by_cursor() {
|
||||||
|
let companion = spawn_mock_gateway(MockGatewayConfig::for_test(MockInstanceKind::Companion))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let operations = spawn_mock_gateway(MockGatewayConfig::for_test(MockInstanceKind::Operations))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let client = Client::new();
|
||||||
|
|
||||||
|
let companion_health: HealthResponse = client
|
||||||
|
.get(format!("{}/desktop/v1/health", companion.base_url()))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.error_for_status()
|
||||||
|
.unwrap()
|
||||||
|
.json()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let operations_health: HealthResponse = client
|
||||||
|
.get(format!("{}/desktop/v1/health", operations.base_url()))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.error_for_status()
|
||||||
|
.unwrap()
|
||||||
|
.json()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_ne!(
|
||||||
|
companion_health.server_instance_id,
|
||||||
|
operations_health.server_instance_id
|
||||||
|
);
|
||||||
|
|
||||||
|
let companion_token = login(&client, &companion.base_url()).await;
|
||||||
|
let operations_token = login(&client, &operations.base_url()).await;
|
||||||
|
let mut companion_stream =
|
||||||
|
open_stream(&client, &companion.base_url(), &companion_token, None).await;
|
||||||
|
let mut operations_stream =
|
||||||
|
open_stream(&client, &operations.base_url(), &operations_token, None).await;
|
||||||
|
let mut companion_buffer = String::new();
|
||||||
|
let mut operations_buffer = String::new();
|
||||||
|
|
||||||
|
let shared_event_id = "same-event-id";
|
||||||
|
companion
|
||||||
|
.emit_event(event_for(
|
||||||
|
shared_event_id,
|
||||||
|
companion.server_instance_id(),
|
||||||
|
1,
|
||||||
|
))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
operations
|
||||||
|
.emit_event(event_for(
|
||||||
|
shared_event_id,
|
||||||
|
operations.server_instance_id(),
|
||||||
|
1,
|
||||||
|
))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let companion_wire = next_sse_data(&mut companion_stream, &mut companion_buffer).await;
|
||||||
|
let operations_wire = next_sse_data(&mut operations_stream, &mut operations_buffer).await;
|
||||||
|
assert_eq!(companion_wire["eventId"], shared_event_id);
|
||||||
|
assert_eq!(operations_wire["eventId"], shared_event_id);
|
||||||
|
assert_ne!(
|
||||||
|
companion_wire["serverInstanceId"],
|
||||||
|
operations_wire["serverInstanceId"]
|
||||||
|
);
|
||||||
|
|
||||||
|
let companion_bound = bind_wire(
|
||||||
|
companion_wire,
|
||||||
|
"local-companion",
|
||||||
|
ActiveSlotKind::Companion,
|
||||||
|
companion.server_instance_id(),
|
||||||
|
);
|
||||||
|
let operations_bound = bind_wire(
|
||||||
|
operations_wire,
|
||||||
|
"local-operations",
|
||||||
|
ActiveSlotKind::Operations,
|
||||||
|
operations.server_instance_id(),
|
||||||
|
);
|
||||||
|
assert_eq!(companion_bound.profile_id, "local-companion");
|
||||||
|
assert_eq!(operations_bound.profile_id, "local-operations");
|
||||||
|
|
||||||
|
companion.disconnect_streams();
|
||||||
|
let operations_second = operations
|
||||||
|
.emit_body(GatewayEventBody::Heartbeat(HeartbeatPayload {
|
||||||
|
interval_ms: 1_000,
|
||||||
|
}))
|
||||||
|
.await;
|
||||||
|
let operations_wire = next_sse_data(&mut operations_stream, &mut operations_buffer).await;
|
||||||
|
assert_eq!(
|
||||||
|
operations_wire["eventId"],
|
||||||
|
operations_second.metadata.event_id
|
||||||
|
);
|
||||||
|
|
||||||
|
let companion_second = companion
|
||||||
|
.emit_body(GatewayEventBody::Heartbeat(HeartbeatPayload {
|
||||||
|
interval_ms: 1_000,
|
||||||
|
}))
|
||||||
|
.await;
|
||||||
|
drop(companion_stream);
|
||||||
|
let mut resumed = open_stream(
|
||||||
|
&client,
|
||||||
|
&companion.base_url(),
|
||||||
|
&companion_token,
|
||||||
|
Some(shared_event_id),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let mut resumed_buffer = String::new();
|
||||||
|
let replayed = next_sse_data(&mut resumed, &mut resumed_buffer).await;
|
||||||
|
assert_eq!(replayed["eventId"], companion_second.metadata.event_id);
|
||||||
|
drop(resumed);
|
||||||
|
drop(operations_stream);
|
||||||
|
|
||||||
|
companion.shutdown().await.unwrap();
|
||||||
|
operations.shutdown().await.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn duplicate_events_are_emitted_with_the_original_event_id() {
|
||||||
|
let gateway = spawn_mock_gateway(MockGatewayConfig::for_test(MockInstanceKind::Companion))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let client = Client::new();
|
||||||
|
let token = login(&client, &gateway.base_url()).await;
|
||||||
|
let mut stream = open_stream(&client, &gateway.base_url(), &token, None).await;
|
||||||
|
let mut buffer = String::new();
|
||||||
|
|
||||||
|
let event = gateway
|
||||||
|
.emit_body(GatewayEventBody::Heartbeat(HeartbeatPayload {
|
||||||
|
interval_ms: 1_000,
|
||||||
|
}))
|
||||||
|
.await;
|
||||||
|
let first = next_sse_data(&mut stream, &mut buffer).await;
|
||||||
|
assert!(gateway.replay_event(&event.metadata.event_id).await);
|
||||||
|
let duplicate = next_sse_data(&mut stream, &mut buffer).await;
|
||||||
|
assert_eq!(first["eventId"], duplicate["eventId"]);
|
||||||
|
drop(stream);
|
||||||
|
|
||||||
|
gateway.shutdown().await.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rejected_authentication_is_scoped_to_one_instance() {
|
||||||
|
let companion = spawn_mock_gateway(MockGatewayConfig::for_test(MockInstanceKind::Companion))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let operations = spawn_mock_gateway(MockGatewayConfig::for_test(MockInstanceKind::Operations))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
operations.set_auth_mode(mock_gateway::AuthMode::Reject);
|
||||||
|
let client = Client::new();
|
||||||
|
|
||||||
|
let companion_response = login_response(&client, &companion.base_url()).await;
|
||||||
|
let operations_response = login_response(&client, &operations.base_url()).await;
|
||||||
|
assert!(companion_response.status().is_success());
|
||||||
|
assert_eq!(operations_response.status(), StatusCode::UNAUTHORIZED);
|
||||||
|
|
||||||
|
companion.shutdown().await.unwrap();
|
||||||
|
operations.shutdown().await.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn event_for(event_id: &str, server_instance_id: &str, sequence: u64) -> GatewayEvent {
|
||||||
|
GatewayEvent::new(
|
||||||
|
EventMetadata::new(
|
||||||
|
event_id,
|
||||||
|
server_instance_id,
|
||||||
|
"2026-01-01T00:00:00Z",
|
||||||
|
sequence,
|
||||||
|
),
|
||||||
|
GatewayEventBody::Heartbeat(HeartbeatPayload { interval_ms: 1_000 }),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bind_wire(
|
||||||
|
value: Value,
|
||||||
|
profile_id: &str,
|
||||||
|
slot: ActiveSlotKind,
|
||||||
|
expected_server: &str,
|
||||||
|
) -> BoundGatewayEvent {
|
||||||
|
let raw: RawProtocolEnvelope = serde_json::from_value(value).unwrap();
|
||||||
|
BoundGatewayEvent::bind(raw, profile_id, slot, expected_server).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn login(client: &Client, base_url: &str) -> String {
|
||||||
|
let response = login_response(client, base_url)
|
||||||
|
.await
|
||||||
|
.error_for_status()
|
||||||
|
.unwrap();
|
||||||
|
response
|
||||||
|
.json::<AuthLoginResponse>()
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.access_token
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn login_response(client: &Client, base_url: &str) -> Response {
|
||||||
|
client
|
||||||
|
.post(format!("{base_url}/desktop/v1/auth/login"))
|
||||||
|
.json(&AuthLoginRequest {
|
||||||
|
client_id: "integration-client".to_owned(),
|
||||||
|
device_id: "integration-device".to_owned(),
|
||||||
|
credential: Uuid::new_v4().to_string(),
|
||||||
|
capabilities: ClientCapabilities {
|
||||||
|
protocol_version: PROTOCOL_VERSION.to_owned(),
|
||||||
|
app_version: "0.1.0-test".to_owned(),
|
||||||
|
platform: "windows".to_owned(),
|
||||||
|
features: vec!["events.sse".to_owned()],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn open_stream(
|
||||||
|
client: &Client,
|
||||||
|
base_url: &str,
|
||||||
|
token: &str,
|
||||||
|
last_event_id: Option<&str>,
|
||||||
|
) -> Response {
|
||||||
|
let mut request = client
|
||||||
|
.get(format!("{base_url}/desktop/v1/events/stream"))
|
||||||
|
.bearer_auth(token);
|
||||||
|
if let Some(last_event_id) = last_event_id {
|
||||||
|
request = request.header("Last-Event-ID", last_event_id);
|
||||||
|
}
|
||||||
|
request.send().await.unwrap().error_for_status().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn next_sse_data(response: &mut Response, buffer: &mut String) -> Value {
|
||||||
|
timeout(Duration::from_secs(3), async {
|
||||||
|
loop {
|
||||||
|
while let Some(frame_end) = buffer.find("\n\n") {
|
||||||
|
let frame = buffer[..frame_end].to_owned();
|
||||||
|
buffer.drain(..frame_end + 2);
|
||||||
|
if let Some(data) = frame.lines().find_map(|line| line.strip_prefix("data: ")) {
|
||||||
|
return serde_json::from_str(data).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let chunk = response
|
||||||
|
.chunk()
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.expect("SSE stream closed before an event arrived");
|
||||||
|
buffer.push_str(std::str::from_utf8(&chunk).unwrap());
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("timed out waiting for SSE data")
|
||||||
|
}
|
||||||
115
crates/mock-gateway/tests/soak.rs
普通文件
115
crates/mock-gateway/tests/soak.rs
普通文件
|
|
@ -0,0 +1,115 @@
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use desktop_protocol::{AuthLoginRequest, AuthLoginResponse, ClientCapabilities, PROTOCOL_VERSION};
|
||||||
|
use mock_gateway::{MockGatewayConfig, MockInstanceKind, spawn_mock_gateway};
|
||||||
|
use reqwest::{Client, Response};
|
||||||
|
use serde_json::Value;
|
||||||
|
use tokio::time::{Instant, timeout};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
#[ignore = "manual P00 acceptance run: holds two SSE streams for 30 minutes"]
|
||||||
|
async fn dual_sse_soak_30_minutes_without_cross_routing() {
|
||||||
|
let companion = spawn_mock_gateway(MockGatewayConfig::new(MockInstanceKind::Companion, 0))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let operations = spawn_mock_gateway(MockGatewayConfig::new(MockInstanceKind::Operations, 0))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let client = Client::new();
|
||||||
|
let companion_token = login(&client, &companion.base_url()).await;
|
||||||
|
let operations_token = login(&client, &operations.base_url()).await;
|
||||||
|
let mut companion_stream = open_stream(&client, &companion.base_url(), &companion_token).await;
|
||||||
|
let mut operations_stream =
|
||||||
|
open_stream(&client, &operations.base_url(), &operations_token).await;
|
||||||
|
let mut companion_buffer = String::new();
|
||||||
|
let mut operations_buffer = String::new();
|
||||||
|
let mut companion_events = 0_u64;
|
||||||
|
let mut operations_events = 0_u64;
|
||||||
|
let started_at = Instant::now();
|
||||||
|
let deadline = started_at + Duration::from_secs(30 * 60);
|
||||||
|
|
||||||
|
while Instant::now() < deadline {
|
||||||
|
tokio::select! {
|
||||||
|
event = next_sse_data(&mut companion_stream, &mut companion_buffer) => {
|
||||||
|
assert_eq!(event["serverInstanceId"], companion.server_instance_id());
|
||||||
|
companion_events += 1;
|
||||||
|
}
|
||||||
|
event = next_sse_data(&mut operations_stream, &mut operations_buffer) => {
|
||||||
|
assert_eq!(event["serverInstanceId"], operations.server_instance_id());
|
||||||
|
operations_events += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
println!(
|
||||||
|
"soak summary: elapsed_seconds={} companion_events={} operations_events={}",
|
||||||
|
started_at.elapsed().as_secs(),
|
||||||
|
companion_events,
|
||||||
|
operations_events
|
||||||
|
);
|
||||||
|
assert!(companion_events >= 1_700, "companion stream stalled");
|
||||||
|
assert!(operations_events >= 1_700, "operations stream stalled");
|
||||||
|
drop(companion_stream);
|
||||||
|
drop(operations_stream);
|
||||||
|
companion.shutdown().await.unwrap();
|
||||||
|
operations.shutdown().await.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn login(client: &Client, base_url: &str) -> String {
|
||||||
|
client
|
||||||
|
.post(format!("{base_url}/desktop/v1/auth/login"))
|
||||||
|
.json(&AuthLoginRequest {
|
||||||
|
client_id: "soak-client".to_owned(),
|
||||||
|
device_id: "soak-device".to_owned(),
|
||||||
|
credential: Uuid::new_v4().to_string(),
|
||||||
|
capabilities: ClientCapabilities {
|
||||||
|
protocol_version: PROTOCOL_VERSION.to_owned(),
|
||||||
|
app_version: "0.1.0-soak".to_owned(),
|
||||||
|
platform: "windows".to_owned(),
|
||||||
|
features: vec!["events.sse".to_owned()],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.error_for_status()
|
||||||
|
.unwrap()
|
||||||
|
.json::<AuthLoginResponse>()
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.access_token
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn open_stream(client: &Client, base_url: &str, token: &str) -> Response {
|
||||||
|
client
|
||||||
|
.get(format!("{base_url}/desktop/v1/events/stream"))
|
||||||
|
.bearer_auth(token)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.error_for_status()
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn next_sse_data(response: &mut Response, buffer: &mut String) -> Value {
|
||||||
|
timeout(Duration::from_secs(5), async {
|
||||||
|
loop {
|
||||||
|
while let Some(frame_end) = buffer.find("\n\n") {
|
||||||
|
let frame = buffer[..frame_end].to_owned();
|
||||||
|
buffer.drain(..frame_end + 2);
|
||||||
|
if let Some(data) = frame.lines().find_map(|line| line.strip_prefix("data: ")) {
|
||||||
|
return serde_json::from_str(data).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let chunk = response
|
||||||
|
.chunk()
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.expect("SSE stream closed during soak test");
|
||||||
|
buffer.push_str(std::str::from_utf8(&chunk).unwrap());
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("SSE stream stalled during soak test")
|
||||||
|
}
|
||||||
28
playwright.config.ts
普通文件
28
playwright.config.ts
普通文件
|
|
@ -0,0 +1,28 @@
|
||||||
|
import { defineConfig, devices } from "@playwright/test";
|
||||||
|
|
||||||
|
const desktopChrome = {
|
||||||
|
...devices["Desktop Chrome"],
|
||||||
|
...(process.env.CI ? {} : { channel: "chrome" as const }),
|
||||||
|
};
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
testDir: "./tests/e2e",
|
||||||
|
outputDir: "test-results",
|
||||||
|
timeout: 30_000,
|
||||||
|
fullyParallel: true,
|
||||||
|
forbidOnly: Boolean(process.env.CI),
|
||||||
|
retries: process.env.CI ? 1 : 0,
|
||||||
|
reporter: process.env.CI ? "line" : "list",
|
||||||
|
use: {
|
||||||
|
baseURL: "http://127.0.0.1:4173",
|
||||||
|
trace: "retain-on-failure",
|
||||||
|
},
|
||||||
|
projects: [{ name: "chromium", use: desktopChrome }],
|
||||||
|
webServer: {
|
||||||
|
command:
|
||||||
|
"node ./node_modules/vite/bin/vite.js preview --host 127.0.0.1 --port 4173 --strictPort",
|
||||||
|
url: "http://127.0.0.1:4173",
|
||||||
|
reuseExistingServer: !process.env.CI,
|
||||||
|
timeout: 120_000,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
@ -0,0 +1,255 @@
|
||||||
|
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::<AuthLoginResponse>()
|
||||||
|
.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");
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,99 @@
|
||||||
|
#![cfg(windows)]
|
||||||
|
|
||||||
|
use std::{thread, time::Duration};
|
||||||
|
|
||||||
|
use astrbot_desktop_lib::windows::{
|
||||||
|
capture::{CaptureLimits, WindowCaptureError, capture_selected_window},
|
||||||
|
foreground_window::{ForegroundWindowError, inspect_foreground_window},
|
||||||
|
uia::{UiaReadLimits, read_standard_dialog_text},
|
||||||
|
};
|
||||||
|
use windows::{
|
||||||
|
Win32::{
|
||||||
|
Foundation::{HWND, LPARAM, WPARAM},
|
||||||
|
UI::WindowsAndMessaging::{
|
||||||
|
FindWindowW, GetForegroundWindow, MB_OK, MessageBoxW, PostMessageW,
|
||||||
|
SetForegroundWindow, WM_CLOSE,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
core::w,
|
||||||
|
};
|
||||||
|
|
||||||
|
const TEST_TITLE: &str = "AstrBot Desktop P00 Safe Provider Test";
|
||||||
|
const TEST_BODY: &str = "Known non-sensitive UI Automation fixture text.";
|
||||||
|
|
||||||
|
struct DialogGuard(HWND);
|
||||||
|
|
||||||
|
impl Drop for DialogGuard {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
unsafe {
|
||||||
|
let _ = PostMessageW(Some(self.0), WM_CLOSE, WPARAM(0), LPARAM(0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wait_for_test_dialog() -> HWND {
|
||||||
|
for _ in 0..100 {
|
||||||
|
if let Ok(window) =
|
||||||
|
unsafe { FindWindowW(w!("#32770"), w!("AstrBot Desktop P00 Safe Provider Test")) }
|
||||||
|
&& !window.0.is_null()
|
||||||
|
{
|
||||||
|
return window;
|
||||||
|
}
|
||||||
|
thread::sleep(Duration::from_millis(50));
|
||||||
|
}
|
||||||
|
panic!("the controlled test dialog did not appear");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[ignore = "opens a controlled, non-sensitive Windows dialog for native provider validation"]
|
||||||
|
fn reads_and_captures_only_the_controlled_standard_dialog() {
|
||||||
|
let dialog_thread = thread::spawn(|| unsafe {
|
||||||
|
let _ = MessageBoxW(
|
||||||
|
None,
|
||||||
|
w!("Known non-sensitive UI Automation fixture text."),
|
||||||
|
w!("AstrBot Desktop P00 Safe Provider Test"),
|
||||||
|
MB_OK,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
let window = wait_for_test_dialog();
|
||||||
|
let guard = DialogGuard(window);
|
||||||
|
assert!(unsafe { SetForegroundWindow(window) }.as_bool());
|
||||||
|
|
||||||
|
for _ in 0..40 {
|
||||||
|
if unsafe { GetForegroundWindow() } == window {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
thread::sleep(Duration::from_millis(50));
|
||||||
|
}
|
||||||
|
assert_eq!(unsafe { GetForegroundWindow() }, window);
|
||||||
|
|
||||||
|
let selection = inspect_foreground_window(Duration::from_secs(30))
|
||||||
|
.expect("select the controlled foreground dialog");
|
||||||
|
assert_eq!(selection.summary().title, TEST_TITLE);
|
||||||
|
assert_eq!(selection.summary().process_id, std::process::id());
|
||||||
|
|
||||||
|
let text = read_standard_dialog_text(&selection, UiaReadLimits::default())
|
||||||
|
.expect("read the controlled dialog through UI Automation");
|
||||||
|
assert!(text.text.contains(TEST_TITLE));
|
||||||
|
assert!(text.text.contains(TEST_BODY));
|
||||||
|
assert_eq!(text.password_nodes_skipped, 0);
|
||||||
|
|
||||||
|
let capture = capture_selected_window(&selection, CaptureLimits::default())
|
||||||
|
.expect("capture the explicitly selected controlled dialog");
|
||||||
|
assert!(capture.width > 0);
|
||||||
|
assert!(capture.height > 0);
|
||||||
|
assert_eq!(&capture.png_bytes[..8], b"\x89PNG\r\n\x1a\n");
|
||||||
|
|
||||||
|
drop(guard);
|
||||||
|
dialog_thread.join().expect("close the controlled dialog");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
selection.validate(),
|
||||||
|
Err(ForegroundWindowError::WindowChanged)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
capture_selected_window(&selection, CaptureLimits::default()).unwrap_err(),
|
||||||
|
WindowCaptureError::Selection(ForegroundWindowError::WindowChanged)
|
||||||
|
);
|
||||||
|
}
|
||||||
27
src/App.test.tsx
普通文件
27
src/App.test.tsx
普通文件
|
|
@ -0,0 +1,27 @@
|
||||||
|
import { invoke } from "@tauri-apps/api/core";
|
||||||
|
import { render, screen } from "@testing-library/react";
|
||||||
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
import { App } from "./App";
|
||||||
|
|
||||||
|
vi.mock("@tauri-apps/api/core", () => ({
|
||||||
|
invoke: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe("App", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.mocked(invoke).mockResolvedValue({
|
||||||
|
appVersion: "0.1.0-alpha.0",
|
||||||
|
platform: "windows",
|
||||||
|
rustCore: "ready",
|
||||||
|
protocolVersion: "desktop-v1alpha1",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renders the verified Rust bootstrap status", async () => {
|
||||||
|
render(<App />);
|
||||||
|
|
||||||
|
expect(await screen.findByText("ready")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("desktop-v1alpha1")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
1
src/test/setup.ts
普通文件
1
src/test/setup.ts
普通文件
|
|
@ -0,0 +1 @@
|
||||||
|
import "@testing-library/jest-dom/vitest";
|
||||||
16
tests/e2e/bootstrap.spec.ts
普通文件
16
tests/e2e/bootstrap.spec.ts
普通文件
|
|
@ -0,0 +1,16 @@
|
||||||
|
import { expect, test } from "@playwright/test";
|
||||||
|
|
||||||
|
test("renders the bootstrap shell and safe browser fallback", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await page.goto("/");
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
page.getByRole("heading", { name: "AstrBot Desktop" }),
|
||||||
|
).toBeVisible();
|
||||||
|
await expect(page.getByText("desktop-v1alpha1")).toBeVisible();
|
||||||
|
await expect(
|
||||||
|
page.getByText("IPC unavailable:", { exact: false }),
|
||||||
|
).toBeVisible();
|
||||||
|
await expect(page.getByRole("button")).toBeEnabled();
|
||||||
|
});
|
||||||
正在加载…
添加表格
在新工单中引用