feat/p02-dual-connections #3
共有 12 个文件被更改,包括 522 次插入 和 41 次删除
17
Cargo.lock
自动生成
17
Cargo.lock
自动生成
|
|
@ -2441,6 +2441,16 @@ version = "0.3.17"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
|
||||
|
||||
[[package]]
|
||||
name = "mime_guess"
|
||||
version = "2.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e"
|
||||
dependencies = [
|
||||
"mime",
|
||||
"unicase",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "minimal-lexical"
|
||||
version = "0.2.1"
|
||||
|
|
@ -3328,6 +3338,7 @@ dependencies = [
|
|||
"hyper-util",
|
||||
"js-sys",
|
||||
"log",
|
||||
"mime_guess",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"quinn",
|
||||
|
|
@ -4897,6 +4908,12 @@ dependencies = [
|
|||
"unic-common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicase"
|
||||
version = "2.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.24"
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ 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"] }
|
||||
reqwest = { version = "0.13.4", default-features = false, features = ["json", "rustls", "stream", "multipart"] }
|
||||
rusqlite = { version = "0.40.1", features = ["bundled"] }
|
||||
schemars = { version = "1.2.1", features = ["uuid1"] }
|
||||
secrecy = "0.10.3"
|
||||
|
|
|
|||
|
|
@ -71,11 +71,47 @@ pub struct AstrBotChatRequest {
|
|||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub config_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub attachments: Option<Vec<AstrBotAttachment>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub platform_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub enable_streaming: Option<bool>,
|
||||
}
|
||||
|
||||
/// A model/provider configuration exposed by AstrBot.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AstrBotModelOption {
|
||||
pub id: String,
|
||||
#[serde(default)]
|
||||
pub name: Option<String>,
|
||||
#[serde(default)]
|
||||
pub is_default: Option<bool>,
|
||||
}
|
||||
|
||||
/// Normalized attachment returned by the Rust upload boundary.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AstrBotAttachment {
|
||||
pub attachment_id: String,
|
||||
pub file_name: String,
|
||||
pub mime_type: String,
|
||||
pub size_bytes: u64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AstrBotCapabilitySnapshot {
|
||||
pub transport: String,
|
||||
pub text_chat: bool,
|
||||
pub streaming: bool,
|
||||
pub model_selection: bool,
|
||||
pub file_upload: bool,
|
||||
pub image_input: bool,
|
||||
pub models: Vec<AstrBotModelOption>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AstrBotSessionListData {
|
||||
#[serde(default)]
|
||||
|
|
@ -449,6 +485,29 @@ mod tests {
|
|||
assert!(a.starts_with("astrbot-"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chat_request_serializes_model_and_attachment_options() {
|
||||
let request = AstrBotChatRequest {
|
||||
message: Value::String("hello".into()),
|
||||
session_id: Some("session-a".into()),
|
||||
conversation_id: None,
|
||||
username: Some("desktop".into()),
|
||||
config_id: Some("model-a".into()),
|
||||
attachments: Some(vec![AstrBotAttachment {
|
||||
attachment_id: "file-a".into(),
|
||||
file_name: "image.png".into(),
|
||||
mime_type: "image/png".into(),
|
||||
size_bytes: 12,
|
||||
url: None,
|
||||
}]),
|
||||
platform_id: None,
|
||||
enable_streaming: Some(true),
|
||||
};
|
||||
let value = serde_json::to_value(request).expect("request serializes");
|
||||
assert_eq!(value["config_id"], "model-a");
|
||||
assert_eq!(value["attachments"][0]["attachmentId"], "file-a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn protocol_version_constant_is_unchanged_for_internal_model() {
|
||||
assert_eq!(crate::PROTOCOL_VERSION, "desktop-v1alpha1");
|
||||
|
|
|
|||
|
|
@ -165,3 +165,14 @@ remote_username 用于远端聊天身份和会话命名,不作为本机权限
|
|||
6. Q6 ?? manifest ???????
|
||||
|
||||
??????????? Hook ?????????/???????????????????????????
|
||||
|
||||
|
||||
### Q3.1: Chat extensibility contract
|
||||
|
||||
- Expose normalized AstrBot capability discovery through Rust-owned IPC.
|
||||
- Expose model/provider configuration options as a slot-scoped selector; keep the server default when discovery is unavailable.
|
||||
- Add a bounded 16 MiB multipart upload boundary at /api/v1/file; React receives only normalized attachment metadata.
|
||||
- Carry optional configId and attachment metadata through the send request without exposing credentials or raw HTTP clients.
|
||||
- Keep attachment wire mapping isolated in the AstrBot adapter so the internal chat runtime remains transport-neutral.
|
||||
|
||||
Acceptance: the chat panel can discover model options, stage uploaded files, and submit a normalized message request; real server response-shape compatibility remains verified by the supplied AstrBot containers before claiming end-to-end multimodal support.
|
||||
|
|
|
|||
|
|
@ -120,3 +120,12 @@ Still not claimed complete: automatic startup activation, real Tauri multi-windo
|
|||
- ???????????????????????????????????????????
|
||||
- ??????????????/?????????????????? Windows ?????
|
||||
- ?????TypeScript?ESLint?Vitest 6/6?Vite production build ???
|
||||
|
||||
|
||||
## 2026-07-20: chat extensibility contract
|
||||
|
||||
- Added Rust-owned AstrBot capability discovery, model configuration options, and slot-scoped IPC.
|
||||
- Added a bounded 16 MiB multipart upload boundary and normalized attachment metadata.
|
||||
- Extended chat send requests with optional configId and attachments; the existing dual-slot isolation remains the authority.
|
||||
- Updated ChatPanel with model selection, attachment staging, upload state, and clean WebChat-style text labels.
|
||||
- Validation: Rust workspace tests 60 passed; Vitest 6/6 passed; TypeScript, ESLint, cargo check, and Vite build passed.
|
||||
|
|
|
|||
|
|
@ -207,6 +207,8 @@ pub fn run() {
|
|||
networking::commands::probe_connection_slot,
|
||||
networking::commands::disconnect_connection_slot,
|
||||
networking::commands::send_connection_slot_message,
|
||||
networking::commands::connection_slot_capabilities,
|
||||
networking::commands::upload_connection_slot_file,
|
||||
networking::commands::cancel_connection_slot_message,
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
use std::{collections::VecDeque, sync::Arc, time::Duration};
|
||||
|
||||
use desktop_protocol::{
|
||||
AstrBotApiEnvelope, AstrBotChatRequest, AstrBotConfigListData, AstrBotSessionListData,
|
||||
AstrBotStreamMapper, BoundGatewayEvent, ConnectionState, GatewayEvent, PROTOCOL_VERSION,
|
||||
AstrBotApiEnvelope, AstrBotAttachment, AstrBotCapabilitySnapshot, AstrBotChatRequest,
|
||||
AstrBotConfigListData, AstrBotModelOption, AstrBotSessionListData, AstrBotStreamMapper,
|
||||
BoundGatewayEvent, ConnectionState, GatewayEvent, PROTOCOL_VERSION,
|
||||
derive_astrbot_server_instance_id,
|
||||
};
|
||||
use futures_util::StreamExt;
|
||||
|
|
@ -87,6 +88,7 @@ impl EventDeduplicator {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AstrBotClient {
|
||||
config: AstrBotClientConfig,
|
||||
http: reqwest::Client,
|
||||
|
|
@ -252,9 +254,86 @@ impl AstrBotClient {
|
|||
}))
|
||||
}
|
||||
|
||||
pub async fn capabilities(&self) -> Result<AstrBotCapabilitySnapshot, AstrBotClientError> {
|
||||
let configs = self.list_configs().await?;
|
||||
let models = configs
|
||||
.configs
|
||||
.into_iter()
|
||||
.map(|config| AstrBotModelOption {
|
||||
id: config.id,
|
||||
name: config.name,
|
||||
is_default: config.is_default,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
Ok(AstrBotCapabilitySnapshot {
|
||||
transport: "astrbot-openapi".to_owned(),
|
||||
text_chat: true,
|
||||
streaming: true,
|
||||
model_selection: !models.is_empty(),
|
||||
file_upload: true,
|
||||
image_input: true,
|
||||
models,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn upload_file(
|
||||
&self,
|
||||
file_name: &str,
|
||||
mime_type: &str,
|
||||
bytes: Vec<u8>,
|
||||
) -> Result<AstrBotAttachment, AstrBotClientError> {
|
||||
if file_name.trim().is_empty() || mime_type.trim().is_empty() || bytes.is_empty() {
|
||||
return Err(AstrBotClientError::InvalidConfig(
|
||||
"file_name, mime_type, and file bytes are required",
|
||||
));
|
||||
}
|
||||
let part = reqwest::multipart::Part::bytes(bytes.clone())
|
||||
.file_name(file_name.to_owned())
|
||||
.mime_str(mime_type)
|
||||
.map_err(|_| AstrBotClientError::InvalidConfig("invalid attachment mime type"))?;
|
||||
let form = reqwest::multipart::Form::new().part("file", part);
|
||||
let response = self
|
||||
.http
|
||||
.post(self.url("/api/v1/file"))
|
||||
.multipart(form)
|
||||
.send()
|
||||
.await?;
|
||||
if !response.status().is_success() {
|
||||
return Err(AstrBotClientError::HttpStatus(response.status()));
|
||||
}
|
||||
let envelope: AstrBotApiEnvelope<Value> = response.json().await?;
|
||||
if !envelope.is_ok() {
|
||||
return Err(AstrBotClientError::ApiStatus(
|
||||
envelope
|
||||
.message
|
||||
.unwrap_or_else(|| "file upload failed".into()),
|
||||
));
|
||||
}
|
||||
let data = envelope.data.unwrap_or(Value::Null);
|
||||
let attachment_id = data
|
||||
.get("id")
|
||||
.or_else(|| data.get("file_id"))
|
||||
.or_else(|| data.get("attachment_id"))
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| AstrBotClientError::Map("upload response has no attachment id".into()))?
|
||||
.to_owned();
|
||||
Ok(AstrBotAttachment {
|
||||
attachment_id,
|
||||
file_name: file_name.to_owned(),
|
||||
mime_type: mime_type.to_owned(),
|
||||
size_bytes: bytes.len() as u64,
|
||||
url: data
|
||||
.get("url")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn send_chat_stream(
|
||||
&self,
|
||||
message: &str,
|
||||
config_id: Option<String>,
|
||||
attachments: Vec<AstrBotAttachment>,
|
||||
sender: &mpsc::Sender<super::gateway_client::BoundGatewayEvent>,
|
||||
cancellation: &CancellationToken,
|
||||
) -> Result<Option<String>, AstrBotClientError> {
|
||||
|
|
@ -265,7 +344,8 @@ impl AstrBotClient {
|
|||
session_id: session_id.clone(),
|
||||
conversation_id: None,
|
||||
username: Some(self.config.remote_username.clone()),
|
||||
config_id: None,
|
||||
config_id,
|
||||
attachments: (!attachments.is_empty()).then_some(attachments),
|
||||
platform_id: None,
|
||||
enable_streaming: Some(true),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -32,6 +32,24 @@ pub struct DisconnectConnectionSlotRequest {
|
|||
pub struct SendConnectionSlotMessageRequest {
|
||||
pub slot: SlotKind,
|
||||
pub message: String,
|
||||
pub config_id: Option<String>,
|
||||
#[serde(default)]
|
||||
pub attachments: Vec<desktop_protocol::AstrBotAttachment>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct SlotFileUploadRequest {
|
||||
pub slot: SlotKind,
|
||||
pub file_name: String,
|
||||
pub mime_type: String,
|
||||
pub bytes: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct SlotCapabilitiesRequest {
|
||||
pub slot: SlotKind,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
|
|
@ -451,6 +469,34 @@ pub async fn cancel_connection_slot_message(
|
|||
) -> Result<(), RuntimeCommandError> {
|
||||
runtime.cancel_slot_message(request.slot).await
|
||||
}
|
||||
#[tauri::command]
|
||||
pub async fn connection_slot_capabilities(
|
||||
runtime: State<'_, DualSlotRuntime>,
|
||||
request: SlotCapabilitiesRequest,
|
||||
) -> Result<desktop_protocol::AstrBotCapabilitySnapshot, RuntimeCommandError> {
|
||||
runtime.slot_capabilities(request.slot).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn upload_connection_slot_file(
|
||||
runtime: State<'_, DualSlotRuntime>,
|
||||
request: SlotFileUploadRequest,
|
||||
) -> Result<desktop_protocol::AstrBotAttachment, RuntimeCommandError> {
|
||||
if request.bytes.len() > 16 * 1024 * 1024 {
|
||||
return Err(RuntimeCommandError::validation(
|
||||
"Attachment exceeds the 16 MiB limit.",
|
||||
));
|
||||
}
|
||||
runtime
|
||||
.upload_slot_file(
|
||||
request.slot,
|
||||
request.file_name,
|
||||
request.mime_type,
|
||||
request.bytes,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn send_connection_slot_message(
|
||||
database: State<'_, ApplicationDatabase>,
|
||||
|
|
@ -486,6 +532,11 @@ pub async fn send_connection_slot_message(
|
|||
);
|
||||
}
|
||||
runtime
|
||||
.send_slot_message(request.slot, request.message)
|
||||
.send_slot_message(
|
||||
request.slot,
|
||||
request.message,
|
||||
request.config_id,
|
||||
request.attachments,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
use desktop_protocol::{ConnectionState, TransportKind};
|
||||
use desktop_protocol::{
|
||||
AstrBotAttachment, AstrBotCapabilitySnapshot, ConnectionState, TransportKind,
|
||||
};
|
||||
use secrecy::SecretString;
|
||||
use serde::Serialize;
|
||||
use std::time::Duration;
|
||||
|
|
@ -297,10 +299,67 @@ impl DualSlotRuntime {
|
|||
cancellation.cancel();
|
||||
Ok(())
|
||||
}
|
||||
pub async fn slot_capabilities(
|
||||
&self,
|
||||
slot: SlotKind,
|
||||
) -> Result<AstrBotCapabilitySnapshot, RuntimeCommandError> {
|
||||
let client = {
|
||||
let guard = self.inner.lock().await;
|
||||
match slot_ref(&guard, slot).client.as_ref() {
|
||||
Some(ActiveClient::AstrBot(client)) => client.clone(),
|
||||
Some(ActiveClient::Desktop(_)) => {
|
||||
return Err(RuntimeCommandError::validation(
|
||||
"Capabilities are not available for the desktop mock transport.",
|
||||
));
|
||||
}
|
||||
None => {
|
||||
return Err(RuntimeCommandError::unavailable(
|
||||
"Activate the connection before loading capabilities.",
|
||||
));
|
||||
}
|
||||
}
|
||||
};
|
||||
client
|
||||
.capabilities()
|
||||
.await
|
||||
.map_err(|_| RuntimeCommandError::unavailable("AstrBot capabilities are unavailable."))
|
||||
}
|
||||
|
||||
pub async fn upload_slot_file(
|
||||
&self,
|
||||
slot: SlotKind,
|
||||
file_name: String,
|
||||
mime_type: String,
|
||||
bytes: Vec<u8>,
|
||||
) -> Result<AstrBotAttachment, RuntimeCommandError> {
|
||||
let client = {
|
||||
let guard = self.inner.lock().await;
|
||||
match slot_ref(&guard, slot).client.as_ref() {
|
||||
Some(ActiveClient::AstrBot(client)) => client.clone(),
|
||||
Some(ActiveClient::Desktop(_)) => {
|
||||
return Err(RuntimeCommandError::validation(
|
||||
"File upload is not available for the desktop mock transport.",
|
||||
));
|
||||
}
|
||||
None => {
|
||||
return Err(RuntimeCommandError::unavailable(
|
||||
"Activate the connection before uploading a file.",
|
||||
));
|
||||
}
|
||||
}
|
||||
};
|
||||
client
|
||||
.upload_file(&file_name, &mime_type, bytes)
|
||||
.await
|
||||
.map_err(|_| RuntimeCommandError::unavailable("AstrBot file upload failed."))
|
||||
}
|
||||
|
||||
pub async fn send_slot_message(
|
||||
&self,
|
||||
slot: SlotKind,
|
||||
message: String,
|
||||
config_id: Option<String>,
|
||||
attachments: Vec<AstrBotAttachment>,
|
||||
) -> Result<SlotRuntimeSnapshot, RuntimeCommandError> {
|
||||
if message.trim().is_empty() {
|
||||
return Err(RuntimeCommandError::validation(
|
||||
|
|
@ -342,7 +401,13 @@ impl DualSlotRuntime {
|
|||
let mut attempts = 0;
|
||||
loop {
|
||||
match client
|
||||
.send_chat_stream(&message, &self.event_tx, &cancellation)
|
||||
.send_chat_stream(
|
||||
&message,
|
||||
config_id.clone(),
|
||||
attachments.clone(),
|
||||
&self.event_tx,
|
||||
&cancellation,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_session) if cancellation.is_cancelled() => {
|
||||
|
|
|
|||
|
|
@ -2,9 +2,14 @@ import { invoke } from "@tauri-apps/api/core";
|
|||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
|
||||
import {
|
||||
astrbotAttachmentSchema,
|
||||
astrbotCapabilitySnapshotSchema,
|
||||
boundRuntimeEventSchema,
|
||||
chatSessionSchema,
|
||||
connectionRuntimeStatusSchema,
|
||||
type AstrBotAttachment,
|
||||
type AstrBotCapabilitySnapshot,
|
||||
type AstrBotModelOption,
|
||||
type BoundRuntimeEvent,
|
||||
type ChatMessage,
|
||||
type ChatSlot,
|
||||
|
|
@ -39,6 +44,13 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
const selectedSlot = fixedSlot ?? activeSlot;
|
||||
const [draft, setDraft] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [capabilities, setCapabilities] =
|
||||
useState<AstrBotCapabilitySnapshot | null>(null);
|
||||
const [selectedModel, setSelectedModel] = useState("");
|
||||
const [pendingAttachments, setPendingAttachments] = useState<
|
||||
AstrBotAttachment[]
|
||||
>([]);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [unreadCounts, setUnreadCounts] = useState<Record<ChatSlot, number>>({
|
||||
companion: 0,
|
||||
operations: 0,
|
||||
|
|
@ -69,7 +81,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
if (events.length > 0)
|
||||
setMessages((current) => applyRuntimeEvents(current, events));
|
||||
} catch {
|
||||
// Browser fallback keeps the shell usable without Rust IPC.
|
||||
// Keep the browser preview usable without Rust IPC.
|
||||
}
|
||||
}, []);
|
||||
|
||||
|
|
@ -100,6 +112,31 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
};
|
||||
}, [selectedSlot, status]);
|
||||
|
||||
useEffect(() => {
|
||||
const snapshot = status[selectedSlot];
|
||||
setCapabilities(null);
|
||||
setSelectedModel("");
|
||||
if (!snapshot.profileId || snapshot.transport !== "astrbot-openapi") return;
|
||||
let cancelled = false;
|
||||
void invoke<unknown>("connection_slot_capabilities", {
|
||||
request: { slot: selectedSlot },
|
||||
})
|
||||
.then((result) => {
|
||||
if (cancelled) return;
|
||||
const next = astrbotCapabilitySnapshotSchema.parse(result);
|
||||
setCapabilities(next);
|
||||
setSelectedModel(
|
||||
next.models.find((model) => model.isDefault)?.id ??
|
||||
next.models[0]?.id ??
|
||||
"",
|
||||
);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [selectedSlot, status]);
|
||||
|
||||
useEffect(() => {
|
||||
const snapshot = status[selectedSlot];
|
||||
if (
|
||||
|
|
@ -138,20 +175,20 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
.then((result) => {
|
||||
if (cancelled) return;
|
||||
const records = storedChatMessageSchema.array().parse(result);
|
||||
setMessages((current) => {
|
||||
const otherSlots = current.filter(
|
||||
(item) => item.slot !== selectedSlot,
|
||||
);
|
||||
const restored = records.map((record) => ({
|
||||
id: record.messageId,
|
||||
slot: record.slot,
|
||||
role: record.role,
|
||||
content: record.content,
|
||||
streaming: record.streaming,
|
||||
error: record.error,
|
||||
}));
|
||||
return otherSlots.concat(restored);
|
||||
});
|
||||
setMessages((current) =>
|
||||
current
|
||||
.filter((item) => item.slot !== selectedSlot)
|
||||
.concat(
|
||||
records.map((record) => ({
|
||||
id: record.messageId,
|
||||
slot: record.slot,
|
||||
role: record.role,
|
||||
content: record.content,
|
||||
streaming: record.streaming,
|
||||
error: record.error,
|
||||
})),
|
||||
),
|
||||
);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
return () => {
|
||||
|
|
@ -173,11 +210,43 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
};
|
||||
}, [drainEvents, refresh]);
|
||||
|
||||
const uploadFiles = async (files: FileList | null) => {
|
||||
if (!files?.length) return;
|
||||
setUploading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const uploaded: AstrBotAttachment[] = [];
|
||||
for (const file of Array.from(files)) {
|
||||
if (file.size > 16 * 1024 * 1024)
|
||||
throw new Error(`${file.name} 超过 16 MiB 限制`);
|
||||
const bytes = Array.from(new Uint8Array(await file.arrayBuffer()));
|
||||
const result = await invoke<unknown>("upload_connection_slot_file", {
|
||||
request: {
|
||||
slot: selectedSlot,
|
||||
fileName: file.name,
|
||||
mimeType: file.type || "application/octet-stream",
|
||||
bytes,
|
||||
},
|
||||
});
|
||||
uploaded.push(astrbotAttachmentSchema.parse(result));
|
||||
}
|
||||
setPendingAttachments((current) => current.concat(uploaded));
|
||||
} catch (reason) {
|
||||
setError(reason instanceof Error ? reason.message : String(reason));
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const send = async () => {
|
||||
const message = draft.trim();
|
||||
if (!message) return;
|
||||
const id = "local-" + Date.now();
|
||||
const message =
|
||||
draft.trim() ||
|
||||
(pendingAttachments.length > 0 ? "请查看我发送的附件。" : "");
|
||||
if (!message || uploading) return;
|
||||
const id = `local-${Date.now()}`;
|
||||
const attachments = pendingAttachments;
|
||||
setDraft("");
|
||||
setPendingAttachments([]);
|
||||
setMessages((current) =>
|
||||
current.concat({
|
||||
id,
|
||||
|
|
@ -188,7 +257,12 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
);
|
||||
try {
|
||||
await invoke("send_connection_slot_message", {
|
||||
request: { slot: selectedSlot, message },
|
||||
request: {
|
||||
slot: selectedSlot,
|
||||
message,
|
||||
configId: selectedModel || undefined,
|
||||
attachments,
|
||||
},
|
||||
});
|
||||
setError(null);
|
||||
} catch (reason) {
|
||||
|
|
@ -201,17 +275,18 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
}
|
||||
};
|
||||
|
||||
const currentModels: AstrBotModelOption[] = capabilities?.models ?? [];
|
||||
return (
|
||||
<section className="chat-panel" aria-label="聊天面板">
|
||||
<div className="chat-heading">
|
||||
<div>
|
||||
<p className="eyebrow">Q1 shared chat runtime</p>
|
||||
<p className="eyebrow">Shared chat runtime</p>
|
||||
<h2>统一聊天运行时</h2>
|
||||
<p className="chat-note">
|
||||
主页面、快速聊天和气泡共享同一套消息状态。
|
||||
主界面、快速聊天和气泡共享同一套消息状态。
|
||||
</p>
|
||||
</div>
|
||||
<div className="chat-slot-tabs" role="tablist" aria-label="????">
|
||||
<div className="chat-slot-tabs" role="tablist" aria-label="聊天槽位">
|
||||
{(["companion", "operations"] as const).map((slot) => (
|
||||
<button
|
||||
className={activeSlot === slot ? "chat-slot active" : "chat-slot"}
|
||||
|
|
@ -222,7 +297,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
aria-selected={activeSlot === slot}
|
||||
type="button"
|
||||
>
|
||||
{slot === "companion" ? "??" : "??"}
|
||||
{slot === "companion" ? "陪伴" : "运维"}
|
||||
{unreadCounts[slot] > 0 ? (
|
||||
<strong>{unreadCounts[slot]}</strong>
|
||||
) : null}
|
||||
|
|
@ -244,11 +319,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
) : (
|
||||
activeMessages.map((message) => (
|
||||
<article
|
||||
className={
|
||||
"chat-message " +
|
||||
message.role +
|
||||
(message.error ? " failed" : "")
|
||||
}
|
||||
className={`chat-message ${message.role}${message.error ? " failed" : ""}`}
|
||||
key={message.id}
|
||||
>
|
||||
<span className="chat-message-role">
|
||||
|
|
@ -258,13 +329,66 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
? "AstrBot"
|
||||
: "系统"}
|
||||
</span>
|
||||
<p>{message.content || "…"}</p>
|
||||
{message.streaming ? <small>生成中</small> : null}
|
||||
<p>{message.content || "(空消息)"}</p>
|
||||
{message.streaming ? <small>生成中…</small> : null}
|
||||
</article>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
{error ? <p className="chat-error">{error}</p> : null}
|
||||
<div className="chat-composer-toolbar">
|
||||
<label className="file-picker">
|
||||
<span>添加图片/文件</span>
|
||||
<input
|
||||
type="file"
|
||||
multiple
|
||||
onChange={(event) => {
|
||||
void uploadFiles(event.target.files);
|
||||
event.target.value = "";
|
||||
}}
|
||||
disabled={uploading || !capabilities?.fileUpload}
|
||||
/>
|
||||
</label>
|
||||
<select
|
||||
aria-label="模型配置"
|
||||
value={selectedModel}
|
||||
onChange={(event) => setSelectedModel(event.target.value)}
|
||||
disabled={currentModels.length === 0}
|
||||
>
|
||||
{currentModels.length === 0 ? (
|
||||
<option value="">使用服务端默认模型</option>
|
||||
) : (
|
||||
currentModels.map((model) => (
|
||||
<option key={model.id} value={model.id}>
|
||||
{model.name || model.id}
|
||||
</option>
|
||||
))
|
||||
)}
|
||||
</select>
|
||||
{uploading ? <span className="toolbar-note">上传中…</span> : null}
|
||||
</div>
|
||||
{pendingAttachments.length > 0 ? (
|
||||
<div className="attachment-list">
|
||||
{pendingAttachments.map((attachment) => (
|
||||
<span key={attachment.attachmentId}>
|
||||
{attachment.fileName}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`移除 ${attachment.fileName}`}
|
||||
onClick={() =>
|
||||
setPendingAttachments((current) =>
|
||||
current.filter(
|
||||
(item) => item.attachmentId !== attachment.attachmentId,
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
<form
|
||||
className="chat-composer"
|
||||
onSubmit={(event) => {
|
||||
|
|
@ -276,14 +400,19 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
aria-label="聊天消息"
|
||||
onChange={(event) => setDraft(event.target.value)}
|
||||
placeholder={
|
||||
activeSlot === "companion"
|
||||
selectedSlot === "companion"
|
||||
? "和陪伴实例说点什么…"
|
||||
: "向运维实例描述问题…"
|
||||
}
|
||||
value={draft}
|
||||
rows={3}
|
||||
/>
|
||||
<button disabled={!draft.trim()} type="submit">
|
||||
<button
|
||||
disabled={
|
||||
(!draft.trim() && pendingAttachments.length === 0) || uploading
|
||||
}
|
||||
type="submit"
|
||||
>
|
||||
发送
|
||||
</button>
|
||||
</form>
|
||||
|
|
@ -364,7 +493,7 @@ function connectionStateLabel(
|
|||
incompatible: "协议不兼容",
|
||||
serverUnavailable: "服务不可用",
|
||||
offline: "离线",
|
||||
certificateChanged: "证书已变化",
|
||||
certificateChanged: "证书已变更",
|
||||
fatalError: "连接错误",
|
||||
};
|
||||
return labels[state];
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { z } from "zod";
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
activeSlotKindSchema,
|
||||
|
|
@ -85,3 +85,33 @@ export const storedChatMessageSchema = z
|
|||
updatedAt: z.string().min(1),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const astrbotModelOptionSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
name: z.string().min(1).optional(),
|
||||
isDefault: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export const astrbotAttachmentSchema = z.object({
|
||||
attachmentId: z.string().min(1),
|
||||
fileName: z.string().min(1),
|
||||
mimeType: z.string().min(1),
|
||||
sizeBytes: z.number().int().nonnegative(),
|
||||
url: z.string().optional(),
|
||||
});
|
||||
|
||||
export const astrbotCapabilitySnapshotSchema = z.object({
|
||||
transport: z.string().min(1),
|
||||
textChat: z.boolean(),
|
||||
streaming: z.boolean(),
|
||||
modelSelection: z.boolean(),
|
||||
fileUpload: z.boolean(),
|
||||
imageInput: z.boolean(),
|
||||
models: astrbotModelOptionSchema.array(),
|
||||
});
|
||||
|
||||
export type AstrBotModelOption = z.infer<typeof astrbotModelOptionSchema>;
|
||||
export type AstrBotAttachment = z.infer<typeof astrbotAttachmentSchema>;
|
||||
export type AstrBotCapabilitySnapshot = z.infer<
|
||||
typeof astrbotCapabilitySnapshotSchema
|
||||
>;
|
||||
|
|
|
|||
|
|
@ -1101,3 +1101,31 @@ select:focus {
|
|||
flex: 1 0 auto;
|
||||
}
|
||||
}
|
||||
.chat-composer-toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: .65rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.chat-composer-toolbar select {
|
||||
max-width: 19rem;
|
||||
}
|
||||
|
||||
.file-picker {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: .65rem .8rem;
|
||||
border: 1px solid rgb(137 175 232 / 38%);
|
||||
border-radius: .65rem;
|
||||
color: #c7d4e9;
|
||||
background: #20314b;
|
||||
cursor: pointer;
|
||||
font-size: .82rem;
|
||||
}
|
||||
|
||||
.file-picker:hover { background: #24508c; }
|
||||
.file-picker input { display: none; }
|
||||
.attachment-list { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||
.attachment-list > span { display: inline-flex; gap: .45rem; align-items: center; padding: .4rem .55rem .4rem .7rem; border: 1px solid rgb(106 163 255 / 35%); border-radius: 999px; color: #dbe8ff; background: rgb(18 48 84 / 72%); font-size: .78rem; }
|
||||
.attachment-list button { padding: 0; border: 0; color: #b9c8e4; background: transparent; font-size: 1rem; }
|
||||
|
|
|
|||
正在加载…
添加表格
在新工单中引用