feat(connection): auto-connect configured slots
一些检测仍在等待运行
ci / Portable quality checks (push) Waiting to run
ci / Windows Tauri build (push) Waiting to run

这个提交存在于:
YokiiroBW 2026-07-20 12:01:18 +08:00
父节点 3d1d962461
当前提交 2e84ea52e9
共有 8 个文件被更改,包括 193 次插入 和 9 次删除

查看文件

@ -143,3 +143,10 @@ The ordered queue is maintained in docs/implementation-queue.md. The next implem
9. Q9 release hardening and acceptance build
The quick window and bubble are presentation surfaces over the same runtime; they must not create independent network clients or permission scopes.
## 2026-07-20 增量计划更新
1. 启动时读取并校验自动连接 Profile。
2. 按固定槽位独立激活 Rust-owned Runtime。
3. 为失败槽位保留可诊断状态,不影响另一槽位。
4. 补充检查结果并进入聊天运行时事件订阅。

查看文件

@ -143,3 +143,11 @@ remote_username 用于远端聊天身份和会话命名,不作为本机权限
- 最终确定 Companion/Operations 的远端用户名命名规则。
- 首批桌宠素材或授权素材包;在此之前使用测试 PNG/WebP。
- 如需 HTTPS 证书指纹绑定,提供可验证的 HTTPS 入口并确认首次信任交互。
## 2026-07-20 增量:启动自动连接
- 应用启动后由 Rust 读取已保存 Profile,仅处理 `auto_connect=true` 且绑定固定槽位的配置。
- `companion` 与 `operations` 逐槽位独立尝试,不因一个 Profile 凭据缺失、认证失败或服务不可用而跳过另一个槽位。
- API Key / Bearer Token 仍只在 Rust 启动任务和 Windows Credential Manager 之间流动;日志只记录 Profile、槽位和错误类别,不记录凭据或请求内容。
- 启动任务复用现有双槽位 Runtime,不创建额外网络客户端或权限范围。
- 当前仍未实现后台重连退避、JWT 登录和启动自动连接的前端可视化提示。

查看文件

@ -92,3 +92,12 @@ Completed in this increment:
Validation: Rust workspace tests passed (59 tests), Rust Clippy with warnings denied passed, Rust format check passed, TypeScript check passed, Vitest passed (6 tests), and Vite production build passed.
Still not claimed complete: automatic startup activation, real Tauri multi-window manual UX, long-duration reconnect soak, JWT login, attachment protocol, certificate pinning, actual Windows multi-monitor/game-mode integration, voice, and release installer validation.
## 2026-07-20:Q1 启动自动连接增量
- 已完成:在 Tauri 启动阶段读取已保存的 `auto_connect` Profile,并按 Companion / Operations 槽位独立激活。
- 已完成:启动失败保留在对应 Runtime 状态,不阻断另一槽位;凭据仍由 Rust 读取,React 不接触秘密值。
- 已完成:启动自动连接复用现有 AstrBot OpenAPI 与 Desktop Gateway 激活路径。
- 验证:`cargo check --workspace --all-targets`、`cargo test --workspace`(59 项通过)、`cargo clippy --workspace --all-targets -- -D warnings`、`pnpm.cmd run typecheck` 通过。
- 未完成:前端启动连接状态提示、自动重连退避、JWT 登录、聊天布局和快速窗口共享状态完善。
- 当前工作区:本地未提交,等待下一项 Q1/Q2 增量完成后按用户指令提交。

查看文件

@ -13,7 +13,7 @@ pub mod slots;
pub mod windows;
use database::ApplicationDatabase;
use networking::DualSlotRuntime;
use networking::{DualSlotRuntime, auto_connect_configured_slots};
use policy::ConnectionPolicyStatus;
use runtime_guards::RuntimeGuards;
use serde::Serialize;
@ -131,6 +131,13 @@ pub fn run() {
app.manage(RuntimeGuards::new());
app.manage(DualSlotRuntime::new());
let startup_handle = app.handle().clone();
tauri::async_runtime::spawn(async move {
let database = startup_handle.state::<ApplicationDatabase>();
let runtime = startup_handle.state::<DualSlotRuntime>();
auto_connect_configured_slots(&database, &runtime).await;
});
let show = MenuItem::with_id(app, "show", "Show AstrBot Desktop", true, None::<&str>)?;
let quit = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?;
let menu = Menu::with_items(app, &[&show, &quit])?;

查看文件

@ -4,6 +4,7 @@ use secrecy::SecretString;
use serde::Deserialize;
use serde_json::Value;
use tauri::State;
use tracing::{info, warn};
use super::{
ConnectionRuntimeStatus, DualSlotRuntime, RuntimeCommandError, SlotActivationRequest, SlotKind,
@ -55,6 +56,124 @@ pub async fn connection_runtime_status(
Ok(runtime.status().await)
}
/// Starts profiles explicitly marked for startup connection.
///
/// Each slot is attempted independently. A failure is retained in that slot's
/// runtime snapshot and does not prevent the other configured slot from being attempted.
pub async fn auto_connect_configured_slots(
database: &ApplicationDatabase,
runtime: &DualSlotRuntime,
) {
let profiles = match database.list_profiles() {
Ok(profiles) => profiles,
Err(error) => {
warn!(error = %error, "startup auto-connect could not read profiles");
return;
}
};
for profile in profiles.into_iter().filter(|profile| profile.auto_connect) {
let Some(active_slot) = profile.auto_connect_slot else {
warn!(profile_id = %profile.id, "startup auto-connect skipped profile without a slot");
continue;
};
let slot = match active_slot {
desktop_protocol::ActiveSlotKind::Companion => SlotKind::Companion,
desktop_protocol::ActiveSlotKind::Operations => SlotKind::Operations,
};
let profile_id = profile.id.clone();
let activation = match startup_activation_request(database, &profile, slot) {
Ok(request) => request,
Err(error) => {
warn!(profile_id = %profile_id, slot = ?slot, error = %error, "startup auto-connect skipped");
continue;
}
};
match runtime.activate_slot(activation).await {
Ok(snapshot) => info!(
profile_id = %profile_id,
slot = ?slot,
state = ?snapshot.state,
"startup auto-connect completed"
),
Err(error) => warn!(
profile_id = %profile_id,
slot = ?slot,
error = %error,
"startup auto-connect failed"
),
}
}
}
fn startup_activation_request(
database: &ApplicationDatabase,
profile: &desktop_protocol::ConnectionProfile,
slot: SlotKind,
) -> Result<SlotActivationRequest, RuntimeCommandError> {
let secret = load_profile_secret(database, &WindowsCredentialStore, &profile.id).map_err(
|error: CredentialCommandError| RuntimeCommandError {
code: error.code,
message: error.message,
},
)?;
match profile.transport_kind {
TransportKind::AstrBotOpenApi => {
let secret = secret.ok_or(RuntimeCommandError {
code: "credentialMissing",
message: "Enroll an API key before probing an AstrBot profile.",
})?;
let api_key =
String::from_utf8(secret.secret().to_vec()).map_err(|_| RuntimeCommandError {
code: "credentialInvalid",
message: "Stored API key is not valid UTF-8.",
})?;
let remote_username = profile.remote_username.clone().ok_or(RuntimeCommandError {
code: "validationFailed",
message: "AstrBot profiles require remote_username.",
})?;
Ok(SlotActivationRequest {
profile_id: profile.id.clone(),
slot,
base_url: profile.base_url.clone(),
transport: TransportKind::AstrBotOpenApi,
api_key: Some(SecretString::from(api_key)),
bearer_token: None,
remote_username: Some(remote_username),
session_id: profile.sticky_session_id.clone(),
expected_server_instance_id: profile.server_instance_id.clone(),
})
}
TransportKind::DesktopV1 => {
let bearer = secret.and_then(|value| {
String::from_utf8(value.secret().to_vec())
.ok()
.map(SecretString::from)
});
let expected = profile
.server_instance_id
.clone()
.ok_or(RuntimeCommandError {
code: "validationFailed",
message: "Desktop gateway profiles require server_instance_id before probe.",
})?;
Ok(SlotActivationRequest {
profile_id: profile.id.clone(),
slot,
base_url: profile.base_url.clone(),
transport: TransportKind::DesktopV1,
api_key: None,
bearer_token: bearer,
remote_username: None,
session_id: None,
expected_server_instance_id: Some(expected),
})
}
}
}
#[tauri::command]
pub async fn drain_connection_runtime_events(
database: State<'_, ApplicationDatabase>,

查看文件

@ -7,9 +7,9 @@ mod runtime;
pub use astrbot_client::{AstrBotClient, AstrBotClientConfig, AstrBotClientError};
pub use commands::{
DisconnectConnectionSlotRequest, DrainConnectionRuntimeEventsRequest,
ProbeConnectionSlotRequest, SendConnectionSlotMessageRequest, connection_runtime_status,
disconnect_connection_slot, drain_connection_runtime_events, probe_connection_slot,
send_connection_slot_message,
ProbeConnectionSlotRequest, SendConnectionSlotMessageRequest, auto_connect_configured_slots,
connection_runtime_status, disconnect_connection_slot, drain_connection_runtime_events,
probe_connection_slot, send_connection_slot_message,
};
pub use gateway_client::{BoundGatewayEvent, GatewayClient, GatewayClientConfig, GatewayError};
pub use manager::{DualConnectionManager, SlotKind};

查看文件

@ -1,4 +1,4 @@
import { invoke } from "@tauri-apps/api/core";
import { invoke } from "@tauri-apps/api/core";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
@ -158,7 +158,7 @@ export function ChatPanel() {
type="button"
>
{slot === "companion" ? "陪伴" : "运维"}
<span>{status[slot].state}</span>
<span>{connectionStateLabel(status[slot].state)}</span>
</button>
))}
</div>
@ -166,7 +166,7 @@ export function ChatPanel() {
<div className="chat-runtime-strip">
<span>Profile:{status[activeSlot].profileId ?? "未连接"}</span>
<span>Session:{status[activeSlot].activeSessionId ?? "未建立"}</span>
<span>状态:{status[activeSlot].state}</span>
<span>状态:{connectionStateLabel(status[activeSlot].state)}</span>
</div>
<div className="chat-message-list" aria-live="polite">
{activeMessages.length === 0 ? (
@ -281,3 +281,23 @@ function applyRuntimeEvents(
}
return next;
}
function connectionStateLabel(
state: ConnectionRuntimeStatus["companion"]["state"],
): string {
const labels: Record<typeof state, string> = {
disconnected: "未连接",
connecting: "连接中",
authenticating: "认证中",
syncing: "同步中",
connected: "已连接",
reconnecting: "重连中",
authExpired: "认证已过期",
incompatible: "协议不兼容",
serverUnavailable: "服务不可用",
offline: "离线",
certificateChanged: "证书已变化",
fatalError: "连接错误",
};
return labels[state];
}

查看文件

@ -1,4 +1,4 @@
import { invoke } from "@tauri-apps/api/core";
import { invoke } from "@tauri-apps/api/core";
import { useEffect, useState } from "react";
import {
@ -25,6 +25,7 @@ export function StatusBubble() {
const companion = status.companion.state;
const operations = status.operations.state;
const active = companion === "connected" || operations === "connected";
const visibleState = active ? "在线" : stateLabel(companion, operations);
return (
<main className="status-bubble-shell" aria-label="连接状态气泡">
<button
@ -33,8 +34,21 @@ export function StatusBubble() {
onClick={() => void invoke("open_quick_chat_window")}
>
<span className="status-bubble-orb" />
<span className="status-bubble-label">{active ? "在线" : "离线"}</span>
<span className="status-bubble-label">{visibleState}</span>
</button>
</main>
);
}
function stateLabel(
companion: ConnectionRuntimeStatus["companion"]["state"],
operations: ConnectionRuntimeStatus["operations"]["state"],
): string {
if (companion === "connecting" || operations === "connecting")
return "连接中";
if (companion === "authExpired" || operations === "authExpired")
return "需认证";
if (companion === "serverUnavailable" || operations === "serverUnavailable")
return "服务不可用";
return "离线";
}