feat(p00): add Tauri desktop spike foundation

这个提交存在于:
YokiiroBW 2026-07-18 20:34:47 +08:00
父节点 0d12b942bf
当前提交 01607c69ff
共有 137 个文件被更改,包括 17274 次插入 和 0 次删除

1
.node-version 普通文件
查看文件

@ -0,0 +1 @@
24.17.0

6
.npmrc 普通文件
查看文件

@ -0,0 +1,6 @@
save-exact=true
strict-peer-dependencies=true
auto-install-peers=false
enable-global-virtual-store=false
node-linker=hoisted
package-import-method=copy

11
.prettierignore 普通文件
查看文件

@ -0,0 +1,11 @@
node_modules
dist
coverage
src-tauri/target
packages/*/dist
pnpm-lock.yaml
AGENTS.md
AstrBot_Desktop_Codex_Forgejo_Predevelopment_Workflow.md
docs/01_Architecture_Design.md
docs/02_Codex_Implementation_Tasks.md
docs/protocol/v1/schemas

6029
Cargo.lock 自动生成 普通文件

文件差异内容过多而无法显示 加载差异

46
Cargo.toml 普通文件
查看文件

@ -0,0 +1,46 @@
[workspace]
members = [
"src-tauri",
"crates/desktop-protocol",
"crates/mock-gateway",
]
resolver = "3"
[workspace.package]
version = "0.1.0-alpha.0"
edition = "2024"
rust-version = "1.97.1"
license = "MIT OR Apache-2.0"
[workspace.dependencies]
axum = "0.8.9"
clap = { version = "4.6.2", features = ["derive"] }
eventsource-stream = "0.2.3"
futures-util = "0.3.32"
png = "0.18.1"
quick-xml = "0.41.0"
regex = "1.13.1"
reqwest = { version = "0.13.4", default-features = false, features = ["json", "rustls", "stream"] }
rusqlite = { version = "0.40.1", features = ["bundled"] }
schemars = { version = "1.2.1", features = ["uuid1"] }
secrecy = "0.10.3"
serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.150"
sha2 = "0.11.0"
sysinfo = "0.39.6"
tauri = { version = "2.11.5", features = ["tray-icon"] }
tauri-build = "2.6.3"
tempfile = "3.27.0"
thiserror = "2.0.18"
time = { version = "0.3.53", features = ["formatting", "serde"] }
tokio = { version = "1.53.0", features = ["macros", "net", "rt-multi-thread", "sync", "time"] }
tokio-util = "0.7.18"
toml = "1.1.3"
tracing = "0.1.44"
tracing-subscriber = { version = "0.3.23", features = ["env-filter", "fmt"] }
ts-rs = { version = "12.0.1", features = ["uuid-impl"] }
url = "2.5.8"
uuid = { version = "1.24.0", features = ["serde", "v4"] }
windows = "0.61.3"
yaml-rust2 = "0.11.0"
zeroize = "1.9.0"

11
assets/app-icon.svg 普通文件
查看文件

@ -0,0 +1,11 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" role="img" aria-label="AstrBot Desktop">
<defs>
<linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stop-color="#7ab8ff"/>
<stop offset="1" stop-color="#3158d5"/>
</linearGradient>
</defs>
<rect width="512" height="512" rx="112" fill="#08111f"/>
<path d="M128 352 232 112h48l104 240h-64l-20-52h-88l-20 52h-64Zm104-108h48l-24-64-24 64Z" fill="url(#g)"/>
<circle cx="392" cy="120" r="36" fill="#8ee7d2"/>
</svg>

之后

宽度:  |  高度:  |  大小: 519 B

查看文件

@ -0,0 +1,22 @@
[package]
name = "desktop-protocol"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish = false
description = "Canonical AstrBot Desktop Gateway protocol types"
[features]
default = ["schema"]
schema = ["dep:schemars"]
[dependencies]
schemars = { workspace = true, optional = true }
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
[[example]]
name = "export_schemas"
required-features = ["schema"]

查看文件

@ -0,0 +1,80 @@
use std::{
collections::BTreeMap,
env,
error::Error,
fs,
path::{Path, PathBuf},
};
use desktop_protocol::{
ClientCapabilities, ConnectionProfile, ConnectionSlot, DiagnosticBundle, FileTransferPlan,
GatewayEvent, RawProtocolEnvelope, ServerCapabilities, ToolProposal, ToolResult,
};
use schemars::{JsonSchema, schema_for};
use serde_json::Value;
fn main() -> Result<(), Box<dyn Error>> {
let write = env::args().any(|arg| arg == "--write");
let output_dir =
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../docs/protocol/v1/schemas");
let schemas = generated_schemas()?;
if write {
fs::create_dir_all(&output_dir)?;
for (name, schema) in schemas {
let path = output_dir.join(name);
fs::write(
path,
format!("{}\n", serde_json::to_string_pretty(&schema)?),
)?;
}
return Ok(());
}
let mut failures = Vec::new();
for (name, expected) in schemas {
let path = output_dir.join(name);
match read_json(&path) {
Ok(actual) if actual == expected => {}
Ok(_) => failures.push(format!("{} is stale", path.display())),
Err(error) => failures.push(format!("{}: {error}", path.display())),
}
}
if failures.is_empty() {
Ok(())
} else {
Err(format!(
"protocol schema check failed; run with --write:\n{}",
failures.join("\n")
)
.into())
}
}
fn generated_schemas() -> Result<BTreeMap<&'static str, Value>, serde_json::Error> {
let mut output = BTreeMap::new();
insert::<ConnectionProfile>(&mut output, "connection-profile.schema.json")?;
insert::<ConnectionSlot>(&mut output, "connection-slot.schema.json")?;
insert::<ServerCapabilities>(&mut output, "server-capabilities.schema.json")?;
insert::<ClientCapabilities>(&mut output, "client-capabilities.schema.json")?;
insert::<RawProtocolEnvelope>(&mut output, "protocol-envelope.schema.json")?;
insert::<GatewayEvent>(&mut output, "gateway-event.schema.json")?;
insert::<ToolProposal>(&mut output, "tool-proposal.schema.json")?;
insert::<ToolResult>(&mut output, "tool-result.schema.json")?;
insert::<DiagnosticBundle>(&mut output, "diagnostic-bundle.schema.json")?;
insert::<FileTransferPlan>(&mut output, "file-transfer-plan.schema.json")?;
Ok(output)
}
fn insert<T: JsonSchema>(
output: &mut BTreeMap<&'static str, Value>,
name: &'static str,
) -> Result<(), serde_json::Error> {
output.insert(name, serde_json::to_value(schema_for!(T))?);
Ok(())
}
fn read_json(path: &Path) -> Result<Value, Box<dyn Error>> {
Ok(serde_json::from_str(&fs::read_to_string(path)?)?)
}

查看文件

@ -0,0 +1,32 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct CapabilityLimits {
pub max_event_bytes: u64,
pub max_message_bytes: u64,
pub replay_window_events: u32,
pub max_active_connections: u8,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ServerCapabilities {
pub protocol_versions: Vec<String>,
pub features: Vec<String>,
#[serde(default)]
pub local_action_tools: Vec<String>,
pub limits: CapabilityLimits,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ClientCapabilities {
pub protocol_version: String,
pub app_version: String,
pub platform: String,
pub features: Vec<String>,
}

查看文件

@ -0,0 +1,114 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum ActiveSlotKind {
Companion,
Operations,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum AstrBotProfileRole {
Companion,
Operations,
General,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum AuthenticationType {
DeviceToken,
ApiKey,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum ConnectionState {
Disconnected,
Connecting,
Authenticating,
Syncing,
Connected,
Reconnecting,
AuthExpired,
Incompatible,
ServerUnavailable,
Offline,
CertificateChanged,
FatalError,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ConnectionProfile {
pub id: String,
pub display_name: String,
pub role: AstrBotProfileRole,
pub base_url: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub event_stream_url: Option<String>,
pub authentication_type: AuthenticationType,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub credential_reference: Option<String>,
#[serde(default)]
pub allow_insecure_http: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pinned_certificate_fingerprint: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub auto_connect_slot: Option<ActiveSlotKind>,
#[serde(default)]
pub auto_connect: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub server_instance_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub server_version: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub protocol_version: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub local_tool_policy_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_connected_at: Option<String>,
pub created_at: String,
pub updated_at: String,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ConnectionSlot {
pub slot: ActiveSlotKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub profile_id: Option<String>,
pub state: ConnectionState,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub server_instance_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub active_conversation_id: Option<String>,
#[serde(default)]
pub unread_count: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_event_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_connected_at: Option<String>,
}
impl ConnectionSlot {
pub fn empty(slot: ActiveSlotKind) -> Self {
Self {
slot,
profile_id: None,
state: ConnectionState::Disconnected,
server_instance_id: None,
active_conversation_id: None,
unread_count: 0,
last_event_id: None,
last_connected_at: None,
}
}
}

查看文件

@ -0,0 +1,65 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum DiagnosticEntryKind {
System,
Window,
Process,
EventLog,
Network,
Port,
Service,
LogTail,
Configuration,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RedactionSummary {
pub category: String,
pub count: u32,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DiagnosticEntry {
pub entry_id: String,
pub kind: DiagnosticEntryKind,
pub source_label: String,
pub summary: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub content: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mime_type: Option<String>,
#[serde(default)]
pub truncated: bool,
#[serde(default)]
pub redactions: Vec<RedactionSummary>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DiagnosticAttachmentReference {
pub attachment_id: String,
pub mime_type: String,
pub size_bytes: u64,
pub sha256: String,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DiagnosticBundle {
pub bundle_id: String,
pub generated_at: String,
pub scope: Vec<String>,
pub entries: Vec<DiagnosticEntry>,
#[serde(default)]
pub attachments: Vec<DiagnosticAttachmentReference>,
pub total_bytes: u64,
}

查看文件

@ -0,0 +1,313 @@
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use serde_json::Value;
use thiserror::Error;
use crate::{ActiveSlotKind, PROTOCOL_VERSION, ServerCapabilities, ToolProposal};
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct EventMetadata {
pub protocol_version: String,
pub event_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub request_id: Option<String>,
/// Untrusted server hint. Local routing must use `BoundGatewayEvent.profile_id`.
#[serde(rename = "profileId", default, skip_serializing_if = "Option::is_none")]
pub server_profile_hint: Option<String>,
pub server_instance_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub conversation_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub session_id: Option<String>,
pub timestamp: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sequence: Option<u64>,
}
impl EventMetadata {
pub fn new(
event_id: impl Into<String>,
server_instance_id: impl Into<String>,
timestamp: impl Into<String>,
sequence: u64,
) -> Self {
Self {
protocol_version: PROTOCOL_VERSION.to_owned(),
event_id: event_id.into(),
request_id: None,
server_profile_hint: None,
server_instance_id: server_instance_id.into(),
conversation_id: None,
message_id: None,
session_id: None,
timestamp: timestamp.into(),
sequence: Some(sequence),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct HeartbeatPayload {
pub interval_ms: u64,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct MessageDeltaPayload {
pub delta: String,
pub index: u32,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum FinishReason {
Stop,
Cancelled,
Error,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct MessageCompletedPayload {
pub finish_reason: FinishReason,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub content: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ProactiveMessagePayload {
pub content: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub notification_title: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AgentStatusPayload {
pub state: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub detail: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct GatewayErrorPayload {
pub code: String,
pub message: String,
pub retryable: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "eventType", content = "payload")]
pub enum GatewayEventBody {
#[serde(rename = "system.heartbeat")]
Heartbeat(HeartbeatPayload),
#[serde(rename = "message.delta")]
MessageDelta(MessageDeltaPayload),
#[serde(rename = "message.completed")]
MessageCompleted(MessageCompletedPayload),
#[serde(rename = "message.proactive")]
ProactiveMessage(ProactiveMessagePayload),
#[serde(rename = "agent.status")]
AgentStatus(AgentStatusPayload),
#[serde(rename = "tool.proposal")]
ToolProposal(ToolProposal),
#[serde(rename = "capabilities.changed")]
CapabilitiesChanged(ServerCapabilities),
#[serde(rename = "error")]
Error(GatewayErrorPayload),
}
impl GatewayEventBody {
pub fn event_type(&self) -> &'static str {
match self {
Self::Heartbeat(_) => "system.heartbeat",
Self::MessageDelta(_) => "message.delta",
Self::MessageCompleted(_) => "message.completed",
Self::ProactiveMessage(_) => "message.proactive",
Self::AgentStatus(_) => "agent.status",
Self::ToolProposal(_) => "tool.proposal",
Self::CapabilitiesChanged(_) => "capabilities.changed",
Self::Error(_) => "error",
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct GatewayEvent {
#[serde(flatten)]
pub metadata: EventMetadata,
#[serde(flatten)]
pub body: GatewayEventBody,
}
impl GatewayEvent {
pub fn new(metadata: EventMetadata, body: GatewayEventBody) -> Self {
Self { metadata, body }
}
pub fn event_type(&self) -> &'static str {
self.body.event_type()
}
}
/// Two-stage wire representation used before a payload type is trusted.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ProtocolEnvelope {
pub protocol_version: String,
pub event_type: String,
pub event_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub request_id: Option<String>,
/// This value is never used as the local profile binding.
#[serde(rename = "profileId", default, skip_serializing_if = "Option::is_none")]
pub server_profile_hint: Option<String>,
pub server_instance_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub conversation_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub session_id: Option<String>,
pub timestamp: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sequence: Option<u64>,
pub payload: Value,
}
/// Alias used by connection code to emphasize that the envelope remains
/// untrusted until it is decoded and locally bound.
pub type RawProtocolEnvelope = ProtocolEnvelope;
impl TryFrom<ProtocolEnvelope> for GatewayEvent {
type Error = ProtocolError;
fn try_from(raw: RawProtocolEnvelope) -> Result<Self, Self::Error> {
if raw.protocol_version != PROTOCOL_VERSION {
return Err(ProtocolError::IncompatibleProtocolVersion {
received: raw.protocol_version,
});
}
require_non_empty("eventId", &raw.event_id)?;
require_non_empty("serverInstanceId", &raw.server_instance_id)?;
require_non_empty("timestamp", &raw.timestamp)?;
let event_type = raw.event_type;
let body = match event_type.as_str() {
"system.heartbeat" => GatewayEventBody::Heartbeat(decode(&event_type, raw.payload)?),
"message.delta" => GatewayEventBody::MessageDelta(decode(&event_type, raw.payload)?),
"message.completed" => {
GatewayEventBody::MessageCompleted(decode(&event_type, raw.payload)?)
}
"message.proactive" => {
GatewayEventBody::ProactiveMessage(decode(&event_type, raw.payload)?)
}
"agent.status" => GatewayEventBody::AgentStatus(decode(&event_type, raw.payload)?),
"tool.proposal" => GatewayEventBody::ToolProposal(decode(&event_type, raw.payload)?),
"capabilities.changed" => {
GatewayEventBody::CapabilitiesChanged(decode(&event_type, raw.payload)?)
}
"error" => GatewayEventBody::Error(decode(&event_type, raw.payload)?),
_ => return Err(ProtocolError::UnsupportedEventType { event_type }),
};
Ok(Self {
metadata: EventMetadata {
protocol_version: PROTOCOL_VERSION.to_owned(),
event_id: raw.event_id,
request_id: raw.request_id,
server_profile_hint: raw.server_profile_hint,
server_instance_id: raw.server_instance_id,
conversation_id: raw.conversation_id,
message_id: raw.message_id,
session_id: raw.session_id,
timestamp: raw.timestamp,
sequence: raw.sequence,
},
body,
})
}
}
fn decode<T: DeserializeOwned>(event_type: &str, payload: Value) -> Result<T, ProtocolError> {
serde_json::from_value(payload).map_err(|source| ProtocolError::InvalidPayload {
event_type: event_type.to_owned(),
source,
})
}
fn require_non_empty(field: &'static str, value: &str) -> Result<(), ProtocolError> {
if value.trim().is_empty() {
Err(ProtocolError::EmptyRequiredField { field })
} else {
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct BoundGatewayEvent {
/// Trusted local profile binding supplied by the connection object.
pub profile_id: String,
pub slot: ActiveSlotKind,
pub event: GatewayEvent,
}
impl BoundGatewayEvent {
pub fn bind(
raw: RawProtocolEnvelope,
local_profile_id: impl Into<String>,
slot: ActiveSlotKind,
expected_server_instance_id: &str,
) -> Result<Self, ProtocolError> {
let local_profile_id = local_profile_id.into();
require_non_empty("localProfileId", &local_profile_id)?;
let event = GatewayEvent::try_from(raw)?;
if event.metadata.server_instance_id != expected_server_instance_id {
return Err(ProtocolError::ServerInstanceMismatch {
expected: expected_server_instance_id.to_owned(),
received: event.metadata.server_instance_id,
});
}
Ok(Self {
profile_id: local_profile_id,
slot,
event,
})
}
}
#[derive(Debug, Error)]
pub enum ProtocolError {
#[error("unsupported protocol version: {received}")]
IncompatibleProtocolVersion { received: String },
#[error("required field {field} is empty")]
EmptyRequiredField { field: &'static str },
#[error("unsupported gateway event type: {event_type}")]
UnsupportedEventType { event_type: String },
#[error("invalid payload for {event_type}: {source}")]
InvalidPayload {
event_type: String,
#[source]
source: serde_json::Error,
},
#[error("server instance mismatch: expected {expected}, received {received}")]
ServerInstanceMismatch { expected: String, received: String },
}

查看文件

@ -0,0 +1,50 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum ConflictAction {
Copy,
Rename,
Skip,
Ask,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum SourceCleanupPolicy {
Keep,
Recycle,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct FileTransferPlanItem {
/// Opaque, short-lived mapping held by the local client. Never a raw path.
pub source_path_token: String,
/// Display-only value for local review; never used as an execution path.
pub display_source_path: String,
pub destination_relative_path: String,
pub size_bytes: u64,
pub category_reason: String,
pub conflict_action: ConflictAction,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct FileTransferPlan {
pub plan_id: String,
/// Locally bound profile. A remote value must never select the executor.
pub profile_id: String,
pub source_selection_id: String,
pub nas_target_id: String,
pub items: Vec<FileTransferPlanItem>,
pub total_bytes: u64,
pub conflict_count: u32,
pub warning_count: u32,
pub source_cleanup_policy: SourceCleanupPolicy,
pub expires_at: String,
}

查看文件

@ -0,0 +1,89 @@
use serde::{Deserialize, Serialize};
use crate::ClientCapabilities;
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct HealthResponse {
pub status: String,
pub protocol_version: String,
pub server_instance_id: String,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ServerInfo {
pub server_instance_id: String,
pub display_name: String,
pub server_version: String,
pub protocol_version: String,
pub server_time: String,
}
/// Contains secret material and intentionally does not derive `Debug`.
#[derive(Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AuthLoginRequest {
pub client_id: String,
pub device_id: String,
pub credential: String,
pub capabilities: ClientCapabilities,
}
/// Contains secret material and intentionally does not derive `Debug`.
#[derive(Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AuthLoginResponse {
pub access_token: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub refresh_token: Option<String>,
pub expires_in_seconds: u64,
}
/// Contains secret material and intentionally does not derive `Debug`.
#[derive(Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AuthRefreshRequest {
pub refresh_token: String,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SendMessageRequest {
pub conversation_id: String,
pub content: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub client_request_id: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AcceptedMessage {
pub request_id: String,
pub message_id: String,
pub accepted_at: String,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct EventAcknowledgement {
pub event_id: String,
pub acknowledged: bool,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct GatewayErrorResponse {
pub code: String,
pub message: String,
pub retryable: bool,
}

查看文件

@ -0,0 +1,26 @@
//! Canonical protocol types for the stable AstrBot Desktop Gateway boundary.
//!
//! Types in this crate deliberately separate untrusted wire data from locally
//! bound desktop events. A server supplied `profileId` is never authoritative.
mod capabilities;
mod connection;
mod diagnostics;
mod envelope;
mod file_transfer;
mod http;
mod tools;
pub use capabilities::*;
pub use connection::*;
pub use diagnostics::*;
pub use envelope::*;
pub use file_transfer::*;
pub use http::*;
pub use tools::*;
/// Protocol version implemented by the P00 desktop contract.
pub const PROTOCOL_VERSION: &str = "desktop-v1alpha1";
/// Stable REST prefix for this protocol major version.
pub const API_PREFIX: &str = "/desktop/v1";

查看文件

@ -0,0 +1,80 @@
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum RiskLevel {
Read,
ReversibleWrite,
Destructive,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ToolProposal {
pub action_id: String,
pub tool_name: String,
pub reason: String,
pub risk_level: RiskLevel,
pub arguments: Value,
pub requested_at: String,
pub expires_at: String,
pub requires_approval: bool,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum ToolResultStatus {
Rejected,
Completed,
Failed,
Cancelled,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ToolResult {
pub action_id: String,
pub status: ToolResultStatus,
pub summary: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub result: Option<Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error_code: Option<String>,
pub completed_at: String,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum LocalActionDecisionKind {
Accepted,
Rejected,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct LocalActionDecision {
pub action_id: String,
pub decision: LocalActionDecisionKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
pub decided_at: String,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct LocalActionProgress {
pub action_id: String,
pub phase: String,
pub completed_units: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub total_units: Option<u64>,
pub updated_at: String,
}

查看文件

@ -0,0 +1,22 @@
[package]
name = "mock-gateway"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish = false
description = "Deterministic loopback-only AstrBot Desktop Gateway mock"
[dependencies]
async-stream = "0.3"
axum.workspace = true
clap.workspace = true
desktop-protocol = { path = "../desktop-protocol" }
serde_json.workspace = true
thiserror.workspace = true
tokio = { workspace = true, features = ["signal"] }
tokio-util = { workspace = true, features = ["rt"] }
uuid.workspace = true
[dev-dependencies]
reqwest.workspace = true

查看文件

@ -0,0 +1,73 @@
use std::{
net::{IpAddr, Ipv4Addr, SocketAddr},
time::Duration,
};
use clap::ValueEnum;
#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
pub enum MockInstanceKind {
Companion,
Operations,
}
impl MockInstanceKind {
pub fn slug(self) -> &'static str {
match self {
Self::Companion => "companion",
Self::Operations => "operations",
}
}
pub fn display_name(self) -> &'static str {
match self {
Self::Companion => "Mock Companion",
Self::Operations => "Mock Operations",
}
}
pub fn server_instance_id(self) -> String {
format!("mock-{}-1", self.slug())
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
pub enum MockScenario {
Steady,
DisconnectOnce,
DuplicateEvents,
AuthReject,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AuthMode {
Accept,
Reject,
}
#[derive(Clone, Debug)]
pub struct MockGatewayConfig {
pub instance: MockInstanceKind,
pub bind_addr: SocketAddr,
pub scenario: MockScenario,
pub heartbeat_interval: Option<Duration>,
pub replay_capacity: usize,
}
impl MockGatewayConfig {
pub fn new(instance: MockInstanceKind, port: u16) -> Self {
Self {
instance,
bind_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port),
scenario: MockScenario::Steady,
heartbeat_interval: Some(Duration::from_secs(1)),
replay_capacity: 256,
}
}
pub fn for_test(instance: MockInstanceKind) -> Self {
let mut config = Self::new(instance, 0);
config.heartbeat_interval = None;
config
}
}

查看文件

@ -0,0 +1,240 @@
mod config;
mod routes;
mod state;
use std::{io, net::SocketAddr, sync::Arc};
pub use config::{AuthMode, MockGatewayConfig, MockInstanceKind, MockScenario};
use desktop_protocol::{
GatewayEvent, GatewayEventBody, HeartbeatPayload, ProactiveMessagePayload, RiskLevel,
ToolProposal,
};
use state::AppState;
use thiserror::Error;
use tokio::{net::TcpListener, sync::Mutex, task::JoinHandle};
use tokio_util::sync::CancellationToken;
#[derive(Clone)]
pub struct MockGatewayHandle {
inner: Arc<HandleInner>,
}
struct HandleInner {
state: Arc<AppState>,
address: SocketAddr,
shutdown: CancellationToken,
server_task: Mutex<Option<JoinHandle<Result<(), io::Error>>>>,
scenario_task: Mutex<Option<JoinHandle<()>>>,
}
impl MockGatewayHandle {
pub fn base_url(&self) -> String {
format!("http://{}", self.inner.address)
}
pub fn server_instance_id(&self) -> &str {
&self.inner.state.server_instance_id
}
pub async fn emit_event(&self, event: GatewayEvent) -> Result<(), MockGatewayError> {
if event.metadata.server_instance_id != self.server_instance_id() {
return Err(MockGatewayError::EventServerInstanceMismatch {
expected: self.server_instance_id().to_owned(),
received: event.metadata.server_instance_id,
});
}
self.inner.state.publish(event).await;
Ok(())
}
pub async fn emit_body(&self, body: GatewayEventBody) -> GatewayEvent {
let event = self.inner.state.create_event(body, None, None, None);
self.inner.state.publish(event.clone()).await;
event
}
pub async fn emit_proactive_message(&self) -> GatewayEvent {
self.emit_body(GatewayEventBody::ProactiveMessage(
ProactiveMessagePayload {
content: "Deterministic proactive mock message".to_owned(),
notification_title: Some(self.inner.state.instance.display_name().to_owned()),
},
))
.await
}
pub async fn emit_tool_proposal(&self) -> GatewayEvent {
self.emit_body(GatewayEventBody::ToolProposal(ToolProposal {
action_id: "mock-action-event-log-1".to_owned(),
tool_name: "query_recent_event_logs".to_owned(),
reason: "Inspect a bounded set of recent Application events".to_owned(),
risk_level: RiskLevel::Read,
arguments: serde_json::json!({
"provider": "Application",
"sinceMinutes": 15,
"maxEntries": 20
}),
requested_at: state::FIXED_TIMESTAMP.to_owned(),
expires_at: "2030-01-01T00:05:00Z".to_owned(),
requires_approval: true,
}))
.await
}
pub fn disconnect_streams(&self) {
self.inner.state.disconnect_streams();
}
pub async fn replay_event(&self, event_id: &str) -> bool {
self.inner.state.replay_event(event_id).await
}
pub fn set_auth_mode(&self, mode: AuthMode) {
self.inner.state.set_auth_mode(mode);
}
pub async fn acknowledged_event_ids(&self) -> Vec<String> {
self.inner.state.acknowledged_event_ids().await
}
pub async fn shutdown(&self) -> Result<(), MockGatewayError> {
self.inner.shutdown.cancel();
if let Some(task) = self.inner.scenario_task.lock().await.take() {
task.await?;
}
if let Some(task) = self.inner.server_task.lock().await.take() {
task.await??;
}
Ok(())
}
}
pub async fn spawn_mock_gateway(
config: MockGatewayConfig,
) -> Result<MockGatewayHandle, MockGatewayError> {
if !config.bind_addr.ip().is_loopback() {
return Err(MockGatewayError::NonLoopbackBind(config.bind_addr));
}
let listener = TcpListener::bind(config.bind_addr).await?;
let address = listener.local_addr()?;
let state = Arc::new(AppState::new(&config));
let router = routes::router(state.clone());
let shutdown = CancellationToken::new();
let server_shutdown = shutdown.clone();
let server_task = tokio::spawn(async move {
axum::serve(listener, router)
.with_graceful_shutdown(server_shutdown.cancelled_owned())
.await
});
let scenario_task = config.heartbeat_interval.map(|interval| {
let task_state = state.clone();
let task_shutdown = shutdown.clone();
let scenario = config.scenario;
tokio::spawn(async move {
run_scenario(task_state, scenario, interval, task_shutdown).await;
})
});
Ok(MockGatewayHandle {
inner: Arc::new(HandleInner {
state,
address,
shutdown,
server_task: Mutex::new(Some(server_task)),
scenario_task: Mutex::new(scenario_task),
}),
})
}
async fn run_scenario(
state: Arc<AppState>,
scenario: MockScenario,
interval: std::time::Duration,
shutdown: CancellationToken,
) {
if scenario == MockScenario::AuthReject {
state.set_auth_mode(AuthMode::Reject);
}
let mut ticker = tokio::time::interval(interval);
let mut ticks = 0_u64;
loop {
tokio::select! {
_ = shutdown.cancelled() => break,
_ = ticker.tick() => {
ticks += 1;
let heartbeat = state.create_event(
GatewayEventBody::Heartbeat(HeartbeatPayload {
interval_ms: interval.as_millis().try_into().unwrap_or(u64::MAX),
}),
None,
None,
None,
);
state.publish(heartbeat.clone()).await;
if ticks == 2 {
match state.instance {
MockInstanceKind::Companion => {
let event = state.create_event(
GatewayEventBody::ProactiveMessage(ProactiveMessagePayload {
content: "Deterministic proactive mock message".to_owned(),
notification_title: Some("Mock Companion".to_owned()),
}),
None,
Some("mock-companion-conversation".to_owned()),
None,
);
state.publish(event).await;
}
MockInstanceKind::Operations => {
let event = state.create_event(
GatewayEventBody::ToolProposal(ToolProposal {
action_id: "mock-action-event-log-1".to_owned(),
tool_name: "query_recent_event_logs".to_owned(),
reason: "Inspect a bounded set of recent Application events".to_owned(),
risk_level: RiskLevel::Read,
arguments: serde_json::json!({
"provider": "Application",
"sinceMinutes": 15,
"maxEntries": 20
}),
requested_at: state::FIXED_TIMESTAMP.to_owned(),
expires_at: "2030-01-01T00:05:00Z".to_owned(),
requires_approval: true,
}),
None,
Some("mock-operations-conversation".to_owned()),
None,
);
state.publish(event).await;
}
}
}
match scenario {
MockScenario::DisconnectOnce if ticks == 3 => state.disconnect_streams(),
MockScenario::DuplicateEvents if ticks.is_multiple_of(3) => {
state.broadcast_duplicate(&heartbeat);
}
_ => {}
}
}
}
}
}
#[derive(Debug, Error)]
pub enum MockGatewayError {
#[error("mock gateway refuses non-loopback bind address {0}")]
NonLoopbackBind(SocketAddr),
#[error("event server instance mismatch: expected {expected}, received {received}")]
EventServerInstanceMismatch { expected: String, received: String },
#[error(transparent)]
Io(#[from] io::Error),
#[error(transparent)]
Join(#[from] tokio::task::JoinError),
}

查看文件

@ -0,0 +1,36 @@
use std::time::Duration;
use clap::Parser;
use mock_gateway::{MockGatewayConfig, MockInstanceKind, MockScenario, spawn_mock_gateway};
#[derive(Debug, Parser)]
#[command(name = "mock-gateway")]
#[command(about = "Loopback-only deterministic AstrBot Desktop Gateway mock")]
struct Args {
#[arg(long, value_enum)]
instance: MockInstanceKind,
#[arg(long)]
port: u16,
#[arg(long, value_enum, default_value = "steady")]
scenario: MockScenario,
#[arg(long, default_value_t = 1_000)]
heartbeat_ms: u64,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let args = Args::parse();
let mut config = MockGatewayConfig::new(args.instance, args.port);
config.scenario = args.scenario;
config.heartbeat_interval = Some(Duration::from_millis(args.heartbeat_ms.max(1)));
let gateway = spawn_mock_gateway(config).await?;
println!(
"{} listening at {}",
gateway.server_instance_id(),
gateway.base_url()
);
tokio::signal::ctrl_c().await?;
gateway.shutdown().await?;
Ok(())
}

查看文件

@ -0,0 +1,375 @@
use std::{convert::Infallible, sync::Arc, time::Duration};
use axum::{
Json, Router,
extract::{Path, State},
http::{HeaderMap, StatusCode, header::AUTHORIZATION},
response::{
IntoResponse, Response, Sse,
sse::{Event, KeepAlive},
},
routing::{get, post},
};
use desktop_protocol::{
AuthLoginRequest, AuthLoginResponse, AuthRefreshRequest, EventAcknowledgement, FinishReason,
GatewayErrorResponse, GatewayEvent, GatewayEventBody, HealthResponse, LocalActionDecision,
LocalActionDecisionKind, LocalActionProgress, MessageCompletedPayload, MessageDeltaPayload,
PROTOCOL_VERSION, SendMessageRequest, ServerCapabilities, ServerInfo, ToolResult,
};
use tokio::sync::broadcast::error::RecvError;
use crate::state::{AppState, FIXED_TIMESTAMP};
pub(crate) fn router(state: Arc<AppState>) -> Router {
Router::new()
.route("/desktop/v1/health", get(health))
.route("/desktop/v1/server-info", get(server_info))
.route("/desktop/v1/capabilities", get(capabilities))
.route("/desktop/v1/auth/login", post(auth_login))
.route("/desktop/v1/auth/refresh", post(auth_refresh))
.route("/desktop/v1/messages", post(send_message))
.route("/desktop/v1/events/stream", get(event_stream))
.route("/desktop/v1/events/{event_id}/ack", post(acknowledge_event))
.route(
"/desktop/v1/local-actions/{action_id}/accepted",
post(local_action_accepted),
)
.route(
"/desktop/v1/local-actions/{action_id}/rejected",
post(local_action_rejected),
)
.route(
"/desktop/v1/local-actions/{action_id}/progress",
post(local_action_progress),
)
.route(
"/desktop/v1/local-actions/{action_id}/result",
post(local_action_result),
)
.with_state(state)
}
async fn health(State(state): State<Arc<AppState>>) -> Json<HealthResponse> {
Json(HealthResponse {
status: "ok".to_owned(),
protocol_version: PROTOCOL_VERSION.to_owned(),
server_instance_id: state.server_instance_id.clone(),
})
}
async fn server_info(State(state): State<Arc<AppState>>) -> Json<ServerInfo> {
Json(ServerInfo {
server_instance_id: state.server_instance_id.clone(),
display_name: state.display_name.clone(),
server_version: "0.1.0-mock".to_owned(),
protocol_version: PROTOCOL_VERSION.to_owned(),
server_time: FIXED_TIMESTAMP.to_owned(),
})
}
async fn capabilities(State(state): State<Arc<AppState>>) -> Json<ServerCapabilities> {
Json(state.capabilities.clone())
}
async fn auth_login(
State(state): State<Arc<AppState>>,
Json(request): Json<AuthLoginRequest>,
) -> Response {
if state.auth_is_rejected()
|| request.client_id.trim().is_empty()
|| request.device_id.trim().is_empty()
|| request.credential.trim().is_empty()
{
return error_response(
StatusCode::UNAUTHORIZED,
"auth_rejected",
"mock authentication rejected",
false,
);
}
let (access_token, refresh_token) = state.issue_tokens().await;
Json(AuthLoginResponse {
access_token,
refresh_token: Some(refresh_token),
expires_in_seconds: 300,
})
.into_response()
}
async fn auth_refresh(
State(state): State<Arc<AppState>>,
Json(request): Json<AuthRefreshRequest>,
) -> Response {
let Some((access_token, refresh_token)) = state.refresh_tokens(&request.refresh_token).await
else {
return error_response(
StatusCode::UNAUTHORIZED,
"refresh_rejected",
"mock refresh rejected",
false,
);
};
Json(AuthLoginResponse {
access_token,
refresh_token: Some(refresh_token),
expires_in_seconds: 300,
})
.into_response()
}
async fn send_message(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
Json(request): Json<SendMessageRequest>,
) -> Response {
if let Err(response) = require_auth(&state, &headers).await {
return response;
}
if request.conversation_id.trim().is_empty() || request.content.trim().is_empty() {
return error_response(
StatusCode::BAD_REQUEST,
"invalid_message",
"conversationId and content are required",
false,
);
}
let accepted = state.accept_message();
let reply = match state.instance {
crate::MockInstanceKind::Companion => "Deterministic companion response",
crate::MockInstanceKind::Operations => "Deterministic operations response",
};
let delta = state.create_event(
GatewayEventBody::MessageDelta(MessageDeltaPayload {
delta: reply.to_owned(),
index: 0,
}),
Some(accepted.request_id.clone()),
Some(request.conversation_id.clone()),
Some(accepted.message_id.clone()),
);
state.publish(delta).await;
let completed = state.create_event(
GatewayEventBody::MessageCompleted(MessageCompletedPayload {
finish_reason: FinishReason::Stop,
content: Some(reply.to_owned()),
}),
Some(accepted.request_id.clone()),
Some(request.conversation_id),
Some(accepted.message_id.clone()),
);
state.publish(completed).await;
(StatusCode::ACCEPTED, Json(accepted)).into_response()
}
async fn event_stream(State(state): State<Arc<AppState>>, headers: HeaderMap) -> Response {
if let Err(response) = require_auth(&state, &headers).await {
return response;
}
let last_event_id = headers
.get("last-event-id")
.and_then(|value| value.to_str().ok())
.map(str::to_owned);
let mut events = state.subscribe_events();
let mut disconnects = state.subscribe_disconnects();
let replay = state.events_after(last_event_id.as_deref()).await;
let stream = async_stream::stream! {
yield Ok::<Event, Infallible>(Event::default().comment("connected"));
for event in replay {
if let Some(frame) = to_sse_event(&event) {
yield Ok::<Event, Infallible>(frame);
}
}
loop {
tokio::select! {
result = disconnects.changed() => {
if result.is_ok() {
break;
}
}
result = events.recv() => {
match result {
Ok(event) => {
if let Some(frame) = to_sse_event(&event) {
yield Ok::<Event, Infallible>(frame);
}
}
Err(RecvError::Lagged(_)) => continue,
Err(RecvError::Closed) => break,
}
}
}
}
};
Sse::new(stream)
.keep_alive(
KeepAlive::new()
.interval(Duration::from_secs(15))
.text("keep-alive"),
)
.into_response()
}
async fn acknowledge_event(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
Path(event_id): Path<String>,
) -> Response {
if let Err(response) = require_auth(&state, &headers).await {
return response;
}
if event_id.trim().is_empty() {
return error_response(
StatusCode::BAD_REQUEST,
"invalid_event_id",
"event id is required",
false,
);
}
state.acknowledge(event_id.clone()).await;
Json(EventAcknowledgement {
event_id,
acknowledged: true,
})
.into_response()
}
async fn local_action_accepted(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
Path(action_id): Path<String>,
Json(decision): Json<LocalActionDecision>,
) -> Response {
validate_decision(
&state,
&headers,
&action_id,
&decision,
LocalActionDecisionKind::Accepted,
)
.await
}
async fn local_action_rejected(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
Path(action_id): Path<String>,
Json(decision): Json<LocalActionDecision>,
) -> Response {
validate_decision(
&state,
&headers,
&action_id,
&decision,
LocalActionDecisionKind::Rejected,
)
.await
}
async fn validate_decision(
state: &AppState,
headers: &HeaderMap,
action_id: &str,
decision: &LocalActionDecision,
expected: LocalActionDecisionKind,
) -> Response {
if let Err(response) = require_auth(state, headers).await {
return response;
}
if decision.action_id != action_id || decision.decision != expected {
return error_response(
StatusCode::BAD_REQUEST,
"invalid_action_decision",
"path and decision payload do not match",
false,
);
}
StatusCode::NO_CONTENT.into_response()
}
async fn local_action_progress(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
Path(action_id): Path<String>,
Json(progress): Json<LocalActionProgress>,
) -> Response {
if let Err(response) = require_auth(&state, &headers).await {
return response;
}
if progress.action_id != action_id {
return error_response(
StatusCode::BAD_REQUEST,
"invalid_action_progress",
"path and progress payload do not match",
false,
);
}
StatusCode::NO_CONTENT.into_response()
}
async fn local_action_result(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
Path(action_id): Path<String>,
Json(result): Json<ToolResult>,
) -> Response {
if let Err(response) = require_auth(&state, &headers).await {
return response;
}
if result.action_id != action_id {
return error_response(
StatusCode::BAD_REQUEST,
"invalid_action_result",
"path and result payload do not match",
false,
);
}
StatusCode::NO_CONTENT.into_response()
}
async fn require_auth(state: &AppState, headers: &HeaderMap) -> Result<(), Response> {
let token = headers
.get(AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.strip_prefix("Bearer "))
.map(str::to_owned);
if state.is_authorized(token.as_deref()).await {
Ok(())
} else {
Err(error_response(
StatusCode::UNAUTHORIZED,
"unauthorized",
"valid bearer authentication is required",
false,
))
}
}
fn to_sse_event(event: &GatewayEvent) -> Option<Event> {
let data = serde_json::to_string(event).ok()?;
Some(
Event::default()
.id(event.metadata.event_id.clone())
.event(event.event_type())
.data(data),
)
}
fn error_response(status: StatusCode, code: &str, message: &str, retryable: bool) -> Response {
(
status,
Json(GatewayErrorResponse {
code: code.to_owned(),
message: message.to_owned(),
retryable,
}),
)
.into_response()
}

查看文件

@ -0,0 +1,250 @@
use std::{
collections::{HashSet, VecDeque},
sync::atomic::{AtomicU8, AtomicU64, Ordering},
};
use desktop_protocol::{
AcceptedMessage, CapabilityLimits, EventMetadata, GatewayEvent, GatewayEventBody,
PROTOCOL_VERSION, ServerCapabilities,
};
use tokio::sync::{Mutex, RwLock, broadcast, watch};
use uuid::Uuid;
use crate::{AuthMode, MockGatewayConfig, MockInstanceKind, MockScenario};
pub(crate) const FIXED_TIMESTAMP: &str = "2030-01-01T00:00:00Z";
struct SessionTokens {
access: String,
refresh: String,
}
pub(crate) struct AppState {
pub(crate) instance: MockInstanceKind,
pub(crate) server_instance_id: String,
pub(crate) display_name: String,
pub(crate) capabilities: ServerCapabilities,
replay_capacity: usize,
sequence: AtomicU64,
request_sequence: AtomicU64,
auth_mode: AtomicU8,
tokens: RwLock<Option<SessionTokens>>,
event_sender: broadcast::Sender<GatewayEvent>,
disconnect_sender: watch::Sender<u64>,
replay_buffer: Mutex<VecDeque<GatewayEvent>>,
acknowledged_event_ids: Mutex<HashSet<String>>,
}
impl AppState {
pub(crate) fn new(config: &MockGatewayConfig) -> Self {
let (event_sender, _) = broadcast::channel(config.replay_capacity.max(16));
let (disconnect_sender, _) = watch::channel(0_u64);
let initial_auth_mode = if config.scenario == MockScenario::AuthReject {
AuthMode::Reject
} else {
AuthMode::Accept
};
Self {
instance: config.instance,
server_instance_id: config.instance.server_instance_id(),
display_name: config.instance.display_name().to_owned(),
capabilities: capabilities_for(config.instance),
replay_capacity: config.replay_capacity.max(1),
sequence: AtomicU64::new(0),
request_sequence: AtomicU64::new(0),
auth_mode: AtomicU8::new(auth_mode_value(initial_auth_mode)),
tokens: RwLock::new(None),
event_sender,
disconnect_sender,
replay_buffer: Mutex::new(VecDeque::with_capacity(config.replay_capacity.max(1))),
acknowledged_event_ids: Mutex::new(HashSet::new()),
}
}
pub(crate) fn set_auth_mode(&self, mode: AuthMode) {
self.auth_mode
.store(auth_mode_value(mode), Ordering::Release);
}
pub(crate) fn auth_is_rejected(&self) -> bool {
self.auth_mode.load(Ordering::Acquire) == auth_mode_value(AuthMode::Reject)
}
pub(crate) async fn issue_tokens(&self) -> (String, String) {
let tokens = SessionTokens {
access: format!("mock-session-{}", Uuid::new_v4()),
refresh: format!("mock-refresh-{}", Uuid::new_v4()),
};
let response = (tokens.access.clone(), tokens.refresh.clone());
*self.tokens.write().await = Some(tokens);
response
}
pub(crate) async fn refresh_tokens(&self, presented_refresh: &str) -> Option<(String, String)> {
let matches = self
.tokens
.read()
.await
.as_ref()
.is_some_and(|tokens| tokens.refresh == presented_refresh);
if matches && !self.auth_is_rejected() {
Some(self.issue_tokens().await)
} else {
None
}
}
pub(crate) async fn is_authorized(&self, presented_access: Option<&str>) -> bool {
if self.auth_is_rejected() {
return false;
}
let Some(presented_access) = presented_access else {
return false;
};
self.tokens
.read()
.await
.as_ref()
.is_some_and(|tokens| tokens.access == presented_access)
}
pub(crate) fn create_event(
&self,
body: GatewayEventBody,
request_id: Option<String>,
conversation_id: Option<String>,
message_id: Option<String>,
) -> GatewayEvent {
let sequence = self.sequence.fetch_add(1, Ordering::Relaxed) + 1;
let mut metadata = EventMetadata::new(
format!("{}-event-{sequence:06}", self.instance.slug()),
self.server_instance_id.clone(),
FIXED_TIMESTAMP,
sequence,
);
metadata.request_id = request_id;
metadata.conversation_id = conversation_id;
metadata.message_id = message_id;
GatewayEvent::new(metadata, body)
}
pub(crate) async fn publish(&self, event: GatewayEvent) {
let mut replay = self.replay_buffer.lock().await;
replay.push_back(event.clone());
while replay.len() > self.replay_capacity {
replay.pop_front();
}
drop(replay);
let _ = self.event_sender.send(event);
}
pub(crate) fn broadcast_duplicate(&self, event: &GatewayEvent) {
let _ = self.event_sender.send(event.clone());
}
pub(crate) async fn replay_event(&self, event_id: &str) -> bool {
let event = self
.replay_buffer
.lock()
.await
.iter()
.find(|event| event.metadata.event_id == event_id)
.cloned();
if let Some(event) = event {
self.broadcast_duplicate(&event);
true
} else {
false
}
}
pub(crate) async fn events_after(&self, last_event_id: Option<&str>) -> Vec<GatewayEvent> {
let Some(last_event_id) = last_event_id else {
return Vec::new();
};
let replay = self.replay_buffer.lock().await;
let Some(index) = replay
.iter()
.position(|event| event.metadata.event_id == last_event_id)
else {
return Vec::new();
};
replay.iter().skip(index + 1).cloned().collect()
}
pub(crate) fn subscribe_events(&self) -> broadcast::Receiver<GatewayEvent> {
self.event_sender.subscribe()
}
pub(crate) fn subscribe_disconnects(&self) -> watch::Receiver<u64> {
self.disconnect_sender.subscribe()
}
pub(crate) fn disconnect_streams(&self) {
let next = self.disconnect_sender.borrow().wrapping_add(1);
let _ = self.disconnect_sender.send(next);
}
pub(crate) async fn acknowledge(&self, event_id: String) {
self.acknowledged_event_ids.lock().await.insert(event_id);
}
pub(crate) async fn acknowledged_event_ids(&self) -> Vec<String> {
let mut values: Vec<_> = self
.acknowledged_event_ids
.lock()
.await
.iter()
.cloned()
.collect();
values.sort();
values
}
pub(crate) fn accept_message(&self) -> AcceptedMessage {
let sequence = self.request_sequence.fetch_add(1, Ordering::Relaxed) + 1;
AcceptedMessage {
request_id: format!("{}-request-{sequence:06}", self.instance.slug()),
message_id: format!("{}-message-{sequence:06}", self.instance.slug()),
accepted_at: FIXED_TIMESTAMP.to_owned(),
}
}
}
fn auth_mode_value(mode: AuthMode) -> u8 {
match mode {
AuthMode::Accept => 0,
AuthMode::Reject => 1,
}
}
fn capabilities_for(instance: MockInstanceKind) -> ServerCapabilities {
let mut features = vec![
"auth.refresh".to_owned(),
"chat.text".to_owned(),
"events.ack".to_owned(),
"events.sse".to_owned(),
];
let local_action_tools = match instance {
MockInstanceKind::Companion => {
features.push("messages.proactive".to_owned());
Vec::new()
}
MockInstanceKind::Operations => {
features.push("local-actions.proposals".to_owned());
features.push("diagnostics.readonly".to_owned());
vec!["query_recent_event_logs".to_owned()]
}
};
ServerCapabilities {
protocol_versions: vec![PROTOCOL_VERSION.to_owned()],
features,
local_action_tools,
limits: CapabilityLimits {
max_event_bytes: 262_144,
max_message_bytes: 65_536,
replay_window_events: 256,
max_active_connections: 2,
},
}
}

5
docs/protocol/README.md 普通文件
查看文件

@ -0,0 +1,5 @@
# Desktop Gateway Protocol
This directory contains versioned schemas and examples for the stable AstrBot Desktop Gateway boundary. The desktop client must not depend directly on AstrBot internal APIs.
All inbound events are bound to the local connection profile in the Rust connection layer. A server-supplied local `profile_id` is never trusted as the routing authority.

49
docs/protocol/v1/README.md 普通文件
查看文件

@ -0,0 +1,49 @@
# AstrBot Desktop Gateway Protocol v1
Status: provisional P00 contract for desktop development and the local Mock Gateway.
Compatibility with a real AstrBot Gateway must not be claimed until the server-side contract is reviewed.
## Source of truth
Rust types in `crates/desktop-protocol` are authoritative. JSON Schema files in `schemas/` are generated and checked with:
```text
cargo run -p desktop-protocol --example export_schemas -- --write
cargo run -p desktop-protocol --example export_schemas
```
Generated Schema files must not be edited manually.
## Trust boundary
An inbound `profileId` is an untrusted server hint. The Rust connection object binds each accepted event to its local `profile_id` and `companion` or `operations` slot. `serverInstanceId` must match the identity obtained from `server-info`.
The React application never connects directly to this protocol and never receives access or refresh tokens.
## Versioning
- REST prefix: `/desktop/v1`
- Envelope version: `1.0`
- Breaking wire changes require a new major REST prefix and protocol version.
- Unknown event types are reported as unsupported and safely skipped; they are not routed to the UI.
- Security-sensitive payloads reject unknown outer fields.
## Mock instances
Run each instance in a separate process when manually testing independent failure:
```text
cargo run -p mock-gateway -- --instance companion --port 43101
cargo run -p mock-gateway -- --instance operations --port 43102
```
The Mock Gateway refuses non-loopback bind addresses. It uses only runtime-generated mock credentials, has no shell/file/NAS capability, and is not a Tauri release dependency.
Available fixed scenarios:
- `steady`
- `disconnect-once`
- `duplicate-events`
- `auth-reject`
The 30-minute dual-SSE soak is an explicit local Spike acceptance run and must be recorded separately; its result is not implied by unit tests.

查看文件

@ -0,0 +1,14 @@
{
"protocolVersion": "1.0",
"eventId": "companion-event-000001",
"serverInstanceId": "mock-companion-1",
"conversationId": "same-conversation",
"messageId": "companion-message-000001",
"timestamp": "2026-01-01T00:00:00Z",
"sequence": 1,
"eventType": "message.delta",
"payload": {
"delta": "Deterministic companion response",
"index": 0
}
}

查看文件

@ -0,0 +1,5 @@
{
"status": "ok",
"protocolVersion": "1.0",
"serverInstanceId": "mock-companion-1"
}

查看文件

@ -0,0 +1,23 @@
{
"protocolVersion": "1.0",
"eventId": "operations-event-000001",
"serverInstanceId": "mock-operations-1",
"conversationId": "same-conversation",
"timestamp": "2030-01-01T00:00:00Z",
"sequence": 1,
"eventType": "tool.proposal",
"payload": {
"actionId": "mock-action-event-log-1",
"toolName": "query_recent_event_logs",
"reason": "Inspect a bounded set of recent Application events",
"riskLevel": "read",
"arguments": {
"provider": "Application",
"sinceMinutes": 15,
"maxEntries": 20
},
"requestedAt": "2030-01-01T00:00:00Z",
"expiresAt": "2030-01-01T00:05:00Z",
"requiresApproval": true
}
}

查看文件

@ -0,0 +1,18 @@
{
"protocolVersions": ["1.0"],
"features": [
"auth.refresh",
"chat.text",
"events.ack",
"events.sse",
"local-actions.proposals",
"diagnostics.readonly"
],
"localActionTools": ["query_recent_event_logs"],
"limits": {
"maxEventBytes": 262144,
"maxMessageBytes": 65536,
"replayWindowEvents": 256,
"maxActiveConnections": 2
}
}

54
docs/protocol/v1/http.md 普通文件
查看文件

@ -0,0 +1,54 @@
# Desktop Gateway v1 HTTP and SSE surface
## Public discovery
```text
GET /desktop/v1/health
GET /desktop/v1/server-info
GET /desktop/v1/capabilities
```
`server-info.serverInstanceId` becomes the expected server identity for the active connection. A later mismatch freezes that connection rather than silently rebinding it.
## Authentication
```text
POST /desktop/v1/auth/login
POST /desktop/v1/auth/refresh
```
Credentials and returned tokens remain in the Rust layer. Request and response bodies containing credential material must not derive or use unrestricted debug logging.
## Messaging and events
```text
POST /desktop/v1/messages
GET /desktop/v1/events/stream
POST /desktop/v1/events/{event_id}/ack
```
SSE frames carry both the SSE `id` and the complete JSON event envelope in `data`. Reconnect uses the `Last-Event-ID` request header. Replay and de-duplication are scoped to the local connection profile, so the same event ID on two server instances remains two distinct events.
Initial event types:
```text
system.heartbeat
message.delta
message.completed
message.proactive
agent.status
tool.proposal
capabilities.changed
error
```
## Local action reporting
```text
POST /desktop/v1/local-actions/{action_id}/accepted
POST /desktop/v1/local-actions/{action_id}/rejected
POST /desktop/v1/local-actions/{action_id}/progress
POST /desktop/v1/local-actions/{action_id}/result
```
A `tool.proposal` is only an untrusted proposal. Schema validation, tool registry validation, slot/profile checks, server identity verification, expiry checks, local policy, and user authorization happen before any local execution.

查看文件

@ -0,0 +1,30 @@
# Generated JSON Schemas
This directory is populated from the authoritative Rust types by:
```text
cargo run -p desktop-protocol --example export_schemas -- --write
```
The non-writing form checks committed files for semantic equality and fails if they are missing or stale:
```text
cargo run -p desktop-protocol --example export_schemas
```
Expected generated files:
```text
connection-profile.schema.json
connection-slot.schema.json
server-capabilities.schema.json
client-capabilities.schema.json
protocol-envelope.schema.json
gateway-event.schema.json
tool-proposal.schema.json
tool-result.schema.json
diagnostic-bundle.schema.json
file-transfer-plan.schema.json
```
No generated files are claimed current until the Rust toolchain has run the exporter successfully.

查看文件

@ -0,0 +1,29 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"additionalProperties": false,
"properties": {
"appVersion": {
"type": "string"
},
"features": {
"items": {
"type": "string"
},
"type": "array"
},
"platform": {
"type": "string"
},
"protocolVersion": {
"type": "string"
}
},
"required": [
"protocolVersion",
"appVersion",
"platform",
"features"
],
"title": "ClientCapabilities",
"type": "object"
}

查看文件

@ -0,0 +1,128 @@
{
"$defs": {
"ActiveSlotKind": {
"enum": [
"companion",
"operations"
],
"type": "string"
},
"AstrBotProfileRole": {
"enum": [
"companion",
"operations",
"general"
],
"type": "string"
},
"AuthenticationType": {
"enum": [
"device-token",
"api-key"
],
"type": "string"
}
},
"$schema": "https://json-schema.org/draft/2020-12/schema",
"additionalProperties": false,
"properties": {
"allowInsecureHttp": {
"default": false,
"type": "boolean"
},
"authenticationType": {
"$ref": "#/$defs/AuthenticationType"
},
"autoConnect": {
"default": false,
"type": "boolean"
},
"autoConnectSlot": {
"anyOf": [
{
"$ref": "#/$defs/ActiveSlotKind"
},
{
"type": "null"
}
]
},
"baseUrl": {
"type": "string"
},
"createdAt": {
"type": "string"
},
"credentialReference": {
"type": [
"string",
"null"
]
},
"displayName": {
"type": "string"
},
"eventStreamUrl": {
"type": [
"string",
"null"
]
},
"id": {
"type": "string"
},
"lastConnectedAt": {
"type": [
"string",
"null"
]
},
"localToolPolicyId": {
"type": [
"string",
"null"
]
},
"pinnedCertificateFingerprint": {
"type": [
"string",
"null"
]
},
"protocolVersion": {
"type": [
"string",
"null"
]
},
"role": {
"$ref": "#/$defs/AstrBotProfileRole"
},
"serverInstanceId": {
"type": [
"string",
"null"
]
},
"serverVersion": {
"type": [
"string",
"null"
]
},
"updatedAt": {
"type": "string"
}
},
"required": [
"id",
"displayName",
"role",
"baseUrl",
"authenticationType",
"createdAt",
"updatedAt"
],
"title": "ConnectionProfile",
"type": "object"
}

查看文件

@ -0,0 +1,80 @@
{
"$defs": {
"ActiveSlotKind": {
"enum": [
"companion",
"operations"
],
"type": "string"
},
"ConnectionState": {
"enum": [
"disconnected",
"connecting",
"authenticating",
"syncing",
"connected",
"reconnecting",
"authExpired",
"incompatible",
"serverUnavailable",
"offline",
"certificateChanged",
"fatalError"
],
"type": "string"
}
},
"$schema": "https://json-schema.org/draft/2020-12/schema",
"additionalProperties": false,
"properties": {
"activeConversationId": {
"type": [
"string",
"null"
]
},
"lastConnectedAt": {
"type": [
"string",
"null"
]
},
"lastEventId": {
"type": [
"string",
"null"
]
},
"profileId": {
"type": [
"string",
"null"
]
},
"serverInstanceId": {
"type": [
"string",
"null"
]
},
"slot": {
"$ref": "#/$defs/ActiveSlotKind"
},
"state": {
"$ref": "#/$defs/ConnectionState"
},
"unreadCount": {
"default": 0,
"format": "uint32",
"minimum": 0,
"type": "integer"
}
},
"required": [
"slot",
"state"
],
"title": "ConnectionSlot",
"type": "object"
}

查看文件

@ -0,0 +1,152 @@
{
"$defs": {
"DiagnosticAttachmentReference": {
"additionalProperties": false,
"properties": {
"attachmentId": {
"type": "string"
},
"mimeType": {
"type": "string"
},
"sha256": {
"type": "string"
},
"sizeBytes": {
"format": "uint64",
"minimum": 0,
"type": "integer"
}
},
"required": [
"attachmentId",
"mimeType",
"sizeBytes",
"sha256"
],
"type": "object"
},
"DiagnosticEntry": {
"additionalProperties": false,
"properties": {
"content": {
"type": [
"string",
"null"
]
},
"entryId": {
"type": "string"
},
"kind": {
"$ref": "#/$defs/DiagnosticEntryKind"
},
"mimeType": {
"type": [
"string",
"null"
]
},
"redactions": {
"default": [],
"items": {
"$ref": "#/$defs/RedactionSummary"
},
"type": "array"
},
"sourceLabel": {
"type": "string"
},
"summary": {
"type": "string"
},
"truncated": {
"default": false,
"type": "boolean"
}
},
"required": [
"entryId",
"kind",
"sourceLabel",
"summary"
],
"type": "object"
},
"DiagnosticEntryKind": {
"enum": [
"system",
"window",
"process",
"eventLog",
"network",
"port",
"service",
"logTail",
"configuration"
],
"type": "string"
},
"RedactionSummary": {
"additionalProperties": false,
"properties": {
"category": {
"type": "string"
},
"count": {
"format": "uint32",
"minimum": 0,
"type": "integer"
}
},
"required": [
"category",
"count"
],
"type": "object"
}
},
"$schema": "https://json-schema.org/draft/2020-12/schema",
"additionalProperties": false,
"properties": {
"attachments": {
"default": [],
"items": {
"$ref": "#/$defs/DiagnosticAttachmentReference"
},
"type": "array"
},
"bundleId": {
"type": "string"
},
"entries": {
"items": {
"$ref": "#/$defs/DiagnosticEntry"
},
"type": "array"
},
"generatedAt": {
"type": "string"
},
"scope": {
"items": {
"type": "string"
},
"type": "array"
},
"totalBytes": {
"format": "uint64",
"minimum": 0,
"type": "integer"
}
},
"required": [
"bundleId",
"generatedAt",
"scope",
"entries",
"totalBytes"
],
"title": "DiagnosticBundle",
"type": "object"
}

查看文件

@ -0,0 +1,114 @@
{
"$defs": {
"ConflictAction": {
"enum": [
"copy",
"rename",
"skip",
"ask"
],
"type": "string"
},
"FileTransferPlanItem": {
"additionalProperties": false,
"properties": {
"categoryReason": {
"type": "string"
},
"conflictAction": {
"$ref": "#/$defs/ConflictAction"
},
"destinationRelativePath": {
"type": "string"
},
"displaySourcePath": {
"description": "Display-only value for local review; never used as an execution path.",
"type": "string"
},
"sizeBytes": {
"format": "uint64",
"minimum": 0,
"type": "integer"
},
"sourcePathToken": {
"description": "Opaque, short-lived mapping held by the local client. Never a raw path.",
"type": "string"
}
},
"required": [
"sourcePathToken",
"displaySourcePath",
"destinationRelativePath",
"sizeBytes",
"categoryReason",
"conflictAction"
],
"type": "object"
},
"SourceCleanupPolicy": {
"enum": [
"keep",
"recycle"
],
"type": "string"
}
},
"$schema": "https://json-schema.org/draft/2020-12/schema",
"additionalProperties": false,
"properties": {
"conflictCount": {
"format": "uint32",
"minimum": 0,
"type": "integer"
},
"expiresAt": {
"type": "string"
},
"items": {
"items": {
"$ref": "#/$defs/FileTransferPlanItem"
},
"type": "array"
},
"nasTargetId": {
"type": "string"
},
"planId": {
"type": "string"
},
"profileId": {
"description": "Locally bound profile. A remote value must never select the executor.",
"type": "string"
},
"sourceCleanupPolicy": {
"$ref": "#/$defs/SourceCleanupPolicy"
},
"sourceSelectionId": {
"type": "string"
},
"totalBytes": {
"format": "uint64",
"minimum": 0,
"type": "integer"
},
"warningCount": {
"format": "uint32",
"minimum": 0,
"type": "integer"
}
},
"required": [
"planId",
"profileId",
"sourceSelectionId",
"nasTargetId",
"items",
"totalBytes",
"conflictCount",
"warningCount",
"sourceCleanupPolicy",
"expiresAt"
],
"title": "FileTransferPlan",
"type": "object"
}

查看文件

@ -0,0 +1,422 @@
{
"$defs": {
"AgentStatusPayload": {
"additionalProperties": false,
"properties": {
"detail": {
"type": [
"string",
"null"
]
},
"state": {
"type": "string"
}
},
"required": [
"state"
],
"type": "object"
},
"CapabilityLimits": {
"additionalProperties": false,
"properties": {
"maxActiveConnections": {
"format": "uint8",
"maximum": 255,
"minimum": 0,
"type": "integer"
},
"maxEventBytes": {
"format": "uint64",
"minimum": 0,
"type": "integer"
},
"maxMessageBytes": {
"format": "uint64",
"minimum": 0,
"type": "integer"
},
"replayWindowEvents": {
"format": "uint32",
"minimum": 0,
"type": "integer"
}
},
"required": [
"maxEventBytes",
"maxMessageBytes",
"replayWindowEvents",
"maxActiveConnections"
],
"type": "object"
},
"FinishReason": {
"enum": [
"stop",
"cancelled",
"error"
],
"type": "string"
},
"GatewayErrorPayload": {
"additionalProperties": false,
"properties": {
"code": {
"type": "string"
},
"message": {
"type": "string"
},
"retryable": {
"type": "boolean"
}
},
"required": [
"code",
"message",
"retryable"
],
"type": "object"
},
"HeartbeatPayload": {
"additionalProperties": false,
"properties": {
"intervalMs": {
"format": "uint64",
"minimum": 0,
"type": "integer"
}
},
"required": [
"intervalMs"
],
"type": "object"
},
"MessageCompletedPayload": {
"additionalProperties": false,
"properties": {
"content": {
"type": [
"string",
"null"
]
},
"finishReason": {
"$ref": "#/$defs/FinishReason"
}
},
"required": [
"finishReason"
],
"type": "object"
},
"MessageDeltaPayload": {
"additionalProperties": false,
"properties": {
"delta": {
"type": "string"
},
"index": {
"format": "uint32",
"minimum": 0,
"type": "integer"
}
},
"required": [
"delta",
"index"
],
"type": "object"
},
"ProactiveMessagePayload": {
"additionalProperties": false,
"properties": {
"content": {
"type": "string"
},
"notificationTitle": {
"type": [
"string",
"null"
]
}
},
"required": [
"content"
],
"type": "object"
},
"RiskLevel": {
"enum": [
"read",
"reversible-write",
"destructive"
],
"type": "string"
},
"ServerCapabilities": {
"additionalProperties": false,
"properties": {
"features": {
"items": {
"type": "string"
},
"type": "array"
},
"limits": {
"$ref": "#/$defs/CapabilityLimits"
},
"localActionTools": {
"default": [],
"items": {
"type": "string"
},
"type": "array"
},
"protocolVersions": {
"items": {
"type": "string"
},
"type": "array"
}
},
"required": [
"protocolVersions",
"features",
"limits"
],
"type": "object"
},
"ToolProposal": {
"additionalProperties": false,
"properties": {
"actionId": {
"type": "string"
},
"arguments": true,
"expiresAt": {
"type": "string"
},
"reason": {
"type": "string"
},
"requestedAt": {
"type": "string"
},
"requiresApproval": {
"type": "boolean"
},
"riskLevel": {
"$ref": "#/$defs/RiskLevel"
},
"toolName": {
"type": "string"
}
},
"required": [
"actionId",
"toolName",
"reason",
"riskLevel",
"arguments",
"requestedAt",
"expiresAt",
"requiresApproval"
],
"type": "object"
}
},
"$schema": "https://json-schema.org/draft/2020-12/schema",
"oneOf": [
{
"properties": {
"eventType": {
"const": "system.heartbeat",
"type": "string"
},
"payload": {
"$ref": "#/$defs/HeartbeatPayload"
}
},
"required": [
"eventType",
"payload"
],
"type": "object"
},
{
"properties": {
"eventType": {
"const": "message.delta",
"type": "string"
},
"payload": {
"$ref": "#/$defs/MessageDeltaPayload"
}
},
"required": [
"eventType",
"payload"
],
"type": "object"
},
{
"properties": {
"eventType": {
"const": "message.completed",
"type": "string"
},
"payload": {
"$ref": "#/$defs/MessageCompletedPayload"
}
},
"required": [
"eventType",
"payload"
],
"type": "object"
},
{
"properties": {
"eventType": {
"const": "message.proactive",
"type": "string"
},
"payload": {
"$ref": "#/$defs/ProactiveMessagePayload"
}
},
"required": [
"eventType",
"payload"
],
"type": "object"
},
{
"properties": {
"eventType": {
"const": "agent.status",
"type": "string"
},
"payload": {
"$ref": "#/$defs/AgentStatusPayload"
}
},
"required": [
"eventType",
"payload"
],
"type": "object"
},
{
"properties": {
"eventType": {
"const": "tool.proposal",
"type": "string"
},
"payload": {
"$ref": "#/$defs/ToolProposal"
}
},
"required": [
"eventType",
"payload"
],
"type": "object"
},
{
"properties": {
"eventType": {
"const": "capabilities.changed",
"type": "string"
},
"payload": {
"$ref": "#/$defs/ServerCapabilities"
}
},
"required": [
"eventType",
"payload"
],
"type": "object"
},
{
"properties": {
"eventType": {
"const": "error",
"type": "string"
},
"payload": {
"$ref": "#/$defs/GatewayErrorPayload"
}
},
"required": [
"eventType",
"payload"
],
"type": "object"
}
],
"properties": {
"conversationId": {
"type": [
"string",
"null"
]
},
"eventId": {
"type": "string"
},
"messageId": {
"type": [
"string",
"null"
]
},
"profileId": {
"description": "Untrusted server hint. Local routing must use `BoundGatewayEvent.profile_id`.",
"type": [
"string",
"null"
]
},
"protocolVersion": {
"type": "string"
},
"requestId": {
"type": [
"string",
"null"
]
},
"sequence": {
"format": "uint64",
"minimum": 0,
"type": [
"integer",
"null"
]
},
"serverInstanceId": {
"type": "string"
},
"sessionId": {
"type": [
"string",
"null"
]
},
"timestamp": {
"type": "string"
}
},
"required": [
"protocolVersion",
"eventId",
"serverInstanceId",
"timestamp"
],
"title": "GatewayEvent",
"type": "object"
}

查看文件

@ -0,0 +1,72 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"additionalProperties": false,
"description": "Two-stage wire representation used before a payload type is trusted.",
"properties": {
"conversationId": {
"type": [
"string",
"null"
]
},
"eventId": {
"type": "string"
},
"eventType": {
"type": "string"
},
"messageId": {
"type": [
"string",
"null"
]
},
"payload": true,
"profileId": {
"description": "This value is never used as the local profile binding.",
"type": [
"string",
"null"
]
},
"protocolVersion": {
"type": "string"
},
"requestId": {
"type": [
"string",
"null"
]
},
"sequence": {
"format": "uint64",
"minimum": 0,
"type": [
"integer",
"null"
]
},
"serverInstanceId": {
"type": "string"
},
"sessionId": {
"type": [
"string",
"null"
]
},
"timestamp": {
"type": "string"
}
},
"required": [
"protocolVersion",
"eventType",
"eventId",
"serverInstanceId",
"timestamp",
"payload"
],
"title": "ProtocolEnvelope",
"type": "object"
}

查看文件

@ -0,0 +1,70 @@
{
"$defs": {
"CapabilityLimits": {
"additionalProperties": false,
"properties": {
"maxActiveConnections": {
"format": "uint8",
"maximum": 255,
"minimum": 0,
"type": "integer"
},
"maxEventBytes": {
"format": "uint64",
"minimum": 0,
"type": "integer"
},
"maxMessageBytes": {
"format": "uint64",
"minimum": 0,
"type": "integer"
},
"replayWindowEvents": {
"format": "uint32",
"minimum": 0,
"type": "integer"
}
},
"required": [
"maxEventBytes",
"maxMessageBytes",
"replayWindowEvents",
"maxActiveConnections"
],
"type": "object"
}
},
"$schema": "https://json-schema.org/draft/2020-12/schema",
"additionalProperties": false,
"properties": {
"features": {
"items": {
"type": "string"
},
"type": "array"
},
"limits": {
"$ref": "#/$defs/CapabilityLimits"
},
"localActionTools": {
"default": [],
"items": {
"type": "string"
},
"type": "array"
},
"protocolVersions": {
"items": {
"type": "string"
},
"type": "array"
}
},
"required": [
"protocolVersions",
"features",
"limits"
],
"title": "ServerCapabilities",
"type": "object"
}

查看文件

@ -0,0 +1,50 @@
{
"$defs": {
"RiskLevel": {
"enum": [
"read",
"reversible-write",
"destructive"
],
"type": "string"
}
},
"$schema": "https://json-schema.org/draft/2020-12/schema",
"additionalProperties": false,
"properties": {
"actionId": {
"type": "string"
},
"arguments": true,
"expiresAt": {
"type": "string"
},
"reason": {
"type": "string"
},
"requestedAt": {
"type": "string"
},
"requiresApproval": {
"type": "boolean"
},
"riskLevel": {
"$ref": "#/$defs/RiskLevel"
},
"toolName": {
"type": "string"
}
},
"required": [
"actionId",
"toolName",
"reason",
"riskLevel",
"arguments",
"requestedAt",
"expiresAt",
"requiresApproval"
],
"title": "ToolProposal",
"type": "object"
}

查看文件

@ -0,0 +1,44 @@
{
"$defs": {
"ToolResultStatus": {
"enum": [
"rejected",
"completed",
"failed",
"cancelled"
],
"type": "string"
}
},
"$schema": "https://json-schema.org/draft/2020-12/schema",
"additionalProperties": false,
"properties": {
"actionId": {
"type": "string"
},
"completedAt": {
"type": "string"
},
"errorCode": {
"type": [
"string",
"null"
]
},
"result": true,
"status": {
"$ref": "#/$defs/ToolResultStatus"
},
"summary": {
"type": "string"
}
},
"required": [
"actionId",
"status",
"summary",
"completedAt"
],
"title": "ToolResult",
"type": "object"
}

48
eslint.config.js 普通文件
查看文件

@ -0,0 +1,48 @@
import eslint from "@eslint/js";
import globals from "globals";
import reactHooks from "eslint-plugin-react-hooks";
import reactRefresh from "eslint-plugin-react-refresh";
import tseslint from "typescript-eslint";
export default tseslint.config(
{
ignores: [
"dist",
"coverage",
"target",
"src-tauri/target",
"packages/*/dist",
],
},
eslint.configs.recommended,
...tseslint.configs.recommended,
{
files: ["**/*.{ts,tsx}"],
languageOptions: {
ecmaVersion: 2022,
globals: globals.browser,
parserOptions: {
projectService: true,
tsconfigRootDir: import.meta.dirname,
},
},
plugins: {
"react-hooks": reactHooks,
"react-refresh": reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
"react-hooks/set-state-in-effect": "off",
"react-refresh/only-export-components": [
"warn",
{ allowConstantExport: true },
],
},
},
{
files: ["**/*.config.{js,ts}", "eslint.config.js"],
languageOptions: {
globals: globals.node,
},
},
);

13
index.html 普通文件
查看文件

@ -0,0 +1,13 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="color-scheme" content="dark light" />
<title>AstrBot Desktop</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

61
package.json 普通文件
查看文件

@ -0,0 +1,61 @@
{
"name": "astrbot-desktop",
"version": "0.1.0-alpha.0",
"private": true,
"type": "module",
"packageManager": "pnpm@11.9.0",
"engines": {
"node": ">=24.17.0 <25",
"pnpm": ">=11.9.0 <12"
},
"scripts": {
"dev": "node ./node_modules/vite/bin/vite.js --configLoader runner",
"tauri": "node ./node_modules/@tauri-apps/cli/tauri.js",
"tauri:dev": "node ./node_modules/@tauri-apps/cli/tauri.js dev",
"tauri:build": "node ./node_modules/@tauri-apps/cli/tauri.js build",
"build": "node ./node_modules/typescript/bin/tsc -b && node ./node_modules/vite/bin/vite.js build --configLoader runner",
"format": "node ./node_modules/prettier/bin/prettier.cjs --write .",
"format:check": "node ./node_modules/prettier/bin/prettier.cjs --check .",
"lint": "node ./node_modules/eslint/bin/eslint.js . --max-warnings 0",
"typecheck": "node ./node_modules/typescript/bin/tsc -b --pretty false",
"test": "node ./node_modules/vitest/vitest.mjs run --configLoader runner",
"test:watch": "node ./node_modules/vitest/vitest.mjs --configLoader runner",
"pretest:e2e": "node ./node_modules/typescript/bin/tsc -b && node ./node_modules/vite/bin/vite.js build --configLoader runner",
"test:e2e": "node ./node_modules/@playwright/test/cli.js test",
"check:frontend": "node ./node_modules/prettier/bin/prettier.cjs --check . && node ./node_modules/eslint/bin/eslint.js . --max-warnings 0 && node ./node_modules/typescript/bin/tsc -b --pretty false && node ./node_modules/vitest/vitest.mjs run --configLoader runner && node ./node_modules/vite/bin/vite.js build --configLoader runner",
"rust:fmt": "cargo fmt --all -- --check",
"rust:check": "cargo check --workspace --all-targets",
"rust:clippy": "cargo clippy --workspace --all-targets -- -D warnings",
"rust:test": "cargo test --workspace",
"mock:dev": "cargo run -p mock-gateway -- --instance companion --port 43101",
"mock:test": "cargo test -p mock-gateway",
"check:rust": "cargo fmt --all -- --check && cargo clippy --workspace --all-targets -- -D warnings && cargo test --workspace && cargo check --workspace --all-targets"
},
"dependencies": {
"@tauri-apps/api": "2.11.1",
"react": "19.2.7",
"react-dom": "19.2.7",
"zod": "4.4.3"
},
"devDependencies": {
"@eslint/js": "10.0.1",
"@playwright/test": "1.61.1",
"@tauri-apps/cli": "2.11.4",
"@testing-library/jest-dom": "6.9.1",
"@testing-library/react": "16.3.2",
"@types/node": "24.13.3",
"@types/react": "19.2.17",
"@types/react-dom": "19.2.3",
"@vitejs/plugin-react": "6.0.3",
"eslint": "10.7.0",
"eslint-plugin-react-hooks": "7.1.1",
"eslint-plugin-react-refresh": "0.5.3",
"globals": "17.5.0",
"jsdom": "29.1.1",
"prettier": "3.9.5",
"typescript": "6.0.3",
"typescript-eslint": "8.64.0",
"vite": "8.1.5",
"vitest": "4.1.10"
}
}

2644
pnpm-lock.yaml 自动生成 普通文件

文件差异内容过多而无法显示 加载差异

2
pnpm-workspace.yaml 普通文件
查看文件

@ -0,0 +1,2 @@
packages:
- packages/*

5
rust-toolchain.toml 普通文件
查看文件

@ -0,0 +1,5 @@
[toolchain]
channel = "1.97.1"
profile = "minimal"
components = ["rustfmt", "clippy"]
targets = ["x86_64-pc-windows-msvc"]

63
src-tauri/Cargo.toml 普通文件
查看文件

@ -0,0 +1,63 @@
[package]
name = "astrbot-desktop"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
description = "AstrBot Windows companion and local-assistance desktop client"
[lib]
name = "astrbot_desktop_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build.workspace = true
[dependencies]
desktop-protocol = { path = "../crates/desktop-protocol" }
eventsource-stream.workspace = true
futures-util.workspace = true
png.workspace = true
quick-xml.workspace = true
regex.workspace = true
reqwest.workspace = true
rusqlite.workspace = true
secrecy.workspace = true
serde.workspace = true
serde_json.workspace = true
sha2.workspace = true
sysinfo.workspace = true
tauri.workspace = true
tauri-plugin-single-instance = "2.4.3"
thiserror.workspace = true
time.workspace = true
tokio.workspace = true
tokio-util.workspace = true
toml.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
url.workspace = true
uuid.workspace = true
yaml-rust2.workspace = true
zeroize.workspace = true
[target.'cfg(windows)'.dependencies]
windows = { workspace = true, features = [
"Win32_Foundation",
"Win32_Graphics_Gdi",
"Win32_NetworkManagement_IpHelper",
"Win32_Networking_WinSock",
"Win32_Security_Credentials",
"Win32_Storage_FileSystem",
"Win32_Storage_Xps",
"Win32_System_Com",
"Win32_System_EventLog",
"Win32_System_ProcessStatus",
"Win32_System_Threading",
"Win32_UI_Accessibility",
"Win32_UI_WindowsAndMessaging",
] }
[dev-dependencies]
tempfile.workspace = true
mock-gateway = { path = "../crates/mock-gateway" }

3
src-tauri/build.rs 普通文件
查看文件

@ -0,0 +1,3 @@
fn main() {
tauri_build::build();
}

查看文件

@ -0,0 +1,7 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Minimal capability set for the main AstrBot Desktop window.",
"windows": ["main"],
"permissions": ["core:default"]
}

二进制
src-tauri/icons/128x128.png 普通文件

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 3 KiB

二进制
src-tauri/icons/128x128@2x.png 普通文件

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 6.5 KiB

二进制
src-tauri/icons/32x32.png 普通文件

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 867 B

二进制
src-tauri/icons/64x64.png 普通文件

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 1.5 KiB

二进制
src-tauri/icons/Square107x107Logo.png 普通文件

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 2.6 KiB

二进制
src-tauri/icons/Square142x142Logo.png 普通文件

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 3.6 KiB

二进制
src-tauri/icons/Square150x150Logo.png 普通文件

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 3.8 KiB

二进制
src-tauri/icons/Square284x284Logo.png 普通文件

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 7.6 KiB

二进制
src-tauri/icons/Square30x30Logo.png 普通文件

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 812 B

二进制
src-tauri/icons/Square310x310Logo.png 普通文件

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 8.4 KiB

二进制
src-tauri/icons/Square44x44Logo.png 普通文件

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 1.1 KiB

二进制
src-tauri/icons/Square71x71Logo.png 普通文件

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 1.7 KiB

二进制
src-tauri/icons/Square89x89Logo.png 普通文件

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 2.3 KiB

二进制
src-tauri/icons/StoreLogo.png 普通文件

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 1.3 KiB

查看文件

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
<background android:drawable="@color/ic_launcher_background"/>
</adaptive-icon>

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 2 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 4.2 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 1.8 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 1.9 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 2.7 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 1.7 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 4 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 5.4 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 3.6 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 6.2 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 8.7 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 5.4 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 8.5 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 11 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 7.6 KiB

查看文件

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#fff</color>
</resources>

二进制
src-tauri/icons/icon.icns 普通文件

二进制文件未显示。

二进制
src-tauri/icons/icon.ico 普通文件

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 12 KiB

二进制
src-tauri/icons/icon.png 普通文件

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 13 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 549 B

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 1 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 1 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 1.5 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 748 B

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 1.5 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 1.5 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 2.2 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 1 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 1.9 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 1.9 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 3.1 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 36 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 3.1 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 4.7 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 1.9 KiB

二进制文件未显示。

之后

宽度:  |  高度:  |  大小: 3.9 KiB

某些文件未显示,因为此 diff 中更改的文件太多 显示更多