fix(chat): prevent duplicate history on session switch
一些检测仍在等待运行
ci / Portable quality checks (push) Waiting to run
ci / Windows Tauri build (push) Waiting to run

这个提交存在于:
YokiiroBW 2026-07-22 02:52:31 +08:00
父节点 02dfb618b9
当前提交 d100da324d
共有 12 个文件被更改,包括 902 次插入 和 98 次删除

查看文件

@ -213,6 +213,11 @@ pub fn parse_astrbot_sse_line(line: &str) -> Result<AstrBotSseUnit, AstrBotMapEr
} }
/// Stateful mapper that turns AstrBot chat SSE frames into Desktop Gateway events. /// Stateful mapper that turns AstrBot chat SSE frames into Desktop Gateway events.
#[derive(Debug, Clone, PartialEq, Eq)]
struct PendingMedia {
media_type: String,
}
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct AstrBotStreamMapper { pub struct AstrBotStreamMapper {
server_instance_id: String, server_instance_id: String,
@ -222,6 +227,7 @@ pub struct AstrBotStreamMapper {
delta_index: u32, delta_index: u32,
sequence: u64, sequence: u64,
saw_assistant_delta: bool, saw_assistant_delta: bool,
pending_media: Option<PendingMedia>,
} }
impl AstrBotStreamMapper { impl AstrBotStreamMapper {
@ -265,6 +271,7 @@ impl AstrBotStreamMapper {
} }
"user_message_saved" => Vec::new(), "user_message_saved" => Vec::new(),
"plain" => self.map_plain(frame), "plain" => self.map_plain(frame),
"image" | "record" | "file" | "video" => self.map_media(frame),
"complete" => self.map_complete(frame), "complete" => self.map_complete(frame),
"agent_stats" => { "agent_stats" => {
let detail = frame.data.to_string(); let detail = frame.data.to_string();
@ -300,11 +307,51 @@ impl AstrBotStreamMapper {
)); ));
events events
} }
"attachment_saved" => Vec::new(), "attachment_saved" => self.map_attachment_saved(frame),
_ => Vec::new(), _ => Vec::new(),
} }
} }
fn map_media(&mut self, frame: AstrBotStreamFrame) -> Vec<GatewayEvent> {
let mut events = Vec::new();
if let Some(message_id) = frame.message_id {
if self
.active_message_id
.as_ref()
.is_some_and(|current| current != &message_id)
{
events = self.complete_if_needed(FinishReason::Stop);
self.accumulated.clear();
self.delta_index = 0;
self.saw_assistant_delta = false;
}
self.active_message_id = Some(message_id);
}
self.pending_media = Some(PendingMedia {
media_type: frame.frame_type,
});
events
}
fn map_attachment_saved(&mut self, frame: AstrBotStreamFrame) -> Vec<GatewayEvent> {
let Some(media) = self.pending_media.take() else {
return Vec::new();
};
let Some(attachment_id) = frame
.data
.get("id")
.or_else(|| frame.data.get("attachment_id"))
.and_then(Value::as_str)
.filter(|value| !value.trim().is_empty())
else {
return Vec::new();
};
if media.media_type != "image" {
return Vec::new();
}
self.emit_delta(format!("![image](astrbot-attachment://{attachment_id})"))
}
fn map_plain(&mut self, frame: AstrBotStreamFrame) -> Vec<GatewayEvent> { fn map_plain(&mut self, frame: AstrBotStreamFrame) -> Vec<GatewayEvent> {
let chunk = text_from_value(&frame.data).unwrap_or_default(); let chunk = text_from_value(&frame.data).unwrap_or_default();
if chunk.is_empty() && frame.streaming.unwrap_or(false) { if chunk.is_empty() && frame.streaming.unwrap_or(false) {
@ -564,6 +611,28 @@ mod tests {
} }
} }
#[test]
fn maps_image_frames_to_persistable_attachment_markers() {
let mut mapper = AstrBotStreamMapper::new("astrbot-test");
assert!(
mapper
.push_line(r#"data: {"type":"image","data":"[IMAGE]happy.png","message_id":"m1"}"#)
.expect("image frame")
.is_empty()
);
let events = mapper
.push_line(r#"data: {"type":"attachment_saved","data":{"id":"att-1","type":"image"},"message_id":"m1"}"#)
.expect("attachment frame");
let delta = events
.iter()
.find_map(|event| match &event.body {
GatewayEventBody::MessageDelta(payload) => Some(payload.delta.as_str()),
_ => None,
})
.expect("image delta");
assert_eq!(delta, "![image](astrbot-attachment://att-1)");
}
#[test] #[test]
fn derives_stable_instance_ids() { fn derives_stable_instance_ids() {
let a = derive_astrbot_server_instance_id("http://192.168.31.210:26285/"); let a = derive_astrbot_server_instance_id("http://192.168.31.210:26285/");

查看文件

@ -662,6 +662,7 @@ pub fn run() {
networking::commands::connection_slot_sessions, networking::commands::connection_slot_sessions,
networking::commands::switch_connection_slot_session, networking::commands::switch_connection_slot_session,
networking::commands::upload_connection_slot_file, networking::commands::upload_connection_slot_file,
networking::commands::download_connection_slot_attachment,
networking::commands::cancel_connection_slot_message, networking::commands::cancel_connection_slot_message,
]) ])
.run(tauri::generate_context!()) .run(tauri::generate_context!())

查看文件

@ -7,7 +7,7 @@ use desktop_protocol::{
derive_astrbot_server_instance_id, derive_astrbot_server_instance_id,
}; };
use futures_util::StreamExt; use futures_util::StreamExt;
use reqwest::header::{ACCEPT, AUTHORIZATION, HeaderMap, HeaderValue}; use reqwest::header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE, HeaderMap, HeaderValue};
use secrecy::{ExposeSecret, SecretString}; use secrecy::{ExposeSecret, SecretString};
use serde_json::{Value, json}; use serde_json::{Value, json};
use thiserror::Error; use thiserror::Error;
@ -349,6 +349,46 @@ impl AstrBotClient {
}) })
} }
pub async fn download_attachment(
&self,
attachment_id: &str,
) -> Result<(String, Vec<u8>), AstrBotClientError> {
if attachment_id.is_empty()
|| attachment_id.len() > 200
|| !attachment_id
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
{
return Err(AstrBotClientError::InvalidConfig("invalid attachment id"));
}
let response = self
.http
.get(self.url(&format!("/api/v1/files/{attachment_id}/content")))
.send()
.await?;
if response.status().as_u16() == 401 || response.status().as_u16() == 403 {
return Err(AstrBotClientError::HttpStatus(response.status()));
}
if !response.status().is_success() {
return Err(AstrBotClientError::HttpStatus(response.status()));
}
let mime_type = response
.headers()
.get(CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.split(';').next())
.filter(|value| !value.trim().is_empty())
.unwrap_or("application/octet-stream")
.to_owned();
let bytes = response.bytes().await?.to_vec();
if bytes.is_empty() || bytes.len() > 16 * 1024 * 1024 {
return Err(AstrBotClientError::InvalidConfig(
"attachment size is outside the supported range",
));
}
Ok((mime_type, bytes))
}
pub async fn send_chat_stream( pub async fn send_chat_stream(
&self, &self,
message: &str, message: &str,

查看文件

@ -1,7 +1,7 @@
// IPC wrappers for dual-slot runtime. Secrets never leave Rust. // IPC wrappers for dual-slot runtime. Secrets never leave Rust.
use desktop_protocol::TransportKind; use desktop_protocol::TransportKind;
use secrecy::SecretString; use secrecy::SecretString;
use serde::Deserialize; use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value;
use tauri::State; use tauri::State;
use tracing::{info, warn}; use tracing::{info, warn};
@ -46,6 +46,20 @@ pub struct SlotFileUploadRequest {
pub bytes: Vec<u8>, pub bytes: Vec<u8>,
} }
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DownloadConnectionSlotAttachmentRequest {
pub slot: SlotKind,
pub attachment_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DownloadConnectionSlotAttachmentResponse {
pub mime_type: String,
pub bytes: Vec<u8>,
}
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)] #[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SlotCapabilitiesRequest { pub struct SlotCapabilitiesRequest {
@ -92,6 +106,32 @@ fn slot_name(slot: SlotKind) -> &'static str {
} }
} }
fn persist_session_identity(database: &ApplicationDatabase, snapshot: &SlotRuntimeSnapshot) {
let Some(profile_id) = snapshot.profile_id.as_deref() else {
return;
};
let Some(session_id) = snapshot.active_session_id.as_deref() else {
return;
};
let Ok(Some(mut profile)) = database.profile(profile_id) else {
return;
};
let mut dirty = false;
if profile.sticky_session_id.as_deref() != Some(session_id) {
profile.sticky_session_id = Some(session_id.to_owned());
dirty = true;
}
if profile.server_instance_id.is_none()
&& let Some(server_instance_id) = snapshot.server_instance_id.as_deref()
{
profile.server_instance_id = Some(server_instance_id.to_owned());
dirty = true;
}
if dirty {
let _ = database.update_profile(&profile);
}
}
#[tauri::command] #[tauri::command]
pub async fn connection_runtime_status( pub async fn connection_runtime_status(
runtime: State<'_, DualSlotRuntime>, runtime: State<'_, DualSlotRuntime>,
@ -134,12 +174,15 @@ pub async fn auto_connect_configured_slots(
}; };
match runtime.activate_slot(activation).await { match runtime.activate_slot(activation).await {
Ok(snapshot) => info!( Ok(snapshot) => {
profile_id = %profile_id, persist_session_identity(database, &snapshot);
slot = ?slot, info!(
state = ?snapshot.state, profile_id = %profile_id,
"startup auto-connect completed" slot = ?slot,
), state = ?snapshot.state,
"startup auto-connect completed"
);
}
Err(error) => warn!( Err(error) => warn!(
profile_id = %profile_id, profile_id = %profile_id,
slot = ?slot, slot = ?slot,
@ -530,12 +573,15 @@ pub async fn connection_slot_sessions(
#[tauri::command] #[tauri::command]
pub async fn switch_connection_slot_session( pub async fn switch_connection_slot_session(
database: State<'_, ApplicationDatabase>,
runtime: State<'_, DualSlotRuntime>, runtime: State<'_, DualSlotRuntime>,
request: SwitchChatSessionRequest, request: SwitchChatSessionRequest,
) -> Result<SlotRuntimeSnapshot, RuntimeCommandError> { ) -> Result<SlotRuntimeSnapshot, RuntimeCommandError> {
runtime let snapshot = runtime
.switch_slot_session(request.slot, request.session_id) .switch_slot_session(request.slot, request.session_id)
.await .await?;
persist_session_identity(&database, &snapshot);
Ok(snapshot)
} }
#[tauri::command] #[tauri::command]
@ -546,6 +592,17 @@ pub async fn connection_slot_capabilities(
runtime.slot_capabilities(request.slot).await runtime.slot_capabilities(request.slot).await
} }
#[tauri::command]
pub async fn download_connection_slot_attachment(
runtime: State<'_, DualSlotRuntime>,
request: DownloadConnectionSlotAttachmentRequest,
) -> Result<DownloadConnectionSlotAttachmentResponse, RuntimeCommandError> {
let (mime_type, bytes) = runtime
.download_slot_attachment(request.slot, request.attachment_id)
.await?;
Ok(DownloadConnectionSlotAttachmentResponse { mime_type, bytes })
}
#[tauri::command] #[tauri::command]
pub async fn upload_connection_slot_file( pub async fn upload_connection_slot_file(
runtime: State<'_, DualSlotRuntime>, runtime: State<'_, DualSlotRuntime>,
@ -627,5 +684,8 @@ pub async fn send_connection_slot_message(
false, false,
); );
} }
if let Ok(snapshot) = &result {
persist_session_identity(&database, snapshot);
}
result result
} }

查看文件

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

查看文件

@ -502,6 +502,33 @@ impl DualSlotRuntime {
.map_err(|_| RuntimeCommandError::unavailable("AstrBot capabilities are unavailable.")) .map_err(|_| RuntimeCommandError::unavailable("AstrBot capabilities are unavailable."))
} }
pub async fn download_slot_attachment(
&self,
slot: SlotKind,
attachment_id: String,
) -> Result<(String, Vec<u8>), 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(
"Attachment download is not available for the desktop mock transport.",
));
}
None => {
return Err(RuntimeCommandError::unavailable(
"Activate the connection before downloading an attachment.",
));
}
}
};
client
.download_attachment(&attachment_id)
.await
.map_err(|_| RuntimeCommandError::unavailable("AstrBot attachment download failed."))
}
pub async fn upload_slot_file( pub async fn upload_slot_file(
&self, &self,
slot: SlotKind, slot: SlotKind,

查看文件

@ -274,7 +274,14 @@ function WindowChrome({
data-tauri-drag-region data-tauri-drag-region
onDoubleClick={() => void toggleMaximize()} onDoubleClick={() => void toggleMaximize()}
onMouseDown={(event) => { onMouseDown={(event) => {
if (event.button === 0) void currentWindow?.startDragging(); if (
event.button === 0 &&
!(event.target as HTMLElement).closest(
'[data-tauri-drag-region="false"]',
)
) {
void currentWindow?.startDragging();
}
}} }}
> >
<span className="window-chrome-title">AstrBot Desktop</span> <span className="window-chrome-title">AstrBot Desktop</span>

查看文件

@ -13,6 +13,8 @@ import {
type AstrBotAttachment, type AstrBotAttachment,
type AstrBotCapabilitySnapshot, type AstrBotCapabilitySnapshot,
type BoundRuntimeEvent, type BoundRuntimeEvent,
type ChatSession,
mergeLoadedChatMessages,
remoteChatSessionSchema, remoteChatSessionSchema,
type ChatMessage, type ChatMessage,
type ChatSlot, type ChatSlot,
@ -54,6 +56,12 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
const [status, setStatus] = useState(emptyStatus); const [status, setStatus] = useState(emptyStatus);
const [messages, setMessages] = useState<ChatMessage[]>([]); const [messages, setMessages] = useState<ChatMessage[]>([]);
const [remoteSessions, setRemoteSessions] = useState<RemoteChatSession[]>([]); const [remoteSessions, setRemoteSessions] = useState<RemoteChatSession[]>([]);
const [storedSessions, setStoredSessions] = useState<
Record<ChatSlot, ChatSession[]>
>({
companion: [],
operations: [],
});
const [activeSlot, setActiveSlot] = useState<ChatSlot>( const [activeSlot, setActiveSlot] = useState<ChatSlot>(
fixedSlot ?? "companion", fixedSlot ?? "companion",
); );
@ -62,6 +70,8 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
const selectedProfileId = selectedSnapshot.profileId; const selectedProfileId = selectedSnapshot.profileId;
const selectedServerInstanceId = selectedSnapshot.serverInstanceId; const selectedServerInstanceId = selectedSnapshot.serverInstanceId;
const selectedSessionId = selectedSnapshot.activeSessionId; const selectedSessionId = selectedSnapshot.activeSessionId;
const historySessionId =
selectedSessionId ?? storedSessions[selectedSlot][0]?.sessionId;
const selectedTransport = selectedSnapshot.transport; const selectedTransport = selectedSnapshot.transport;
const [draft, setDraft] = useState(""); const [draft, setDraft] = useState("");
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
@ -105,6 +115,15 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
[activeMessages], [activeMessages],
); );
const displaySessions =
remoteSessions.length > 0
? remoteSessions
: storedSessions[selectedSlot].map((session) => ({
sessionId: session.sessionId,
displayName: undefined,
updatedAt: session.lastMessageAt,
}));
const refresh = useCallback(async () => { const refresh = useCallback(async () => {
try { try {
const result = await invoke<unknown>("connection_runtime_status"); const result = await invoke<unknown>("connection_runtime_status");
@ -154,6 +173,11 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
.then((result) => { .then((result) => {
if (cancelled) return; if (cancelled) return;
const sessions = chatSessionSchema.array().parse(result); const sessions = chatSessionSchema.array().parse(result);
setStoredSessions((current) => ({
...current,
[selectedSlot]: sessions,
}));
setUnreadCounts((current) => ({ setUnreadCounts((current) => ({
...current, ...current,
[selectedSlot]: sessions.reduce( [selectedSlot]: sessions.reduce(
@ -171,6 +195,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
selectedProfileId, selectedProfileId,
selectedServerInstanceId, selectedServerInstanceId,
selectedSessionId, selectedSessionId,
historySessionId,
selectedTransport, selectedTransport,
]); ]);
@ -200,6 +225,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
selectedProfileId, selectedProfileId,
selectedServerInstanceId, selectedServerInstanceId,
selectedSessionId, selectedSessionId,
historySessionId,
selectedTransport, selectedTransport,
]); ]);
@ -231,6 +257,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
selectedProfileId, selectedProfileId,
selectedServerInstanceId, selectedServerInstanceId,
selectedSessionId, selectedSessionId,
historySessionId,
selectedTransport, selectedTransport,
]); ]);
@ -238,7 +265,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
const snapshot = { const snapshot = {
profileId: selectedProfileId, profileId: selectedProfileId,
serverInstanceId: selectedServerInstanceId, serverInstanceId: selectedServerInstanceId,
activeSessionId: selectedSessionId, activeSessionId: historySessionId,
transport: selectedTransport, transport: selectedTransport,
}; };
if ( if (
@ -261,6 +288,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
selectedProfileId, selectedProfileId,
selectedServerInstanceId, selectedServerInstanceId,
selectedSessionId, selectedSessionId,
historySessionId,
selectedTransport, selectedTransport,
]); ]);
@ -268,7 +296,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
const snapshot = { const snapshot = {
profileId: selectedProfileId, profileId: selectedProfileId,
serverInstanceId: selectedServerInstanceId, serverInstanceId: selectedServerInstanceId,
activeSessionId: selectedSessionId, activeSessionId: historySessionId,
transport: selectedTransport, transport: selectedTransport,
}; };
if ( if (
@ -290,32 +318,14 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
.then((result) => { .then((result) => {
if (cancelled) return; if (cancelled) return;
const records = storedChatMessageSchema.array().parse(result); const records = storedChatMessageSchema.array().parse(result);
setMessages((current) => { setMessages((current) =>
const localUserMessages = current.filter( mergeLoadedChatMessages(
(item) => current,
(item.id.startsWith("local-") || item.streaming) && records,
item.slot === selectedSlot && selectedSlot,
item.sessionId === snapshot.activeSessionId, snapshot.activeSessionId,
); ),
return current );
.filter(
(item) =>
item.slot !== selectedSlot ||
item.sessionId !== snapshot.activeSessionId,
)
.concat(localUserMessages)
.concat(
records.map((record) => ({
id: record.messageId,
sessionId: record.sessionId,
slot: record.slot,
role: record.role,
content: record.content,
streaming: record.streaming,
error: record.error,
})),
);
});
}) })
.catch(() => undefined); .catch(() => undefined);
return () => { return () => {
@ -326,6 +336,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
selectedProfileId, selectedProfileId,
selectedServerInstanceId, selectedServerInstanceId,
selectedSessionId, selectedSessionId,
historySessionId,
selectedTransport, selectedTransport,
]); ]);
@ -450,7 +461,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
await navigator.clipboard.writeText(content); await navigator.clipboard.writeText(content);
setError(null); setError(null);
} catch { } catch {
setError("Copy failed. Check clipboard permissions."); setError("复制失败,请检查剪贴板权限。");
} }
}; };
@ -577,7 +588,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
<section className="chat-panel" aria-label="聊天面板"> <section className="chat-panel" aria-label="聊天面板">
<div className="chat-heading"> <div className="chat-heading">
<div> <div>
<p className="eyebrow">Shared chat runtime</p> <p className="eyebrow">共享聊天运行时</p>
<h2>统一聊天运行时</h2> <h2>统一聊天运行时</h2>
<p className="chat-note"> <p className="chat-note">
主界面、快速聊天和气泡共享同一套消息状态。 主界面、快速聊天和气泡共享同一套消息状态。
@ -621,35 +632,33 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
</div> </div>
<div className="chat-runtime-strip"> <div className="chat-runtime-strip">
<div> <div>
<span>Profile</span> <span>配置</span>
<strong>{status[selectedSlot].profileId ?? "Not connected"}</strong> <strong>{status[selectedSlot].profileId ?? "未连接"}</strong>
</div> </div>
<div> <div>
<span>Session</span> <span>会话</span>
<strong> <strong>{status[selectedSlot].activeSessionId ?? "新会话"}</strong>
{status[selectedSlot].activeSessionId ?? "New session"}
</strong>
</div> </div>
<div> <div>
<span>Status</span> <span>状态</span>
<strong>{connectionStateLabel(status[selectedSlot].state)}</strong> <strong>{connectionStateLabel(status[selectedSlot].state)}</strong>
</div> </div>
<div className="chat-runtime-actions"> <div className="chat-runtime-actions">
<button type="button" onClick={() => void refreshConnection()}> <button type="button" onClick={() => void refreshConnection()}>
Refresh 刷新
</button> </button>
<button type="button" onClick={() => void reconnectConnection()}> <button type="button" onClick={() => void reconnectConnection()}>
Reconnect 重连
</button> </button>
<button <button
type="button" type="button"
onClick={() => void disconnectConnection()} onClick={() => void disconnectConnection()}
disabled={status[selectedSlot].state === "disconnected"} disabled={status[selectedSlot].state === "disconnected"}
> >
Disconnect 断开
</button> </button>
<button type="button" onClick={() => void startNewSession()}> <button type="button" onClick={() => void startNewSession()}>
New chat 新对话
</button> </button>
</div> </div>
</div> </div>
@ -669,9 +678,9 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
</button> </button>
</div> </div>
) : null} ) : null}
{remoteSessions.length > 0 ? ( {displaySessions.length > 0 ? (
<div className="chat-session-list" aria-label="Chat sessions"> <div className="chat-session-list" aria-label="Chat sessions">
{remoteSessions.map((session) => ( {displaySessions.map((session, index) => (
<button <button
className={ className={
session.sessionId === status[selectedSlot].activeSessionId session.sessionId === status[selectedSlot].activeSessionId
@ -679,6 +688,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
: "chat-session" : "chat-session"
} }
key={session.sessionId} key={session.sessionId}
title={`会话标识:${session.sessionId}`}
type="button" type="button"
onClick={() => { onClick={() => {
void invoke("switch_connection_slot_session", { void invoke("switch_connection_slot_session", {
@ -692,8 +702,8 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
); );
}} }}
> >
<strong>{session.displayName || session.sessionId}</strong> <strong>{session.displayName || `会话 ${index + 1}`}</strong>
<small>{session.updatedAt || "Remote session"}</small> <small>{formatSessionTime(session.updatedAt)}</small>
</button> </button>
))} ))}
</div> </div>
@ -708,7 +718,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
> >
{visibleMessages.length === 0 ? ( {visibleMessages.length === 0 ? (
<p className="chat-empty"> <p className="chat-empty">
No messages in this slot yet. Connect a Profile to start chatting. 当前槽位还没有消息。连接 Profile 后即可开始聊天。
</p> </p>
) : ( ) : (
visibleMessages.map((message) => { visibleMessages.map((message) => {
@ -724,43 +734,63 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
? "A" ? "A"
: "!"} : "!"}
</div> </div>
<div className="chat-bubble"> <div className="chat-message-content">
<div className="chat-bubble-header"> <div className="chat-bubble">
<span> <div className="chat-bubble-header">
{message.role === "user" <span>
? "You" {message.role === "user"
: message.role === "assistant" ? "你"
? "AstrBot" : message.role === "assistant"
: "System"} ? "AstrBot"
</span> : "系统"}
{message.streaming ? <small>Generating</small> : null} </span>
{message.streaming ? <small>生成中</small> : null}
</div>
{message.content ? (
<MessageContent content={message.content} slot={selectedSlot} />
) : (
<p className="message-placeholder">正在生成…</p>
)}
</div> </div>
{message.content ? (
<MessageContent content={message.content} />
) : (
<p className="message-placeholder">Generating?</p>
)}
{message.role === "assistant" && {message.role === "assistant" &&
message.content && message.content &&
!message.streaming ? ( !message.streaming ? (
<div className="chat-message-actions"> <div className="chat-message-actions" aria-label="消息操作">
<button <button
type="button" type="button"
aria-label="复制消息"
title="复制消息"
onClick={() => void copyMessage(message.content)} onClick={() => void copyMessage(message.content)}
> >
Copy <span
className="message-action-icon icon-copy"
aria-hidden="true"
/>
<span>复制</span>
</button> </button>
<button <button
type="button" type="button"
aria-label="重试消息"
title="重试消息"
onClick={() => retryMessage(message.id)} onClick={() => retryMessage(message.id)}
> >
Retry <span
className="message-action-icon icon-retry"
aria-hidden="true"
/>
<span>重试</span>
</button> </button>
<button <button
type="button" type="button"
aria-label="朗读消息"
title="朗读消息"
onClick={() => speakMessage(message.content)} onClick={() => speakMessage(message.content)}
> >
Read aloud <span
className="message-action-icon icon-read"
aria-hidden="true"
/>
<span>朗读</span>
</button> </button>
</div> </div>
) : null} ) : null}
@ -770,7 +800,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
type="button" type="button"
onClick={() => void stopGeneration()} onClick={() => void stopGeneration()}
> >
Stop generating 停止生成
</button> </button>
) : null} ) : null}
</div> </div>
@ -843,19 +873,33 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
onChange={(event) => setDraft(event.target.value)} onChange={(event) => setDraft(event.target.value)}
placeholder={ placeholder={
selectedSlot === "companion" selectedSlot === "companion"
? "和陪伴实例说点什么…" ? "和陪伴实例说点什么…(Enter 发送,Shift+Enter 换行)"
: "向运维实例描述问题…" : "向运维实例描述问题…(Enter 发送,Shift+Enter 换行)"
} }
value={draft} value={draft}
rows={3} rows={3}
onKeyDown={(event) => {
if (
event.key !== "Enter" ||
event.shiftKey ||
event.nativeEvent.isComposing
)
return;
event.preventDefault();
void send();
}}
/> />
<button <button
className="chat-send-button"
disabled={ disabled={
(!draft.trim() && pendingAttachments.length === 0) || uploading (!draft.trim() && pendingAttachments.length === 0) || uploading
} }
type="submit" type="submit"
> >
发送 <span className="send-button-icon" aria-hidden="true">
↑
</span>
<span>发送</span>
</button> </button>
</form> </form>
</section> </section>
@ -940,6 +984,18 @@ function applyRuntimeEvents(
return next; return next;
} }
function formatSessionTime(value?: string): string {
if (!value) return "本地历史";
const date = new Date(value);
if (Number.isNaN(date.getTime())) return "本地历史";
return new Intl.DateTimeFormat("zh-CN", {
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
}).format(date);
}
function connectionStateLabel( function connectionStateLabel(
state: ConnectionRuntimeStatus["companion"]["state"], state: ConnectionRuntimeStatus["companion"]["state"],
): string { ): string {

查看文件

@ -1,13 +1,62 @@
import { Fragment, type ReactNode } from "react"; import { Fragment, useEffect, useState, type ReactNode } from "react";
import { invoke } from "@tauri-apps/api/core";
import type { ChatSlot } from "./types";
type MessageContentProps = { type MessageContentProps = {
content: string; content: string;
slot: ChatSlot;
}; };
function renderInline(text: string, keyPrefix: string): ReactNode[] { type DownloadedAttachment = {
const tokens = text.split(/(`[^`]+`|\*\*[^*]+\*\*|\[[^\]]+\]\([^)]+\))/g); mimeType?: unknown;
bytes?: unknown;
};
const emotionLabels: Record<string, string> = {
happy: "【开心】",
sad: "【难过】",
angry: "【生气】",
surprised: "【惊讶】",
confused: "【困惑】",
crying: "【哭泣】",
love: "【喜欢】",
};
function normalizeContent(content: string): string {
return content.replace(/&&([a-zA-Z_-]+)&&/g, (_, name: string) =>
emotionLabels[name.toLowerCase()] ?? "",
);
}
function renderInline(
text: string,
keyPrefix: string,
imageUrls: Record<string, string>,
): ReactNode[] {
const tokens = text.split(
/(!\[[^\]]*\]\(astrbot-attachment:\/\/[A-Za-z0-9._-]+\)|`[^`]+`|\*\*[^*]+\*\*|\[[^\]]+\]\([^)]+\))/g,
);
return tokens.map((token, index) => { return tokens.map((token, index) => {
const key = `${keyPrefix}-${index}`; const key = `${keyPrefix}-${index}`;
const image = token.match(
/^!\[([^\]]*)\]\(astrbot-attachment:\/\/([A-Za-z0-9._-]+)\)$/,
);
if (image) {
const source = imageUrls[image[2]];
return source ? (
<img
className="message-attachment-image"
key={key}
src={source}
alt={image[1] || "image"}
/>
) : (
<span className="message-attachment-placeholder" key={key}>
image loading
</span>
);
}
if (token.startsWith("`") && token.endsWith("`")) { if (token.startsWith("`") && token.endsWith("`")) {
return <code key={key}>{token.slice(1, -1)}</code>; return <code key={key}>{token.slice(1, -1)}</code>;
} }
@ -26,8 +75,65 @@ function renderInline(text: string, keyPrefix: string): ReactNode[] {
}); });
} }
export function MessageContent({ content }: MessageContentProps) { export function MessageContent({ content, slot }: MessageContentProps) {
const lines = content.replaceAll("\r\n", "\n").split("\n"); const [imageUrls, setImageUrls] = useState<Record<string, string>>({});
const attachmentIds = Array.from(
content.matchAll(
/!\[[^\]]*\]\(astrbot-attachment:\/\/([A-Za-z0-9._-]+)\)/g,
),
(match) => match[1],
);
const attachmentKey = attachmentIds.join("|");
useEffect(() => {
let cancelled = false;
const createdUrls: string[] = [];
setImageUrls({});
const ids = attachmentKey ? attachmentKey.split("|") : [];
if (!ids.length) return undefined;
void Promise.all(
ids.map(async (attachmentId) => {
try {
const result = await invoke<unknown>(
"download_connection_slot_attachment",
{ request: { slot, attachmentId } },
);
const payload = result as DownloadedAttachment;
const bytes =
payload.bytes instanceof Uint8Array
? payload.bytes
: Array.isArray(payload.bytes)
? new Uint8Array(payload.bytes.filter((item): item is number => typeof item === "number"))
: null;
if (!bytes || cancelled) return;
const blob = new Blob([bytes.buffer as ArrayBuffer], {
type:
typeof payload.mimeType === "string"
? payload.mimeType
: "application/octet-stream",
});
const url = URL.createObjectURL(blob);
createdUrls.push(url);
if (!cancelled) {
setImageUrls((current) => ({ ...current, [attachmentId]: url }));
}
} catch {
// Keep an inline placeholder when the attachment is no longer available.
}
}),
);
return () => {
cancelled = true;
createdUrls.forEach((url) => URL.revokeObjectURL(url));
};
}, [attachmentKey, slot]);
const lines = normalizeContent(content)
.replaceAll("\r\n", "\n")
.split("\n");
const blocks: ReactNode[] = []; const blocks: ReactNode[] = [];
let codeLines: string[] | null = null; let codeLines: string[] | null = null;
let codeLanguage = ""; let codeLanguage = "";
@ -38,7 +144,7 @@ export function MessageContent({ content }: MessageContentProps) {
if (!paragraph.length) return; if (!paragraph.length) return;
blocks.push( blocks.push(
<p key={`paragraph-${blocks.length}`}> <p key={`paragraph-${blocks.length}`}>
{renderInline(paragraph.join(" "), `paragraph-${blocks.length}`)} {renderInline(paragraph.join(" "), `paragraph-${blocks.length}`, imageUrls)}
</p>, </p>,
); );
paragraph = []; paragraph = [];
@ -49,7 +155,7 @@ export function MessageContent({ content }: MessageContentProps) {
<ul key={`list-${blocks.length}`}> <ul key={`list-${blocks.length}`}>
{list.map((item, index) => ( {list.map((item, index) => (
<li key={`list-${blocks.length}-${index}`}> <li key={`list-${blocks.length}-${index}`}>
{renderInline(item, `list-${blocks.length}-${index}`)} {renderInline(item, `list-${blocks.length}-${index}`, imageUrls)}
</li> </li>
))} ))}
</ul>, </ul>,
@ -92,7 +198,7 @@ export function MessageContent({ content }: MessageContentProps) {
const Heading = `h${level}` as "h1" | "h2" | "h3"; const Heading = `h${level}` as "h1" | "h2" | "h3";
blocks.push( blocks.push(
<Heading key={`heading-${index}`}> <Heading key={`heading-${index}`}>
{renderInline(heading[2], `heading-${index}`)} {renderInline(heading[2], `heading-${index}`, imageUrls)}
</Heading>, </Heading>,
); );
return; return;

查看文件

@ -0,0 +1,85 @@
import { describe, expect, it } from "vitest";
import {
chatSessionSchema,
mergeLoadedChatMessages,
storedChatMessageSchema,
} from "./types";
describe("chat persistence IPC schemas", () => {
it("accepts nullable Rust fields in stored sessions", () => {
expect(
chatSessionSchema.parse({
accountId: "local-default",
profileId: "profile-1",
slot: "companion",
serverInstanceId: "server-1",
remoteUsername: null,
sessionId: "session-1",
unreadCount: 0,
lastMessageId: null,
lastMessageAt: "2026-07-20T12:00:00Z",
}),
).toMatchObject({ sessionId: "session-1" });
});
it("accepts nullable remote usernames in stored messages", () => {
expect(
storedChatMessageSchema.parse({
accountId: "local-default",
profileId: "profile-1",
slot: "companion",
serverInstanceId: "server-1",
remoteUsername: null,
sessionId: "session-1",
messageId: "message-1",
role: "user",
content: "hello",
streaming: false,
error: false,
updatedAt: "2026-07-20T12:00:00Z",
}),
).toMatchObject({ content: "hello" });
});
it("replaces loaded session messages without duplicating optimistic users", () => {
const record = {
accountId: "local-default",
profileId: "profile-1",
slot: "companion" as const,
serverInstanceId: "server-1",
remoteUsername: null,
sessionId: "session-1",
messageId: "stored-user-1",
role: "user" as const,
content: "hello",
streaming: false,
error: false,
updatedAt: "2026-07-20T12:00:00Z",
};
const result = mergeLoadedChatMessages(
[
{
id: "local-temp-1",
sessionId: "session-1",
slot: "companion",
role: "user",
content: "hello",
},
{
id: "stored-user-1",
sessionId: "session-1",
slot: "companion",
role: "user",
content: "hello",
},
],
[record],
"companion",
"session-1",
);
expect(result).toHaveLength(1);
expect(result[0]?.id).toBe("stored-user-1");
});
});

查看文件

@ -49,10 +49,10 @@ export const chatSessionSchema = z
profileId: z.string().min(1), profileId: z.string().min(1),
slot: activeSlotKindSchema, slot: activeSlotKindSchema,
serverInstanceId: z.string().min(1), serverInstanceId: z.string().min(1),
remoteUsername: z.string().min(1).optional(), remoteUsername: z.string().min(1).nullish(),
sessionId: z.string().min(1), sessionId: z.string().min(1),
unreadCount: z.number().int().nonnegative(), unreadCount: z.number().int().nonnegative(),
lastMessageId: z.string().min(1).optional(), lastMessageId: z.string().min(1).nullish(),
lastMessageAt: z.string().min(1), lastMessageAt: z.string().min(1),
}) })
.strict(); .strict();
@ -84,7 +84,7 @@ export const storedChatMessageSchema = z
profileId: z.string().min(1), profileId: z.string().min(1),
slot: activeSlotKindSchema, slot: activeSlotKindSchema,
serverInstanceId: z.string().min(1), serverInstanceId: z.string().min(1),
remoteUsername: z.string().min(1).optional(), remoteUsername: z.string().min(1).nullish(),
sessionId: z.string().min(1), sessionId: z.string().min(1),
messageId: z.string().min(1), messageId: z.string().min(1),
role: z.enum(["user", "assistant", "system"]), role: z.enum(["user", "assistant", "system"]),
@ -95,6 +95,62 @@ export const storedChatMessageSchema = z
}) })
.strict(); .strict();
export type StoredChatMessage = z.infer<typeof storedChatMessageSchema>;
export function mergeLoadedChatMessages(
current: ChatMessage[],
records: StoredChatMessage[],
slot: ChatSlot,
sessionId: string,
): ChatMessage[] {
const sessionMessages = current.filter(
(message) => message.slot === slot && message.sessionId === sessionId,
);
const persistedUserCounts = new Map<string, number>();
for (const record of records) {
if (record.role !== "user") continue;
persistedUserCounts.set(
record.content,
(persistedUserCounts.get(record.content) ?? 0) + 1,
);
}
const optimisticMessages = sessionMessages.filter((message) => {
if (!message.id.startsWith("local-") || message.role !== "user") {
return false;
}
const count = persistedUserCounts.get(message.content) ?? 0;
if (count === 0) return true;
persistedUserCounts.set(message.content, count - 1);
return false;
});
const streamingMessages = sessionMessages.filter(
(message) => message.streaming && !message.id.startsWith("local-"),
);
const loadedMessages = records.map((record) => ({
id: record.messageId,
sessionId: record.sessionId,
slot: record.slot,
role: record.role,
content: record.content,
streaming: record.streaming,
error: record.error,
}));
const next = current
.filter(
(message) => message.slot !== slot || message.sessionId !== sessionId,
)
.concat(loadedMessages, streamingMessages, optimisticMessages);
const seen = new Set<string>();
return next.filter((message) => {
const key = message.slot + ":" + (message.sessionId ?? "") + ":" + message.id;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
export const astrbotModelOptionSchema = z.object({ export const astrbotModelOptionSchema = z.object({
id: z.string().min(1), id: z.string().min(1),
name: z.string().min(1).optional(), name: z.string().min(1).optional(),

查看文件

@ -1,4 +1,4 @@
:root { :root {
font-family: font-family:
Inter, Inter,
ui-sans-serif, ui-sans-serif,
@ -3086,3 +3086,300 @@ button:disabled {
animation: none !important; animation: none !important;
} }
} }
.chat-message-content {
display: flex;
flex: 1 1 auto;
flex-direction: column;
width: 0;
min-width: 0;
gap: 0.35rem;
}
.chat-message-row.assistant .chat-message-content,
.chat-message-row.system .chat-message-content {
align-items: flex-start;
}
.chat-message-row.user .chat-message-content {
align-items: flex-end;
}
.chat-bubble {
width: fit-content;
max-width: 100%;
}
.chat-message-actions {
display: flex;
align-items: center;
justify-content: flex-start;
gap: 0.15rem;
min-height: 2rem;
padding-inline: 0.15rem;
opacity: 0;
pointer-events: none;
transform: translateY(-0.2rem);
transition:
opacity 150ms ease,
transform 150ms ease,
visibility 150ms ease;
visibility: hidden;
}
.chat-message-row:hover .chat-message-actions,
.chat-message-row:focus-within .chat-message-actions {
opacity: 1;
pointer-events: auto;
transform: translateY(0);
visibility: visible;
}
.chat-message-actions button {
display: inline-flex;
align-items: center;
justify-content: center;
width: 2rem;
min-height: 2rem;
padding: 0;
border: 1px solid transparent;
border-radius: 0.55rem;
color: var(--ui-subtle);
background: transparent;
cursor: pointer;
}
.chat-message-actions button:hover:not(:disabled),
.chat-message-actions button:focus-visible {
border-color: var(--ui-line);
color: var(--ui-ink);
background: var(--ui-surface-soft);
}
.message-action-label {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
.message-action-icon {
display: inline-grid;
position: relative;
width: 1rem;
height: 1rem;
place-items: center;
color: var(--ui-muted);
line-height: 1;
}
.message-action-icon::before,
.message-action-icon::after {
position: absolute;
display: block;
content: "";
}
.icon-copy::before,
.icon-copy::after {
width: 0.62rem;
height: 0.7rem;
border: 1.5px solid currentcolor;
border-radius: 0.16rem;
}
.icon-copy::before {
top: 0.08rem;
left: 0.22rem;
background: var(--ui-surface-soft);
}
.icon-copy::after {
top: 0.23rem;
left: 0.08rem;
background: transparent;
}
.icon-retry::before {
width: 0.82rem;
height: 0.82rem;
border: 1.5px solid currentcolor;
border-right-color: transparent;
border-radius: 50%;
}
.icon-retry::after {
top: 0.02rem;
right: 0.02rem;
width: 0.32rem;
height: 0.32rem;
border-top: 1.5px solid currentcolor;
border-right: 1.5px solid currentcolor;
transform: rotate(18deg);
}
.icon-read::before {
width: 0.94rem;
height: 0.62rem;
border: 1.5px solid currentcolor;
border-radius: 0.72rem / 0.52rem;
transform: scaleY(0.78);
}
.icon-read::after {
width: 0.28rem;
height: 0.28rem;
border: 1.5px solid currentcolor;
border-radius: 50%;
}
@media (hover: none) {
.chat-message-actions {
opacity: 1;
pointer-events: auto;
transform: none;
visibility: visible;
}
}
.chat-send-button {
display: inline-flex;
min-width: 6.5rem;
min-height: 3.75rem;
align-items: center;
justify-content: center;
gap: 0.4rem;
border-color: var(--ui-accent);
border-radius: var(--ui-radius-md);
color: #071321;
background: var(--ui-accent);
font-size: 0.95rem;
font-weight: 700;
}
.chat-send-button:hover:not(:disabled) {
background: var(--ui-accent-strong);
}
.send-button-icon {
font-size: 1.2rem;
line-height: 1;
}
.chat-composer textarea {
resize: none;
}
@media (max-width: 680px) {
.chat-send-button {
min-width: 5.5rem;
min-height: 3.25rem;
}
.chat-message-actions button {
min-height: 2.1rem;
}
}
/* Stable chat session pills and native-style window controls. */
.chat-session-list {
flex: 0 0 auto;
min-width: 0;
max-width: 100%;
align-items: stretch;
overflow-x: auto;
overflow-y: hidden;
scrollbar-gutter: stable;
}
.chat-session {
flex: 0 0 10.5rem;
min-width: 0;
min-height: 3.35rem;
max-width: 10.5rem;
overflow: hidden;
}
.chat-session strong,
.chat-session small {
display: block;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.chat-session strong {
color: var(--ui-ink);
font-size: 0.82rem;
}
.chat-session small {
color: var(--ui-subtle);
font-size: 0.7rem;
}
.window-chrome {
box-sizing: border-box;
padding-right: 0;
}
.window-chrome-actions {
flex: 0 0 auto;
gap: 0.5rem;
margin-left: auto;
}
.window-controls {
flex: 0 0 auto;
}
.window-control {
flex: 0 0 46px;
width: 46px;
}
@media (max-width: 900px) {
.chat-heading {
align-items: stretch;
}
.chat-slot-tabs {
width: 100%;
justify-content: stretch;
}
.chat-slot {
flex: 1 1 0;
min-width: 0;
}
}
.message-attachment-image {
display: block;
max-width: min(22rem, 100%);
max-height: 22rem;
border: 1px solid var(--ui-line);
border-radius: var(--ui-radius-sm);
object-fit: contain;
background: var(--ui-surface-soft);
}
.message-attachment-placeholder {
display: inline-flex;
align-items: center;
min-height: 2rem;
padding: 0.35rem 0.55rem;
border: 1px dashed var(--ui-line-strong);
border-radius: var(--ui-radius-sm);
color: var(--ui-subtle);
background: var(--ui-surface-soft);
font-size: 0.78rem;
}