Merge pull request 'feat(p00): bootstrap Tauri desktop and validate high-risk spikes' (#1) from feat/p00-bootstrap into main
一些检测仍在等待运行
ci / Portable quality checks (push) Waiting to run
ci / Windows Tauri build (push) Waiting to run

Reviewed-on: http://192.168.31.210:18085/YokiiroBW/AstrBot-Desktop/pulls/1
这个提交存在于:
YokiiroBW 2026-07-18 21:48:26 +08:00
当前提交 b3420e485a
共有 168 个文件被更改,包括 19506 次插入 和 0 次删除

141
.forgejo/workflows/ci.yml 普通文件
查看文件

@ -0,0 +1,141 @@
name: ci
on:
push:
pull_request:
workflow_dispatch:
permissions:
contents: read
env:
CI: "true"
CARGO_TERM_COLOR: always
jobs:
portable-quality:
name: Portable quality checks
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- name: Check out repository
uses: actions/checkout@v4
- name: Install pnpm
uses: pnpm/action-setup@v4
with:
version: 11.9.0
run_install: false
- name: Install Node.js
uses: actions/setup-node@v4
with:
node-version-file: .node-version
cache: pnpm
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@1.97.1
with:
components: rustfmt, clippy
- name: Install Linux Tauri prerequisites
shell: bash
run: |
if command -v sudo >/dev/null 2>&1; then
SUDO=sudo
else
SUDO=
fi
$SUDO apt-get update
$SUDO apt-get install -y \
libwebkit2gtk-4.1-dev \
libayatana-appindicator3-dev \
librsvg2-dev \
libxdo-dev \
libssl-dev \
patchelf
- name: Install JavaScript dependencies
run: pnpm install --frozen-lockfile
- name: Run frontend checks
run: pnpm check:frontend
- name: Install Playwright Chromium
run: pnpm exec playwright install chromium
- name: Run browser smoke tests
run: pnpm test:e2e
- name: Run workspace package tests
run: pnpm -r --if-present run test
- name: Check Rust formatting
run: pnpm rust:fmt
- name: Run Rust Clippy
run: pnpm rust:clippy
- name: Run Rust tests
run: pnpm rust:test
- name: Run Rust check
run: pnpm rust:check
windows-tauri:
name: Windows Tauri build
if: vars.ENABLE_WINDOWS_TAURI_CI == 'true'
runs-on: windows-latest
timeout-minutes: 45
steps:
- name: Check out repository
uses: actions/checkout@v4
- name: Install pnpm
uses: pnpm/action-setup@v4
with:
version: 11.9.0
run_install: false
- name: Install Node.js
uses: actions/setup-node@v4
with:
node-version-file: .node-version
cache: pnpm
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@1.97.1
with:
components: rustfmt, clippy
- name: Install JavaScript dependencies
run: pnpm install --frozen-lockfile
- name: Run frontend checks
run: pnpm check:frontend
- name: Install Playwright Chromium
run: pnpm exec playwright install chromium
- name: Run browser smoke tests
run: pnpm test:e2e
- name: Run workspace package tests
run: pnpm -r --if-present run test
- name: Check Rust formatting
run: pnpm rust:fmt
- name: Run Rust Clippy
run: pnpm rust:clippy
- name: Run Rust tests
run: pnpm rust:test
- name: Run Rust check
run: pnpm rust:check
- name: Build Tauri application
run: pnpm tauri:build

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

26
CHANGELOG.md 普通文件
查看文件

@ -0,0 +1,26 @@
# Changelog
All notable changes to this project will be documented in this file.
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow Semantic Versioning.
## [Unreleased]
### Added
- Authoritative architecture, implementation, and repository workflow documents.
- Repository rules, ignore rules, implementation plan, progress tracking, and decision log.
- Tauri 2, React, TypeScript, Vite, and Rust workspace skeleton with tray and single-instance lifecycle.
- Independent companion and operations REST/SSE clients with local profile binding, cancellation, reconnect, Last-Event-ID, and per-slot deduplication.
- Windows Credential Manager, bounded UI Automation, selected-window in-memory capture, Event Log, process, port, foreground-window, authorized log-tail, configuration parsing, and redaction Spikes.
- Recoverable plan/dry-run/copy/verify/commit file transactions with no-overwrite conflict policies and source preservation.
- Composite-key SQLite isolation for profile, server, conversation, message, cursor, proposal, and transaction data.
- Provisional desktop-v1alpha1 Rust types, TypeScript exports, ten JSON Schemas, drift checks, and two loopback-only Mock Gateway instances.
- Frontend, browser, Rust, integration, Windows provider, soak, and Forgejo CI test entry points.
- P00 dependency review and durable Spike result records.
### Security
- Kept credentials and native capabilities in Rust; the React capability set remains `core:default` only.
- Added secret redaction and repository scans; no arbitrary PowerShell, CMD, shell, input-injection, registry-write, or unrestricted filesystem API is exposed.
- Kept real UNC writes, signing keys, updater keys, and release secrets outside P00.

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"

62
README.md 普通文件
查看文件

@ -0,0 +1,62 @@
# AstrBot Desktop
AstrBot Desktop is a Windows companion and local-assistance client built with Tauri 2, React, TypeScript, Vite, and Rust.
The MVP supports two isolated active AstrBot connection slots:
- `companion` for chat, proactive messages, voice, and game companionship;
- `operations` for user-authorized, policy-controlled diagnostics and recoverable file operations.
## Security boundaries
- Credentials remain in Windows secure storage and are never exposed to React.
- Server tool requests are proposals; the Rust policy layer makes the final decision.
- The application does not provide arbitrary PowerShell, CMD, or shell execution.
- NAS transfers use `plan -> dry run -> copy -> verify -> commit` and preserve source files on failure.
## Current phase
The repository is in the P00 bootstrap and high-risk Spike phase. See [docs/implementation-plan.md](docs/implementation-plan.md) and [docs/progress.md](docs/progress.md).
## Authoritative documents
- `AGENTS.md`
- `docs/01_Architecture_Design.md`
- `docs/02_Codex_Implementation_Tasks.md`
- `AstrBot_Desktop_Codex_Forgejo_Predevelopment_Workflow.md`
## Development prerequisites
- Windows 11
- Node.js and pnpm
- Rust stable with the MSVC target
- Visual Studio 2022 Build Tools with Desktop development with C++
- WebView2 Evergreen Runtime
## Local commands
```text
pnpm install --frozen-lockfile
pnpm check:frontend
pnpm test:e2e
pnpm rust:fmt
pnpm rust:clippy
pnpm rust:test
pnpm rust:check
pnpm tauri:dev
pnpm tauri:build
```
On Windows, Cargo build output can be redirected away from a NAS workspace:
```powershell
$env:CARGO_TARGET_DIR = "$env:LOCALAPPDATA\Temp\AstrBot-Desktop-target"
```
The 30-minute connection soak and the controlled Windows UIA/capture smoke are
ignored by the normal suite and must be invoked explicitly as documented in
[tests/README.md](tests/README.md). The UIA/capture smoke opens only a generated,
non-sensitive standard dialog and never writes captured pixels to disk.
P00 results and unresolved environment boundaries are recorded in
[docs/spikes](docs/spikes) and [docs/progress.md](docs/progress.md).

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,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,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,
},
}
}

查看文件

@ -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")
}

查看文件

@ -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")
}

查看文件

@ -0,0 +1,36 @@
# ADR-0001: Use a Root-Level Desktop Application for P00
- Status: Accepted
- Date: 2026-07-18
- Scope: Repository layout and build orchestration
## Context
The architecture document illustrates a future monorepo with the desktop application under apps/desktop. The predevelopment workflow separately recommends root-level src and src-tauri directories. P00 has one product application plus supporting protocol and Mock Gateway packages, so an additional application directory would add path and command complexity without isolating a second deployable application.
## Options considered
1. Put the desktop application under apps/desktop immediately.
2. Keep the desktop application at the repository root and place reusable development packages under packages.
3. Create separate repositories for the desktop application, protocol, and Mock Gateway.
## Decision
P00 uses a root-level React/Vite application and root-level src-tauri directory. Reusable protocol types, fixtures, and the Mock Gateway may live under packages and are managed by the root pnpm workspace.
Moving the desktop application under apps/desktop is deferred until a second independently deployable application creates a concrete need.
## Rationale
- Matches the explicit P00 workflow.
- Keeps Tauri and Vite generated conventions simple.
- Avoids premature monorepo nesting.
- Still permits package-level isolation for protocol and test tooling.
- Does not change the React/Rust security boundary.
## Consequences
- Root scripts are the canonical entry points for frontend, Rust, and Tauri checks.
- CI paths refer to src-tauri/Cargo.toml.
- A future layout move will require path updates in scripts, CI, and documentation.
- No package may introduce a second product UI without a separate decision.

查看文件

@ -0,0 +1,39 @@
# ADR-0002: Bind Profile Identity at the Rust Connection Boundary
- Status: Accepted
- Date: 2026-07-18
- Scope: Protocol identity, dual-instance isolation, and connection lifecycle
## Context
The desktop client maintains two simultaneously active connection slots: companion and operations. A remote event can contain identifiers such as profile_id, server_instance_id, conversation_id, and message_id. The remote service is not authoritative for the local profile assignment, and conversation or message identifiers may overlap across servers.
## Options considered
1. Merge both SSE streams and route events using remote conversation_id values.
2. Trust a remote profile_id field and route events from a shared client.
3. Maintain one independently owned connection session per active slot and attach the selected local profile identity before events leave the Rust networking layer.
## Decision
Each active slot owns an independent REST client, SSE stream, cancellation handle, retry state, Last-Event-ID cursor, and deduplication cache.
The Rust networking layer binds every accepted event to the locally selected profile_id. A remote profile_id is treated as untrusted protocol data and cannot override local routing.
Persisted or cached server data is keyed by at least profile_id, server_instance_id, and conversation_id. Message-level data additionally uses message_id where applicable.
The initial Mock Gateway protocol is explicitly provisional and identified as desktop-v1alpha1 until it is reviewed against a real AstrBot Gateway.
## Rationale
- Prevents cross-instance message and authorization confusion.
- Allows either connection to fail, cancel, or reconnect independently.
- Makes the operations-slot security check deterministic.
- Preserves isolation when two servers reuse the same conversation or message IDs.
## Consequences
- Shared global retry, cursor, and deduplication state is prohibited.
- Tests must inject identical and malicious identifiers across both mock instances.
- A server identity change freezes local-tool eligibility until the user reconfirms it.
- Real AstrBot compatibility remains unverified while the Gateway is unavailable.

查看文件

@ -0,0 +1,41 @@
# ADR-0003: Keep Native Security-Critical Capabilities in Rust
- Status: Accepted
- Date: 2026-07-18
- Scope: Credentials, diagnostics, local actions, and file transactions
## Context
AstrBot Desktop needs Windows Credential Manager access, bounded diagnostics, UI Automation, window capture, event-log queries, and recoverable NAS file transactions. Remote model output, screen content, and file content are untrusted. Exposing generic operating-system execution or unrestricted paths would violate the project security model.
## Options considered
1. Expose broad filesystem or command APIs to React and enforce safety in the UI.
2. Add a generic command runner and restrict it through prompts or string validation.
3. Expose only typed, bounded Tauri commands backed by Rust policy checks and Windows-native APIs.
## Decision
All credentials, operating-system inspection, local policy decisions, and filesystem mutations remain in Rust.
React receives only display-safe results, opaque credential references, bounded path-selection tokens, and explicit operation states. It never receives credential values or unrestricted filesystem access.
The product does not include a shell plugin or any generic PowerShell, CMD, shell, registry-write, keyboard-script, or arbitrary-path execution API.
Local actions follow schema validation, tool allowlisting, profile and slot validation, path-scope validation, risk classification, authorization, execution, and audit.
P00 NAS validation uses plan, dry run, temporary copy, size and SHA-256 verification, and atomic destination commit. Source files are preserved; source cleanup is represented only as a non-executed plan field.
## Rationale
- Makes security enforcement independent of UI state and remote prompts.
- Limits the native attack surface to explicit operations.
- Keeps secret values out of React, SQLite ordinary fields, logs, and snapshots.
- Preserves source data during an interrupted or failed NAS operation.
## Consequences
- Windows-native behavior requires Windows-specific tests and cannot be certified by Linux CI.
- Unsupported or elevated targets must fail safely without privilege escalation.
- New native tools require an explicit schema, allowlist entry, risk level, tests, and audit behavior.
- Destructive cleanup, updater signing, and broader desktop control require separate decisions and authorization.

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

@ -0,0 +1,5 @@
# Architecture Decision Records
Use `ADR-NNNN-short-title.md` for decisions that materially affect the protocol, security model, database schema, public interfaces, or long-term architecture.
Use `pending-decisions.md` for unresolved or operational questions that do not yet justify an ADR.

查看文件

@ -0,0 +1,52 @@
# Pending Decisions
## PD-0001: Forgejo transport for the development machine
- Status: resolved for HTTP push; SSH remains unavailable
- Current value: `ssh://git@localhost:18086/YokiiroBW/AstrBot-Desktop.git`
- Push URL: `http://192.168.31.210:18085/YokiiroBW/AstrBot-Desktop.git`
- Observation: the authenticated Forgejo API confirmed `YokiiroBW/AstrBot-Desktop` existed, was empty, used `main`, and granted push permission before initialization.
- SSH observation: `localhost:18086` refuses connections. `192.168.31.210:18086` answers but rejects the available SSH key.
- Push observation: Git Credential Manager was cleared and reauthenticated without placing a secret in the repository or chat. The approved non-forced HTTP push succeeded and remote `main` now points to `0d12b94`.
- Decision: retain the SSH URL as the fetch URL for future key repair and use the explicitly approved HTTP URL as the push URL for this workflow.
- Safety impact: no force push or history overwrite occurred; `feat/p00-bootstrap` was created from the pushed baseline.
## PD-0002: P00 branch naming
- Status: resolved for this predevelopment workflow
- Decision: use `feat/p00-bootstrap` as explicitly required by the workflow and current user request.
- Follow-up: subsequent stages use the branch names in `AGENTS.md`.
## PD-0003: Node.js release line
- Status: monitor during bootstrap
- Current environment: Node.js 24.
- Decision: use the installed version initially; pin package-manager and dependency versions in the repository and record any Tauri/Vite incompatibility found by actual builds.
## PD-0004: P00 source layout
- Status: resolved for P00
- Observation: the architecture document illustrates an `apps/desktop` monorepo, while the predevelopment workflow recommends root-level `src` and `src-tauri` directories.
- Decision: keep the single desktop application at the repository root during P00 and use Cargo workspace crates for protocol and Mock Gateway isolation.
- Reason: there is only one application, and the workflow explicitly recommends the root layout; this avoids an extra package layer without preventing a later move if a second application appears.
## PD-0005: Source cleanup in the NAS Spike
- Status: resolved for P00
- Conflict: the implementation task mentions cleanup after verification, while the workflow and safety rules require source preservation and prohibit irreversible tests.
- Decision: P00 always preserves source files and tests cleanup policy only as a non-executed plan field.
- Follow-up: reversible recycle-bin behavior requires a later explicitly authorized Spike.
## PD-0006: Provisional desktop gateway contract
- Status: resolved for P00
- Decision: define a provisional `desktop-v1alpha1` contract and Mock Gateway without claiming compatibility with an unavailable real AstrBot Gateway.
- Follow-up: authentication fields, error codes, event retention, ACK timing, and capability names require a later real-gateway contract review.
## PD-0007: Repository-local Git author identity
- Status: resolved
- Decision: the user explicitly approved `YokiiroBW <yokiirobw@gmail.com>`.
- Implementation: the identity is configured only in this repository.
- Result: two Conventional Commit baseline commits were created on `main`, pushed normally, and followed by scoped feature-branch commits.
- Safety impact: no global Git identity was changed.

57
docs/dependency-review.md 普通文件
查看文件

@ -0,0 +1,57 @@
# P00 Dependency Review
Date: 2026-07-18
This review covers direct dependencies introduced for the isolated P00 Spikes. Versions are pinned in
`package.json`, `pnpm-lock.yaml`, `Cargo.toml`, and `Cargo.lock`. ?Maintained? below means the
selected release line is current enough to resolve, compile, lint, test, and build on the audited
toolchain; it is not a promise of future upstream maintenance.
## Frontend and desktop dependencies
| Dependency | Purpose | Maintenance and alternatives | Native compile | Permission or attack-surface effect |
| --------------------------------------------- | ------------------------------------------------------ | ----------------------------------------------------------------------------------- | ---------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| React, React DOM | Minimal status UI and future interaction layer | Active release line; alternatives would replace the mandated React baseline | No | Browser-side rendering only |
| Zod | Runtime validation for frontend-facing typed data | Active release line; manual validators are possible but easier to drift | No | Reduces acceptance of malformed data |
| Tauri API and CLI | Mandated Tauri 2 application runtime and build tooling | Active Tauri 2 release line; changing it would violate the baseline | Rust build for the desktop binary | Adds only configured Tauri core capabilities; no shell or broad filesystem plugin is enabled |
| Vite and React plugin | Development server and production web bundle | Active release line; alternative bundlers are unnecessary for P00 | esbuild binaries are dependency-managed | Development/build-time surface only |
| TypeScript and type packages | Static frontend typing | Active release line; no equivalent is needed under the mandated stack | No | Build-time only |
| ESLint, TypeScript ESLint, React lint plugins | Static correctness and hook checks | Active release lines; alternatives provide similar checks | No | Build-time only |
| Prettier | Deterministic formatting | Active release line; alternatives would add no P00 value | No | Build-time only |
| Vitest, Testing Library, jsdom | Frontend unit and component tests | Active release lines; Jest is an alternative with more configuration | Some transitive optional binaries may be platform-specific | Test-only; no release capability |
| Playwright Test | Browser smoke testing | Active release line; WebDriver alternatives are less aligned with the existing test | Browser executable is external to the app | Test-only; browsers are not shipped with the desktop binary |
## Rust runtime dependencies
| Dependency group | Purpose | Maintenance and alternatives | Native compile | Permission or attack-surface effect |
| ----------------------------------------------------------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------ |
| `tauri`, `tauri-build`, `tauri-plugin-single-instance` | Desktop lifecycle, tray, IPC bootstrap, single instance | Mandated and on the Tauri 2 line; no framework substitution approved | Yes | Native window/tray lifecycle only; capabilities remain explicit |
| `reqwest` with rustls, `eventsource-stream`, `futures-util` | REST and SSE clients | Current release lines; manual HTTP/SSE parsing would increase risk | Rustls is compiled in Rust | Outbound HTTP(S) to configured gateways; redirects are disabled |
| `tokio`, `tokio-util` | Independent async connections, cancellation, timers | Current release lines; required by the selected HTTP/server ecosystem | No external native library | Concurrency only; no new OS permission |
| `secrecy`, `zeroize` | Reduce accidental secret exposure and clear owned buffers | Current small crates; custom wrappers are possible but easier to misuse | No | Narrows secret exposure |
| `rusqlite` with bundled SQLite | Disposable schema/isolation Spike and future local storage | Current release line; system SQLite would reduce reproducibility | Yes, bundled SQLite C code | Local database files only; credentials remain excluded |
| `windows` | Typed Windows Credential Manager, UIA, GDI, Event Log, process, and port APIs | Official Microsoft projection; direct FFI is the higher-risk alternative | Links Windows system libraries | Adds only explicitly selected Win32 API feature sets; no input injection, registry write, or shell API |
| `sysinfo` | Read-only process metadata fallback | Current release line; direct Win32-only implementation is an alternative | Platform-specific Rust code | Read-only process inspection |
| `png` | In-memory encoding of one explicitly selected window | Current focused crate; Windows Imaging Component is an alternative | No external library | No disk write; bounded pixel allocation |
| `quick-xml` | Bounded Event Log XML parsing | Current release line; manual parsing is unsafe | No | Parses only returned event XML |
| `regex` | Local redaction and bounded format checks | Widely maintained; manual scanners are possible but error-prone | No | Reduces disclosure risk |
| `serde`, `serde_json`, `toml`, `yaml-rust2` | Typed protocol and bounded configuration fixtures | Active ecosystem crates; handwritten parsers are higher risk | No | Parsing only; file access remains separately authorized |
| `sha2` | File transaction verification | Current cryptographic primitive crate; platform hashing APIs are an alternative | No | Read-only hashing of authorized fixture data |
| `uuid`, `time`, `url` | Identifiers, timestamps, and URL validation | Active ecosystem crates; custom implementations would increase ambiguity | No | Validation and metadata only |
| `thiserror`, `tracing`, `tracing-subscriber` | Structured errors and sanitized diagnostics | Active ecosystem crates; standard-library-only alternatives are more verbose | No | Logs must still pass redaction rules |
## Protocol and Mock-only dependencies
| Dependency | Purpose | Maintenance and alternatives | Native compile | Permission or attack-surface effect |
| ------------------------------ | ------------------------------------------------------- | ---------------------------------------------------------------------- | -------------------------- | ------------------------------------------------------------------------ |
| `schemars` | Export checked JSON Schema from canonical Rust types | Active release line; handwritten schema is the drift-prone alternative | No | Build/test tooling only |
| `ts-rs` | Export TypeScript protocol types | Active release line; handwritten duplication is the alternative | No | Build/test tooling only |
| `axum`, `async-stream`, `clap` | Loopback-only dual Mock Gateway and CLI | Active release lines; custom HTTP server code is riskier | No external native library | Mock refuses non-loopback bind addresses and is not a release dependency |
| `tempfile` | Disposable database, log, and file-transaction fixtures | Active release line; manual temp naming is less safe | No | Test-only generated paths |
## Review outcome
- No dependency exposes arbitrary PowerShell, CMD, shell, keyboard, mouse, registry-write, or unrestricted filesystem execution.
- Native compilation is limited to the mandated Tauri/Windows stack and bundled SQLite.
- Mock and test dependencies do not enter the release dependency graph.
- Dependency updates require lockfile review, the full P00 check set, and a repeat of affected Windows Spikes.

36
docs/implementation-plan.md 普通文件
查看文件

@ -0,0 +1,36 @@
# P00 Bootstrap Implementation Plan
## Objective
Establish a reproducible Tauri 2 + React + TypeScript + Rust baseline and complete the high-risk technical Spikes required before formal feature development.
## Ordered work
1. Normalize repository documents and Git metadata on `main`.
2. Verify Forgejo is empty before the first `main` push; never overwrite remote history.
3. Create `feat/p00-bootstrap` from the pushed `main` baseline.
4. Establish the Tauri 2 application and typed frontend-to-Rust IPC.
5. Implement two independent REST/SSE clients and a dual-instance Mock Gateway.
6. Verify Windows secure credential CRUD without exposing secret values to React or logs.
7. Verify bounded Windows diagnostics: foreground window, UI Automation, selected-window capture, process information, event logs, ports, network targets, authorized log tails, configuration parsing, and redaction.
8. Verify NAS transactions only in a dedicated generated fixture directory: dry run, temporary copy, size/hash verification, atomic commit, conflict handling, interruption recovery, and source preservation.
9. Define protocol schemas and capability negotiation types.
10. Add frontend, Rust, integration, and Forgejo CI checks.
11. Run and record all checks, commit by independently verifiable increments, and push the feature branch without merging `main`.
## Safety gates
- No arbitrary command execution is exposed by product code.
- No real credential is used in fixtures, logs, snapshots, or commits.
- No NAS Spike touches an existing user file or directory.
- No remote branch is changed until `git ls-remote` succeeds and remote history is reviewed.
- No test or build is marked successful without captured execution results.
## Current handoff status
- Rust/MSVC/Tauri are verified and no longer block local work.
- Git Credential Manager reauthentication succeeded and the non-forced HTTP push created the remote `main` baseline at `0d12b94`.
- Development is active on `feat/p00-bootstrap`; the remaining repository handoff step is a normal push of this feature branch.
- The configured SSH fetch endpoint still refuses connections and the LAN SSH endpoint rejects the available key, but the approved HTTP push URL is operational.
- Forgejo runner labels/jobs remain unverified, so the committed workflow is not claimed successful.
- Real UNC execution still requires a user-authorized disposable fixture.

72
docs/progress.md 普通文件
查看文件

@ -0,0 +1,72 @@
# Development Progress
## Current phase
P00 bootstrap implementation and high-risk Spike verification is complete; the feature branch is published and awaiting user PR review.
## Completed
- Read `AGENTS.md` and all authoritative architecture, implementation, and Forgejo workflow documents.
- Verified the Windows, Git, Node.js, package-manager, WebView2, Rust, Tauri, and MSVC environment.
- Initialized a local Git repository on `main`.
- Configured `origin` as `ssh://git@localhost:18086/YokiiroBW/AstrBot-Desktop.git`.
- Verified through authenticated Forgejo API and HTTP Git that the remote repository existed, was empty, used `main`, and granted push permission before the baseline push.
- Reauthenticated through Git Credential Manager and non-forced pushed the `main` baseline to Forgejo at `0d12b94`.
- Created and switched to `feat/p00-bootstrap` from the pushed `main` baseline.
- Built the Tauri 2 + React + TypeScript + Rust skeleton with tray, single-instance, CSP, and minimal `core:default` capability.
- Implemented independent companion/operations REST and SSE clients and passed the corrected 30-minute soak.
- Implemented and tested Windows Credential Manager, UI Automation, selected-window capture, Event Log, process, port, foreground-window, authorized log-tail, configuration parsing, and redaction Spikes.
- Implemented and tested composite-key SQLite isolation and recoverable local file transactions with source preservation.
- Added provisional protocol types, ten JSON Schemas, TypeScript exports, drift checks, and two loopback-only Mock Gateway instances.
- Added frontend, Playwright, Rust, integration, Windows-provider, soak, and Forgejo CI entry points.
- Built the Windows release executable and SHA-256-recorded NSIS installer.
- Added dependency, Spike, progress, changelog, and pending-decision records.
- Committed the implementation, test, and CI increments with Conventional Commit subjects.
## In progress
- Preparing the final PR draft and handoff report without merging `main`.
## Remaining
- Open and review the Forgejo PR from `feat/p00-bootstrap` to `main`; do not merge automatically.
- Run the Forgejo workflow when a compatible runner is available.
- Execute a real UNC transaction only after an authorized disposable fixture is supplied.
- Add the combined end-to-end test that keeps configured streams active while the real Tauri window is hidden to tray.
## Blockers
- Configured Forgejo SSH `localhost:18086` refuses connections.
- LAN SSH `192.168.31.210:18086` responds but rejects the available public key.
- HTTP Git push is operational after Git Credential Manager reauthentication and is no longer a blocker.
- Forgejo runner labels/jobs could not be verified; the jobs API endpoint returned 404.
## Test status
- `pnpm check:frontend`: passed; 1 Vitest test and production Vite build.
- `pnpm test:e2e`: passed; 1 Chromium smoke test.
- Rust fmt/check/Clippy with warnings denied: passed.
- `cargo test --workspace`: 40 passed, 2 explicit manual tests ignored.
- Controlled Windows UIA/PrintWindow smoke: 1 passed.
- Corrected dual-SSE soak: 1800.02 seconds, 1800 companion events, 1801 operations events, passed.
- Protocol Schema drift check: passed.
- Tauri development smoke, release executable, and NSIS installer build: passed.
- pnpm 11.9.0 frozen lockfile-only validation: passed using a local temporary store to avoid the pnpm UNC project-registry limitation.
- Forgejo CI and a real UNC transaction were not executed and are not claimed successful.
## Current branch
`feat/p00-bootstrap`
## Recent commits
- `5e6e8d5 docs(project): add architecture and implementation specifications`
- `0d12b94 chore(repo): initialize repository and ignore rules`
- `01607c6 feat(p00): add Tauri desktop spike foundation`
- `69b432b test(p00): add frontend browser rust and windows checks`
- `d4af979 ci(forgejo): add portable and windows quality workflows`
- `353a439 docs(p00): record spike results and unresolved boundaries`
## Next step
Provide the verified test report and PR draft. The user can then review the Forgejo diff and decide whether to merge; `main` remains unchanged by this workflow.

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"
}

查看文件

@ -0,0 +1,130 @@
# P00 Bootstrap Verification and PR Draft
Date: 2026-07-18
## Delivery status
Local implementation and verification are complete. Git Credential Manager reauthentication succeeded, the `main` baseline was pushed non-forced to Forgejo at `0d12b94`, and `feat/p00-bootstrap` was published and verified at `353a439`.
Implementation, test, CI, and documentation increments are committed on the feature branch. Forgejo CI has not run because runner availability remains unverified; no CI success is claimed.
No merge to `main` has been performed.
## Environment
- Windows NT 10.0.26100.0, PowerShell 5.1.26100.7920
- Git 2.54.0.windows.1
- Node.js 24.17.0, npm 11.13.0, pnpm 11.9.0
- rustc/cargo 1.97.1
- Tauri CLI 2.11.4, Tauri crate 2.11.5
- WebView2 Runtime 131.0.2903.86
- MSVC link environment verified by debug/release and NSIS builds
## Completed scope
- Tauri 2 + React + TypeScript + Vite + Rust skeleton, tray, single-instance, CSP, and minimal capability configuration.
- Two independent companion/operations REST and SSE clients with local profile binding, state, cancellation, reconnect, Last-Event-ID, and deduplication.
- Windows Credential Manager CRUD with generated fake credentials and cleanup.
- Bounded UI Automation, selected-window in-memory PrintWindow capture, closed-window identity rejection, Event Log, process, port, foreground-window, authorized log-tail, configuration parsing, and redaction Spikes.
- Composite-key SQLite isolation.
- Recoverable plan/dry-run/copy/size+SHA-256 verify/atomic commit file transactions with ask/rename/skip and source preservation.
- Provisional desktop-v1alpha1 protocol types, TypeScript exports, ten JSON Schemas, and dual loopback Mock Gateway.
- Frontend, browser, Rust, integration, Windows-provider, soak, and Forgejo CI entry points.
- Dependency review, Spike reports, progress records, and changelog.
## Test report
| Check | Result |
| ------------------------------------------------------- | ------------------------------------------------------------------------------ |
| pnpm frozen lockfile-only validation | Passed with pnpm 11.9.0 and a local temporary store; no dependency scripts run |
| Frontend format, ESLint, TypeScript, Vitest, Vite build | Passed; 1 Vitest test |
| Playwright Chromium smoke | Passed; 1 test |
| cargo fmt --all -- --check | Passed |
| cargo check --workspace --all-targets | Passed |
| cargo clippy --workspace --all-targets -- -D warnings | Passed |
| cargo test --workspace | Passed; 40 tests, 2 explicit manual tests ignored |
| Controlled Windows UIA/PrintWindow smoke | Passed; 1 test, 0.12 seconds |
| Protocol Schema drift check | Passed |
| Corrected dual-SSE soak | Passed; 1800.02 seconds, companion 1800, operations 1801 |
| Tauri development launch | Passed; `AstrBot Desktop` window responsive and safely stopped |
| Tauri release executable | Passed |
| Tauri NSIS installer | Passed |
Soak resource samples:
- Working set: approximately 11.4-12.1 MiB.
- Private memory: approximately 2.0-2.4 MiB.
- Final pre-exit cumulative CPU: 1.38 seconds.
- No cross-routing assertion, stream stall, or failed shutdown in the corrected run.
NSIS artifact:
- File: `AstrBot Desktop_0.1.0-alpha.0_x64-setup.exe`
- Size: 3,552,257 bytes
- SHA-256: `BF87DCD13B81C18EFC9A2DB8DE6E201396FFBB9ABA0EABC579A22479C004816C`
## Security review
- Tauri window capability contains only `core:default`.
- No shell plugin or product API for PowerShell, CMD, arbitrary shell, input injection, registry write, or unrestricted filesystem execution exists.
- Credential values remain in Rust/Windows Credential Manager; React has no credential read command.
- Repository secret scan found only the documented redaction example and deliberate fake test fixtures.
- File-transaction deletion calls are limited to transaction-owned temporary destination files and generated test-fixture cleanup; P00 never deletes the source.
- No real UNC path, NAS credential, signing key, updater key, private key, or production token was used.
## Unresolved issues
1. `ssh://git@localhost:18086/...` refuses connections.
2. `ssh://git@192.168.31.210:18086/...` responds but rejects the available key; approved HTTP push is the working transport.
3. Forgejo CI has not run; runner jobs/labels could not be verified and the jobs API returned 404.
4. Real UNC/SMB behavior is not tested because no authorized disposable fixture was provided.
5. A real elevated or custom-drawn window remains a manual UIA/capture boundary test.
6. The connection layer and tray lifecycle passed separately; configured Gateway sessions are not yet wired into Tauri setup for a combined tray-hidden end-to-end run.
7. Real AstrBot Gateway protocol compatibility is unverified; desktop-v1alpha1 remains provisional.
8. Code signing, updater signing, updater endpoint, and release publication remain outside P00.
9. pnpm 11 project registration cannot create its store symlink when the project/store are on this UNC share; local temporary store plus frozen-store is the verified lockfile-only workaround.
## Commit list
Branch commit sequence:
1. `5e6e8d5 docs(project): add architecture and implementation specifications`
2. `0d12b94 chore(repo): initialize repository and ignore rules`
3. `01607c6 feat(p00): add Tauri desktop spike foundation`
4. `69b432b test(p00): add frontend browser rust and windows checks`
5. `d4af979 ci(forgejo): add portable and windows quality workflows`
6. `353a439 docs(p00): record spike results and unresolved boundaries`
7. `docs(p00): record Forgejo branch publication`
## Forgejo PR title
`feat(p00): bootstrap Tauri desktop and validate high-risk spikes`
## Forgejo PR body
### Summary
- bootstrap the Tauri 2 + React + TypeScript + Rust desktop workspace;
- add isolated companion and operations REST/SSE clients and dual Mock Gateway;
- add provisional protocol Schema, Windows secure/native Spikes, SQLite isolation, and recoverable file transactions;
- add frontend, browser, Rust, Windows, soak, and Forgejo CI checks.
### Verification
- frontend quality/build and Chromium smoke pass;
- Rust fmt/check/Clippy and 40 normal tests pass;
- controlled UIA/PrintWindow smoke passes;
- corrected 30-minute dual-SSE soak passes with 1800/1801 isolated events;
- Tauri development launch, release executable, and NSIS installer build pass.
### Known boundaries
- Forgejo CI is not yet executed;
- real UNC, elevated/custom-drawn window, real AstrBot Gateway, signing, and updater verification remain pending;
- connection tasks are not yet wired into a combined real tray-hidden session test.
### Safety
- no arbitrary shell or unrestricted desktop/filesystem capability;
- no real credentials or destructive source-file operations;
- no force push and no automatic merge to `main`.

查看文件

@ -0,0 +1,70 @@
# P00-01: Dual REST and SSE Connections
- Status: Connection isolation and 30-minute soak passed; end-to-end tray-hidden wiring remains pending
- Date recorded: 2026-07-18
- MVP gate: Required before formal dual-connection development
## Objective
Verify that one Tauri process can maintain independent companion and operations REST/SSE sessions while the main window is hidden, without event mixing or shared failure state.
## Environment
- Host: Windows 11 x64
- Mock transport: loopback only
- Rust toolchain: rustc/cargo 1.97.1
- MSVC C++ build tools: verified by native builds
- Forgejo: HTTP Git reachable and baseline pushed; no CI result exists
## Minimal validation implementation
The Spike is expected to provide:
- Two independently constructed REST clients.
- Two independently constructed SSE clients.
- Local companion and operations profile bindings.
- Per-session cancellation, retry, Last-Event-ID, and deduplication state.
- A dual-instance Mock Gateway with health, server-info, capabilities, authentication, SSE, disconnect, and duplicate-event controls.
- Sanitized metrics and state snapshots.
The Rust connection object must overwrite or ignore any remote profile_id when producing a locally routed event.
## Required execution
1. Start Mock A and Mock B on loopback using dynamically allocated ports.
2. Connect both slots and confirm independent health and capability responses.
3. Stream uniquely attributable events from both mocks.
4. Inject identical conversation_id, message_id, and event payload values.
5. Inject a conflicting remote profile_id and confirm the local binding wins.
6. Replay an event_id and confirm it is delivered once.
7. Stop A, verify B continues, then repeat in the other direction.
8. Hide the main window to the tray and verify both streams continue.
9. Run a 30-minute soak and record CPU, memory, reconnect count, event count, and duplicates suppressed.
## Actual execution result
Passed for the isolated connection layer. Two loopback Mock Gateways and two independent Rust GatewayClients verified local profile binding, per-slot state/cancellation/Last-Event-ID/deduplication, duplicate suppression, server identity checks, one-slot disconnect/reconnect, and continued events from the unaffected slot.
The first long run completed the event loop but exposed a test-harness shutdown defect: the two SSE Response values were still alive when graceful Mock shutdown began. The run was correctly recorded as failed, the streams were explicitly dropped before shutdown, event-count output was added, and the full test was restarted from zero.
The corrected soak passed after 1800.02 seconds with 1800 companion events and 1801 operations events and no server-instance cross-routing assertion. Process samples ranged from about 11.4 to 12.1 MiB working set, about 2.0 to 2.4 MiB private memory, and 1.38 seconds cumulative CPU at the final pre-exit sample.
Tauri development launch, tray creation, close-to-hide handling, and process responsiveness were verified separately. P00 does not yet wire saved Gateway profiles into the application setup, so a combined end-to-end run that hides the real Tauri window while these two configured streams remain active is still pending formal connection integration.
## Log summary
Commands: `cargo test --workspace` and `cargo test -p mock-gateway --test soak -- --ignored --nocapture`. Results: connection/reconnect/dedup integration tests passed; corrected soak passed with the counts and resources above.
## Known limitations
- Real AstrBot Gateway compatibility is unverified.
- The provisional protocol may change after a real Gateway review.
- A loopback Mock does not validate TLS, proxy, certificate, or real-network behavior.
## Security impact
Profile binding at the Rust connection boundary is mandatory. A merged SSE stream or remote-controlled profile identity could route an operations proposal to the wrong local policy context.
## Recommendation
Keep connection ownership per slot and add deterministic clock/backoff injection for unit tests. Do not proceed to formal dual-chat UI until the isolation, failure, and soak checks have recorded results.

查看文件

@ -0,0 +1,59 @@
# P00-02: Windows Credential Manager
- Status: Passed on the audited Windows host
- Date recorded: 2026-07-18
- MVP gate: Required before storing any AstrBot or NAS credential
## Objective
Verify create, read, update, and delete operations for a test-only generic credential while keeping the secret value inside Rust and outside React, ordinary SQLite fields, logs, snapshots, and repository files.
## Environment
- Host: Windows 11 x64
- Secure store target: Windows Credential Manager
- Rust toolchain: rustc/cargo 1.97.1
- MSVC C++ build tools: verified by Rust and Tauri native builds
- Administrative elevation: not permitted or required
## Minimal validation implementation
The Spike is expected to expose typed Rust operations that accept a logical credential reference and return metadata or an opaque reference. Secret bytes must use bounded lifetimes and must not implement debug output that reveals their value.
React may request save, replace, existence, and delete operations, but a read operation must not return the credential value across Tauri IPC.
## Required execution
1. Create a uniquely named test-only credential containing a fake generated value.
2. Read it in Rust and compare without printing the value.
3. Replace it and confirm the old value is no longer returned.
4. Delete it and confirm a structured not-found result.
5. Verify missing, denied, oversized, and malformed-reference error paths.
6. Scan application logs, frontend state, SQLite data, snapshots, and terminal output for the fake value.
7. Confirm the test credential is removed at the end.
## Actual execution result
Passed. The Windows-only Rust test created a uniquely named generic credential containing a generated fake value, read it inside Rust, replaced it, confirmed the replacement, deleted it, and confirmed the deleted value was unavailable. The cleanup path ran even when an assertion would fail, and a post-run check found no remaining test credential.
Reference and size validation tests cover empty, malformed, and oversized inputs before native access. The public secure-store surface returns metadata or an opaque reference; it does not expose the secret through Tauri IPC or React.
The workspace secret scan reported only the security-rule example in `AGENTS.md` and deliberate fake redaction fixtures. No real credential, Authorization header, private key, or NAS secret was found.
## Log summary
Command: `cargo test --workspace` on Windows, including the Credential Manager CRUD test. Result: passed. Terminal output contained only test names and result categories; the generated fake secret was never printed.
## Known limitations
- Windows Credential Manager behavior cannot be certified by Linux CI.
- Locked sessions, policy restrictions, roaming behavior, and credential-size limits still require Windows tests.
- NAS authentication integration is outside this isolated CRUD Spike.
## Security impact
Failure would block all authenticated AstrBot and NAS connections. Falling back to plaintext configuration, SQLite, environment files, or logs is prohibited.
## Recommendation
Use the Windows-native credential APIs behind a narrow Rust trait. Persist only a credential reference. Treat inability to access secure storage as an explicit user-visible error rather than a reason to weaken storage.

查看文件

@ -0,0 +1,64 @@
# P00-03: UI Automation and Selected-Window Capture
- Status: Passed for a controlled non-elevated standard dialog; elevated/custom-drawn manual coverage remains
- Date recorded: 2026-07-18
- MVP gate: Required for bounded error-window diagnostics
## Objective
Verify read-only extraction from a standard Windows dialog and a user-selected, single-window capture fallback without running the application as administrator or broadening access to the desktop.
## Environment
- Host: Windows 11 x64
- Target class: standard non-elevated Windows dialog
- Rust toolchain: rustc/cargo 1.97.1
- MSVC C++ build tools: verified by the Windows test and Tauri build
- Elevated target testing: negative boundary only
## Minimal validation implementation
The Spike is expected to:
- Identify the current foreground window.
- Return bounded title, process, and UI Automation text fields.
- Report unsupported, inaccessible, closed, or elevated targets safely.
- Capture only the window explicitly selected by the user.
- Keep image bytes in Rust until a display-safe preview is produced.
- Delete transient capture data after the diagnostic flow unless the user explicitly saves it.
## Required execution
1. Open a standard non-elevated dialog with known text.
2. Read its title and UI Automation text.
3. Verify an unsupported or custom-drawn window produces a structured fallback result.
4. Select one window and capture only its client/window bounds.
5. Verify a closed or invalid handle does not capture another window.
6. Attempt an elevated target and confirm a safe access-denied result without elevation.
7. Confirm transient image data is removed after the test.
## Actual execution result
The ignored Windows smoke test opened a test-owned standard MessageBox containing fixed, non-sensitive text. It selected only that foreground HWND, verified title and process identity, read the expected title/body through UI Automation, captured the same selected window through PrintWindow, and validated an in-memory PNG without writing image bytes to disk.
The test then closed the controlled dialog and verified that the expired HWND identity returned `WindowChanged` and could not capture a replacement window. The test passed in 0.12 seconds.
An elevated target was not created because that would require a UAC/elevation action outside this bounded Spike. The implementation maps access denied and element-unavailable HRESULTs to structured errors, but a real elevated/custom-drawn target remains an explicit manual boundary test.
## Log summary
Command: `cargo test -p astrbot-desktop --test windows_dialog_smoke -- --ignored --nocapture`. Result: 1 passed. Output contained test status only; no extracted text or pixel bytes were logged or persisted.
## Known limitations
- UI Automation does not expose all custom-rendered content.
- Protected, elevated, DRM, or hardware-accelerated windows may reject inspection or capture.
- DPI scaling and multi-monitor coordinates require explicit tests.
## Security impact
Window content can contain personal or secret data. Capture must be user-selected, bounded to one target, previewable, and excluded from durable logs.
## Recommendation
Keep UI Automation as the preferred text path and selected-window capture as an explicit fallback. Do not add continuous desktop capture, global hooks, input injection, or privilege escalation.

查看文件

@ -0,0 +1,61 @@
# P00-04: Event Log and Read-Only Diagnostics
- Status: Passed for bounded local and loopback diagnostics
- Date recorded: 2026-07-18
- MVP gate: Required before exposing local diagnostic tools
## Objective
Verify bounded, read-only collection of Windows event summaries, process and foreground-window metadata, port occupancy, network-target reachability, authorized log tails, configuration parsing, and local redaction.
## Environment
- Host: Windows 11 x64
- Rust toolchain: rustc/cargo 1.97.1
- MSVC C++ build tools: verified by native builds
- Network targets: no production target authorized for this Spike
- Event-log scope: explicit provider and time range only
## Minimal validation implementation
Each diagnostic operation must have a typed argument schema and explicit limits. It must return structured summaries, not arbitrary command output or unrelated full logs.
File reads must require a user-authorized path token, enforce size limits, prefer log tails, reject binary content, and redact before any preview or upload.
## Required execution
1. Query a known provider over a short time window and return a bounded summary.
2. Apply provider, time, level, and optional process filtering.
3. Inspect one explicitly identified process without controlling it.
4. Check one port and one explicitly supplied network target.
5. Read the tail of a disposable authorized log fixture.
6. Parse JSON, YAML, TOML, and INI fixtures with limits.
7. Redact fake tokens, passwords, cookies, API keys, URL credentials, connection-string passwords, and PEM material.
8. Verify invalid provider, permission denial, timeout, malformed file, and oversized input errors.
## Actual execution result
Passed. Windows-native tests executed a bounded recent Event Log query, inspected the current process and foreground-window metadata, identified the owner PID of a test-created TCP listener, and exercised structured error handling.
Disposable local fixtures verified authorized log-tail reads, JSON/YAML/TOML/INI parsing limits, binary/oversized rejection, and redaction of fake bearer tokens, passwords, cookies, API keys, URL credentials, connection-string secrets, and PEM material.
Network reachability coverage is limited to explicit loopback fixtures; no production or user network target was contacted.
## Log summary
Commands: `cargo test --workspace` plus the Windows native-provider tests. Result: passed. Event content and fake secrets were not printed; only bounded result categories and test status were retained.
## Known limitations
- Some event channels require permissions unavailable to a standard user.
- Provider names and event schemas vary by installed software.
- Reachability is not proof that an application protocol is healthy.
- Parser support does not authorize arbitrary file access.
## Security impact
Overbroad queries can disclose unrelated personal or security information. Every diagnostic must be locally authorized, scope-limited, and redacted before leaving Rust.
## Recommendation
Implement independent typed tools rather than a generic diagnostics command. Keep all Windows queries read-only and return partial results with explicit access boundaries.

查看文件

@ -0,0 +1,70 @@
# P00-05: NAS File Transaction
- Status: Local transaction and recovery passed; real UNC execution blocked by missing authorized fixture
- Date recorded: 2026-07-18
- MVP gate: Required before any NAS write feature
## Objective
Verify a recoverable UNC transaction using plan, dry run, temporary copy, size and SHA-256 verification, atomic destination commit, conflict handling, and interruption recovery while preserving the source.
## Environment
- Host: Windows 11 x64
- Authorized UNC fixture: not supplied
- Rust toolchain: rustc/cargo 1.97.1
- MSVC C++ build tools: verified by native builds
- Real user or production files: prohibited
## Minimal validation implementation
The Spike is expected to operate only on a user-authorized disposable source fixture and destination share. It must:
- Tokenize the selected source path.
- Reject paths outside the authorized source and destination roots.
- Produce a non-mutating dry-run plan.
- Copy to a unique temporary destination.
- Verify byte count and SHA-256.
- Commit by renaming within the destination filesystem.
- Apply ask, rename, or skip conflict policy without overwrite.
- Persist resumable transaction state without credentials.
- Preserve the source in every P00 outcome.
## Required execution
1. Obtain explicit user authorization for disposable source and UNC destination fixtures.
2. Generate unique test data inside the fixture.
3. Execute and inspect a dry run.
4. Copy to a temporary destination and verify size and SHA-256.
5. Commit to the final name and confirm the source still exists.
6. Exercise ask, rename, and skip conflicts.
7. Interrupt during copy and verify no final destination is exposed.
8. Resume or restart safely and verify source preservation.
9. Inject hash mismatch and confirm no commit or cleanup occurs.
## Actual execution result
The transaction implementation and disposable local-fixture tests passed. They cover non-mutating plan/dry-run, copy to a unique temporary name, byte-count and SHA-256 verification, atomic final rename, ask/rename/skip conflict behavior without overwrite, injected interruption and hash mismatch, restart-safe state, and source preservation.
No real UNC path was read or written. The user did not identify an authorized disposable source directory and destination share, so executing the same flow against a NAS would violate the project safety rule.
This is an environment/authorization block for the UNC transport check, not a claim that SMB interruption behavior passed.
## Log summary
Command: `cargo test --workspace` on generated temporary directories. Result: passed. No source fixture was deleted, no existing destination was overwritten, and no NAS credential was used or logged.
## Known limitations
- Atomic rename guarantees depend on the destination filesystem and share behavior.
- Network interruption and SMB caching can affect observability.
- P00 does not validate recycle-bin or source-cleanup behavior.
- Performance on large files remains unmeasured.
## Security impact
Silent overwrite or premature source cleanup can cause data loss. Credentials must remain in Windows secure storage, and remote payloads must never provide unrestricted local or UNC paths.
## Recommendation
Do not enable NAS writes until this Spike has executed against a disposable authorized share. P00 must preserve sources and treat source cleanup only as a non-executed plan field.

查看文件

@ -0,0 +1,59 @@
# P00-06: SQLite Profile Isolation
- Status: Passed on a disposable SQLite database
- Date recorded: 2026-07-18
- MVP gate: Required before persistent dual-instance data
## Objective
Verify schema and repository isolation for multiple saved profiles and two active slots, including collisions in server, conversation, message, cursor, proposal, and transaction identifiers.
## Environment
- SQLite implementation: rusqlite 0.40.1 with bundled SQLite
- Rust toolchain: rustc/cargo 1.97.1
- Migration execution: transactional disposable fixture
- Persistent user database: not created
## Minimal validation implementation
The Spike is expected to use a disposable database and transactional migrations. Server-derived tables must include profile_id and server_instance_id. Conversation and message keys must remain unique within their profile and server context.
Credential values must never be stored; only opaque credential references are permitted.
## Required execution
1. Create at least five profiles with only two active slots.
2. Store identical conversation_id and message_id values for two different profiles.
3. Store independent SSE cursors, unread counts, errors, proposals, and transaction summaries.
4. Query each profile and verify no cross-profile result.
5. Verify a duplicate within the same composite key is rejected or deterministically updated.
6. Verify credential values are absent from all tables.
7. Interrupt a transaction and confirm rollback or recovery.
8. Reopen the database and repeat isolation checks.
## Actual execution result
Passed. Tests created multiple saved profiles with only companion and operations active slots, inserted intentionally colliding server/conversation/message identifiers under different composite profile keys, and verified independent reads.
Tests also covered separate SSE cursors, unread/error state, proposals and file-transaction summaries, duplicate composite-key behavior, transaction rollback, reopen/requery behavior, and schema inspection confirming that credential values are absent.
All database files were disposable test fixtures; no migration touched user data.
## Log summary
Command: `cargo test --workspace`. Result: passed, including SQLite migration and isolation tests. Logs contained test status only and no stored content values.
## Known limitations
- Migration backup and recovery behavior remain unverified.
- WAL behavior on abrupt process termination remains unverified.
- Encryption at rest is not provided by ordinary SQLite and does not replace Credential Manager.
## Security impact
Incorrect composite keys can mix conversations or local-tool state between companion and operations profiles. Storing credential values would violate the security model.
## Recommendation
Use transactional migrations, foreign keys, explicit composite uniqueness, and a disposable database for isolation tests. Any migration with potential data loss requires a separate stop-and-review decision.

查看文件

@ -0,0 +1,59 @@
# P00-07: Protocol Schema and Dual Mock Gateway
- Status: Passed for the provisional desktop-v1alpha1 contract
- Date recorded: 2026-07-18
- MVP gate: Required for repeatable connection and policy tests
## Objective
Define a provisional desktop-v1alpha1 protocol and verify two independently configurable Mock Gateway instances without claiming compatibility with an unavailable real AstrBot Gateway.
## Environment
- Forgejo API and HTTP Git endpoint reachable; SSH origin remains unusable
- Real AstrBot Gateway: not connected
- Package dependencies: installed from pnpm/Cargo lockfiles
- Mock execution: two loopback instances verified
## Minimal validation implementation
The provisional schema must cover ConnectionProfile, ConnectionSlot, ConnectionState, ServerCapabilities, ClientCapabilities, ProtocolEnvelope, GatewayEvent, ToolProposal, ToolResult, DiagnosticBundle, and FileTransferPlan.
The Mock Gateway must expose health, server information, capabilities, fake authentication, SSE, proactive messages, disconnect injection, duplicate events, companion messages, and operations tool proposals. It must support two simultaneous instances with independent identity and behavior.
## Required execution
1. Validate representative valid fixtures against every schema.
2. Reject missing, unknown, malformed, oversized, and wrong-version fields as defined by policy.
3. Start two mocks on dynamic loopback ports.
4. Verify independent server_instance_id and capabilities.
5. Exercise authentication success and failure with fake values.
6. Stream normal, duplicate, delayed, disconnected, and tool-proposal events.
7. Confirm companion-origin tool proposals are rejected by the client policy boundary.
8. Record any divergence found during a later real Gateway review.
## Actual execution result
Passed for the provisional contract. The canonical Rust protocol package exports ten JSON Schemas and TypeScript types. Valid/invalid fixtures, unknown-field rejection, protocol-version checks, and schema drift checks passed.
Two independently configured loopback Mock Gateways passed health, server-info, capability, fake-auth success/failure, SSE, duplicate-event, disconnect/reconnect, proactive companion message, and operations tool-proposal tests.
Client integration tests verified local Rust-side profile binding, independent event-id deduplication, identical remote identifiers without cross-routing, and one-slot reconnect while the other slot continued. Compatibility with a real AstrBot Gateway remains explicitly unclaimed.
## Log summary
Commands: protocol contract/schema tests, Mock Gateway tests, and `cargo test --workspace`. Results: 5 protocol tests, 4 Mock Gateway integration tests, and the wider Rust suite passed. Only generated fake credentials were used.
## Known limitations
- Endpoint names, authentication fields, ACK behavior, event retention, error codes, and capability names are provisional.
- Mock success cannot prove interoperability with AstrBot.
- Loopback HTTP tests do not validate production TLS or certificate identity.
## Security impact
Schemas form the first validation boundary for untrusted remote data. Mock convenience behavior must not weaken production parsing, profile binding, role checks, or TLS validation.
## Recommendation
Version the schema explicitly, keep invalid fixtures alongside valid ones, and require a real Gateway contract review before declaring protocol compatibility.

查看文件

@ -0,0 +1,70 @@
# P00-08: Build, CI, and Release Readiness
- Status: Local Windows build passed; Forgejo CI, signing, and updater release configuration remain pending
- Date recorded: 2026-07-18
- MVP gate: Required before declaring P00 complete
## Objective
Verify reproducible frontend, Rust, Tauri development, Windows production-build, Forgejo CI, installer, updater, and signing prerequisites without creating temporary release credentials or claiming unexecuted jobs passed.
## Environment
- Node.js: 24.17.0 detected
- pnpm: 11.9.0 detected
- Rust/Cargo: 1.97.1 detected and verified
- MSVC C++ build tools: verified by debug and release links
- WebView2: previously detected
- Forgejo SSH endpoint: connection refused at localhost:18086
- Forgejo runner labels: unknown
- Windows code-signing certificate: not configured
- Tauri updater signing key and endpoint: not configured
## Minimal validation implementation
The repository pins Node, pnpm, Rust, direct JavaScript dependencies, and lockfiles. Local scripts cover frontend and Rust checks. Forgejo CI provides:
- A portable Linux quality job for frontend, workspace, and Rust checks.
- A Windows Tauri job guarded by the ENABLE_WINDOWS_TAURI_CI repository variable.
- No publication, release upload, or long-lived secret use.
## Required execution
1. Install dependencies from committed lockfiles.
2. Run frontend format, lint, typecheck, unit tests, and production build.
3. Run Rust fmt, Clippy with warnings denied, tests, and check.
4. Start Tauri development mode on Windows and verify IPC plus tray hide/restore.
5. Run the Windows Tauri production build.
6. Inspect Forgejo runner labels and enable only jobs with verified prerequisites.
7. Run the Forgejo workflow and retain sanitized results.
8. Record installer bundle prerequisites.
9. Record code-signing and updater requirements without generating temporary production keys.
## Actual execution result
Local Windows validation passed: frontend format/lint/type/unit/build checks, Playwright Chrome smoke, Rust fmt/check/Clippy/tests, Tauri development launch, release executable build, and NSIS bundle generation all completed successfully.
The first two bundle attempts timed out while Tauri downloaded its official NSIS archive. The official tauri-bundler 2.9.4 source confirmed the standard cache path and embedded SHA-1 values. The NSIS 3.11 archive and nsis-tauri-utils 0.5.3 DLL were then downloaded from their official Tauri release URLs, matched the embedded SHA-1 values, installed into the standard cache, and the bundle succeeded.
Installer: `AstrBot Desktop_0.1.0-alpha.0_x64-setup.exe`, 3,552,257 bytes, SHA-256 `BF87DCD13B81C18EFC9A2DB8DE6E201396FFBB9ABA0EABC579A22479C004816C`.
Forgejo API confirmed the repository existed and was empty before initialization. Git Credential Manager reauthentication then enabled a normal, non-forced HTTP push of `main` at `0d12b94`, and `feat/p00-bootstrap` was created from that baseline. The configured SSH origin `localhost:18086` still refuses connections; the LAN SSH endpoint responds but rejects the available key. The workflow file has not run, and the action-runner jobs endpoint returned 404, so no CI success is claimed.
## Log summary
Local command logs support the Windows build claims. No Forgejo workflow, code-signing, updater-signing, or publication result exists.
## Known limitations
- The ubuntu-latest and windows-latest labels are assumptions until a Forgejo act_runner is inspected.
- Linux checks cannot certify Windows Credential Manager, UI Automation, Event Log, window capture, UNC behavior, tray behavior, or Windows bundling.
- Action availability and outbound registry access are unknown.
- Code signing and updater verification remain release-stage work.
## Security impact
CI must not receive AstrBot, NAS, SSH, signing, or updater secrets during P00. Action references should be pinned to reviewed commit hashes after runner connectivity is restored.
## Recommendation
Treat Windows local checks as mandatory until a trusted Windows runner is configured. Mark the Windows job skipped when the enabling variable is absent, and never interpret that skip as a successful Windows build.

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

@ -0,0 +1,5 @@
# Technical Spikes
Each Spike report must record its objective, environment, minimal implementation, actual commands and results, log summary, limitations, security impact, MVP blocking status, and recommended production approach.
Reports must distinguish verified behavior from planned or blocked work.

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"
}
}

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,
},
});

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

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