From d100da324dde2553b28bc187cef944f822e8d190 Mon Sep 17 00:00:00 2001 From: YokiiroBW Date: Wed, 22 Jul 2026 02:52:31 +0800 Subject: [PATCH] fix(chat): prevent duplicate history on session switch --- crates/desktop-protocol/src/astrbot.rs | 71 ++++- src-tauri/src/lib.rs | 1 + src-tauri/src/networking/astrbot_client.rs | 42 ++- src-tauri/src/networking/commands.rs | 78 +++++- src-tauri/src/networking/mod.rs | 10 +- src-tauri/src/networking/runtime.rs | 27 ++ src/App.tsx | 9 +- src/features/chat/ChatPanel.tsx | 194 ++++++++----- src/features/chat/MessageContent.tsx | 122 ++++++++- src/features/chat/types.test.ts | 85 ++++++ src/features/chat/types.ts | 62 ++++- src/styles.css | 299 ++++++++++++++++++++- 12 files changed, 902 insertions(+), 98 deletions(-) create mode 100644 src/features/chat/types.test.ts diff --git a/crates/desktop-protocol/src/astrbot.rs b/crates/desktop-protocol/src/astrbot.rs index 96a593f..08e9469 100644 --- a/crates/desktop-protocol/src/astrbot.rs +++ b/crates/desktop-protocol/src/astrbot.rs @@ -213,6 +213,11 @@ pub fn parse_astrbot_sse_line(line: &str) -> Result, } impl AstrBotStreamMapper { @@ -265,6 +271,7 @@ impl AstrBotStreamMapper { } "user_message_saved" => Vec::new(), "plain" => self.map_plain(frame), + "image" | "record" | "file" | "video" => self.map_media(frame), "complete" => self.map_complete(frame), "agent_stats" => { let detail = frame.data.to_string(); @@ -300,11 +307,51 @@ impl AstrBotStreamMapper { )); events } - "attachment_saved" => Vec::new(), + "attachment_saved" => self.map_attachment_saved(frame), _ => Vec::new(), } } + fn map_media(&mut self, frame: AstrBotStreamFrame) -> Vec { + 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 { + 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 { let chunk = text_from_value(&frame.data).unwrap_or_default(); 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] fn derives_stable_instance_ids() { let a = derive_astrbot_server_instance_id("http://192.168.31.210:26285/"); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index fc4645e..51fc93c 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -662,6 +662,7 @@ pub fn run() { networking::commands::connection_slot_sessions, networking::commands::switch_connection_slot_session, networking::commands::upload_connection_slot_file, + networking::commands::download_connection_slot_attachment, networking::commands::cancel_connection_slot_message, ]) .run(tauri::generate_context!()) diff --git a/src-tauri/src/networking/astrbot_client.rs b/src-tauri/src/networking/astrbot_client.rs index b1b2896..8a78325 100644 --- a/src-tauri/src/networking/astrbot_client.rs +++ b/src-tauri/src/networking/astrbot_client.rs @@ -7,7 +7,7 @@ use desktop_protocol::{ derive_astrbot_server_instance_id, }; 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 serde_json::{Value, json}; use thiserror::Error; @@ -349,6 +349,46 @@ impl AstrBotClient { }) } + pub async fn download_attachment( + &self, + attachment_id: &str, + ) -> Result<(String, Vec), 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( &self, message: &str, diff --git a/src-tauri/src/networking/commands.rs b/src-tauri/src/networking/commands.rs index 5d1ec4b..9eaeb4e 100644 --- a/src-tauri/src/networking/commands.rs +++ b/src-tauri/src/networking/commands.rs @@ -1,7 +1,7 @@ // IPC wrappers for dual-slot runtime. Secrets never leave Rust. use desktop_protocol::TransportKind; use secrecy::SecretString; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use serde_json::Value; use tauri::State; use tracing::{info, warn}; @@ -46,6 +46,20 @@ pub struct SlotFileUploadRequest { pub bytes: Vec, } +#[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, +} + #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] 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] pub async fn connection_runtime_status( runtime: State<'_, DualSlotRuntime>, @@ -134,12 +174,15 @@ pub async fn auto_connect_configured_slots( }; match runtime.activate_slot(activation).await { - Ok(snapshot) => info!( - profile_id = %profile_id, - slot = ?slot, - state = ?snapshot.state, - "startup auto-connect completed" - ), + Ok(snapshot) => { + persist_session_identity(database, &snapshot); + info!( + profile_id = %profile_id, + slot = ?slot, + state = ?snapshot.state, + "startup auto-connect completed" + ); + } Err(error) => warn!( profile_id = %profile_id, slot = ?slot, @@ -530,12 +573,15 @@ pub async fn connection_slot_sessions( #[tauri::command] pub async fn switch_connection_slot_session( + database: State<'_, ApplicationDatabase>, runtime: State<'_, DualSlotRuntime>, request: SwitchChatSessionRequest, ) -> Result { - runtime + let snapshot = runtime .switch_slot_session(request.slot, request.session_id) - .await + .await?; + persist_session_identity(&database, &snapshot); + Ok(snapshot) } #[tauri::command] @@ -546,6 +592,17 @@ pub async fn connection_slot_capabilities( runtime.slot_capabilities(request.slot).await } +#[tauri::command] +pub async fn download_connection_slot_attachment( + runtime: State<'_, DualSlotRuntime>, + request: DownloadConnectionSlotAttachmentRequest, +) -> Result { + let (mime_type, bytes) = runtime + .download_slot_attachment(request.slot, request.attachment_id) + .await?; + Ok(DownloadConnectionSlotAttachmentResponse { mime_type, bytes }) +} + #[tauri::command] pub async fn upload_connection_slot_file( runtime: State<'_, DualSlotRuntime>, @@ -627,5 +684,8 @@ pub async fn send_connection_slot_message( false, ); } + if let Ok(snapshot) = &result { + persist_session_identity(&database, snapshot); + } result } diff --git a/src-tauri/src/networking/mod.rs b/src-tauri/src/networking/mod.rs index 19b9617..007a67d 100644 --- a/src-tauri/src/networking/mod.rs +++ b/src-tauri/src/networking/mod.rs @@ -6,11 +6,11 @@ mod runtime; pub use astrbot_client::{AstrBotClient, AstrBotClientConfig, AstrBotClientError}; pub use commands::{ - DisconnectConnectionSlotRequest, DrainConnectionRuntimeEventsRequest, ListChatSessionsRequest, - MarkChatSessionReadRequest, ProbeConnectionSlotRequest, SendConnectionSlotMessageRequest, - auto_connect_configured_slots, cancel_connection_slot_message, connection_runtime_status, - disconnect_connection_slot, drain_connection_runtime_events, probe_connection_slot, - send_connection_slot_message, + DisconnectConnectionSlotRequest, DownloadConnectionSlotAttachmentRequest, + DrainConnectionRuntimeEventsRequest, ListChatSessionsRequest, MarkChatSessionReadRequest, + ProbeConnectionSlotRequest, SendConnectionSlotMessageRequest, auto_connect_configured_slots, + cancel_connection_slot_message, 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}; diff --git a/src-tauri/src/networking/runtime.rs b/src-tauri/src/networking/runtime.rs index e8d0693..15dcd17 100644 --- a/src-tauri/src/networking/runtime.rs +++ b/src-tauri/src/networking/runtime.rs @@ -502,6 +502,33 @@ impl DualSlotRuntime { .map_err(|_| RuntimeCommandError::unavailable("AstrBot capabilities are unavailable.")) } + pub async fn download_slot_attachment( + &self, + slot: SlotKind, + attachment_id: String, + ) -> Result<(String, Vec), 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( &self, slot: SlotKind, diff --git a/src/App.tsx b/src/App.tsx index f4ec5ca..7e60089 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -274,7 +274,14 @@ function WindowChrome({ data-tauri-drag-region onDoubleClick={() => void toggleMaximize()} 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(); + } }} > AstrBot Desktop diff --git a/src/features/chat/ChatPanel.tsx b/src/features/chat/ChatPanel.tsx index 5aa03c9..820386f 100644 --- a/src/features/chat/ChatPanel.tsx +++ b/src/features/chat/ChatPanel.tsx @@ -13,6 +13,8 @@ import { type AstrBotAttachment, type AstrBotCapabilitySnapshot, type BoundRuntimeEvent, + type ChatSession, + mergeLoadedChatMessages, remoteChatSessionSchema, type ChatMessage, type ChatSlot, @@ -54,6 +56,12 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { const [status, setStatus] = useState(emptyStatus); const [messages, setMessages] = useState([]); const [remoteSessions, setRemoteSessions] = useState([]); + const [storedSessions, setStoredSessions] = useState< + Record + >({ + companion: [], + operations: [], + }); const [activeSlot, setActiveSlot] = useState( fixedSlot ?? "companion", ); @@ -62,6 +70,8 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { const selectedProfileId = selectedSnapshot.profileId; const selectedServerInstanceId = selectedSnapshot.serverInstanceId; const selectedSessionId = selectedSnapshot.activeSessionId; + const historySessionId = + selectedSessionId ?? storedSessions[selectedSlot][0]?.sessionId; const selectedTransport = selectedSnapshot.transport; const [draft, setDraft] = useState(""); const [error, setError] = useState(null); @@ -105,6 +115,15 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { [activeMessages], ); + const displaySessions = + remoteSessions.length > 0 + ? remoteSessions + : storedSessions[selectedSlot].map((session) => ({ + sessionId: session.sessionId, + displayName: undefined, + updatedAt: session.lastMessageAt, + })); + const refresh = useCallback(async () => { try { const result = await invoke("connection_runtime_status"); @@ -154,6 +173,11 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { .then((result) => { if (cancelled) return; const sessions = chatSessionSchema.array().parse(result); + setStoredSessions((current) => ({ + ...current, + [selectedSlot]: sessions, + })); + setUnreadCounts((current) => ({ ...current, [selectedSlot]: sessions.reduce( @@ -171,6 +195,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { selectedProfileId, selectedServerInstanceId, selectedSessionId, + historySessionId, selectedTransport, ]); @@ -200,6 +225,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { selectedProfileId, selectedServerInstanceId, selectedSessionId, + historySessionId, selectedTransport, ]); @@ -231,6 +257,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { selectedProfileId, selectedServerInstanceId, selectedSessionId, + historySessionId, selectedTransport, ]); @@ -238,7 +265,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { const snapshot = { profileId: selectedProfileId, serverInstanceId: selectedServerInstanceId, - activeSessionId: selectedSessionId, + activeSessionId: historySessionId, transport: selectedTransport, }; if ( @@ -261,6 +288,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { selectedProfileId, selectedServerInstanceId, selectedSessionId, + historySessionId, selectedTransport, ]); @@ -268,7 +296,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { const snapshot = { profileId: selectedProfileId, serverInstanceId: selectedServerInstanceId, - activeSessionId: selectedSessionId, + activeSessionId: historySessionId, transport: selectedTransport, }; if ( @@ -290,32 +318,14 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { .then((result) => { if (cancelled) return; const records = storedChatMessageSchema.array().parse(result); - setMessages((current) => { - const localUserMessages = current.filter( - (item) => - (item.id.startsWith("local-") || item.streaming) && - item.slot === selectedSlot && - item.sessionId === 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, - })), - ); - }); + setMessages((current) => + mergeLoadedChatMessages( + current, + records, + selectedSlot, + snapshot.activeSessionId, + ), + ); }) .catch(() => undefined); return () => { @@ -326,6 +336,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { selectedProfileId, selectedServerInstanceId, selectedSessionId, + historySessionId, selectedTransport, ]); @@ -450,7 +461,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { await navigator.clipboard.writeText(content); setError(null); } catch { - setError("Copy failed. Check clipboard permissions."); + setError("复制失败,请检查剪贴板权限。"); } }; @@ -577,7 +588,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
-

Shared chat runtime

+

共享聊天运行时

统一聊天运行时

主界面、快速聊天和气泡共享同一套消息状态。 @@ -621,35 +632,33 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {

- Profile - {status[selectedSlot].profileId ?? "Not connected"} + 配置 + {status[selectedSlot].profileId ?? "未连接"}
- Session - - {status[selectedSlot].activeSessionId ?? "New session"} - + 会话 + {status[selectedSlot].activeSessionId ?? "新会话"}
- Status + 状态 {connectionStateLabel(status[selectedSlot].state)}
@@ -669,9 +678,9 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
) : null} - {remoteSessions.length > 0 ? ( + {displaySessions.length > 0 ? (
- {remoteSessions.map((session) => ( + {displaySessions.map((session, index) => ( ))}
@@ -708,7 +718,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { > {visibleMessages.length === 0 ? (

- No messages in this slot yet. Connect a Profile to start chatting. + 当前槽位还没有消息。连接 Profile 后即可开始聊天。

) : ( visibleMessages.map((message) => { @@ -724,43 +734,63 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { ? "A" : "!"} -
-
- - {message.role === "user" - ? "You" - : message.role === "assistant" - ? "AstrBot" - : "System"} - - {message.streaming ? Generating : null} +
+
+
+ + {message.role === "user" + ? "你" + : message.role === "assistant" + ? "AstrBot" + : "系统"} + + {message.streaming ? 生成中 : null} +
+ {message.content ? ( + + ) : ( +

正在生成…

+ )}
- {message.content ? ( - - ) : ( -

Generating?

- )} {message.role === "assistant" && message.content && !message.streaming ? ( -
+
) : null} @@ -770,7 +800,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { type="button" onClick={() => void stopGeneration()} > - Stop generating + 停止生成 ) : null}
@@ -843,19 +873,33 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { onChange={(event) => setDraft(event.target.value)} placeholder={ selectedSlot === "companion" - ? "和陪伴实例说点什么…" - : "向运维实例描述问题…" + ? "和陪伴实例说点什么…(Enter 发送,Shift+Enter 换行)" + : "向运维实例描述问题…(Enter 发送,Shift+Enter 换行)" } value={draft} rows={3} + onKeyDown={(event) => { + if ( + event.key !== "Enter" || + event.shiftKey || + event.nativeEvent.isComposing + ) + return; + event.preventDefault(); + void send(); + }} />
@@ -940,6 +984,18 @@ function applyRuntimeEvents( 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( state: ConnectionRuntimeStatus["companion"]["state"], ): string { diff --git a/src/features/chat/MessageContent.tsx b/src/features/chat/MessageContent.tsx index d0dd789..316d4e9 100644 --- a/src/features/chat/MessageContent.tsx +++ b/src/features/chat/MessageContent.tsx @@ -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 = { content: string; + slot: ChatSlot; }; -function renderInline(text: string, keyPrefix: string): ReactNode[] { - const tokens = text.split(/(`[^`]+`|\*\*[^*]+\*\*|\[[^\]]+\]\([^)]+\))/g); +type DownloadedAttachment = { + mimeType?: unknown; + bytes?: unknown; +}; + +const emotionLabels: Record = { + 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, +): ReactNode[] { + const tokens = text.split( + /(!\[[^\]]*\]\(astrbot-attachment:\/\/[A-Za-z0-9._-]+\)|`[^`]+`|\*\*[^*]+\*\*|\[[^\]]+\]\([^)]+\))/g, + ); return tokens.map((token, index) => { const key = `${keyPrefix}-${index}`; + const image = token.match( + /^!\[([^\]]*)\]\(astrbot-attachment:\/\/([A-Za-z0-9._-]+)\)$/, + ); + if (image) { + const source = imageUrls[image[2]]; + return source ? ( + {image[1] + ) : ( + + image loading + + ); + } if (token.startsWith("`") && token.endsWith("`")) { return {token.slice(1, -1)}; } @@ -26,8 +75,65 @@ function renderInline(text: string, keyPrefix: string): ReactNode[] { }); } -export function MessageContent({ content }: MessageContentProps) { - const lines = content.replaceAll("\r\n", "\n").split("\n"); +export function MessageContent({ content, slot }: MessageContentProps) { + const [imageUrls, setImageUrls] = useState>({}); + 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( + "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[] = []; let codeLines: string[] | null = null; let codeLanguage = ""; @@ -38,7 +144,7 @@ export function MessageContent({ content }: MessageContentProps) { if (!paragraph.length) return; blocks.push(

- {renderInline(paragraph.join(" "), `paragraph-${blocks.length}`)} + {renderInline(paragraph.join(" "), `paragraph-${blocks.length}`, imageUrls)}

, ); paragraph = []; @@ -49,7 +155,7 @@ export function MessageContent({ content }: MessageContentProps) {
    {list.map((item, index) => (
  • - {renderInline(item, `list-${blocks.length}-${index}`)} + {renderInline(item, `list-${blocks.length}-${index}`, imageUrls)}
  • ))}
, @@ -92,7 +198,7 @@ export function MessageContent({ content }: MessageContentProps) { const Heading = `h${level}` as "h1" | "h2" | "h3"; blocks.push( - {renderInline(heading[2], `heading-${index}`)} + {renderInline(heading[2], `heading-${index}`, imageUrls)} , ); return; diff --git a/src/features/chat/types.test.ts b/src/features/chat/types.test.ts new file mode 100644 index 0000000..2fd6154 --- /dev/null +++ b/src/features/chat/types.test.ts @@ -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"); + }); +}); \ No newline at end of file diff --git a/src/features/chat/types.ts b/src/features/chat/types.ts index 258c4b3..fb26236 100644 --- a/src/features/chat/types.ts +++ b/src/features/chat/types.ts @@ -49,10 +49,10 @@ export const chatSessionSchema = z profileId: z.string().min(1), slot: activeSlotKindSchema, serverInstanceId: z.string().min(1), - remoteUsername: z.string().min(1).optional(), + remoteUsername: z.string().min(1).nullish(), sessionId: z.string().min(1), unreadCount: z.number().int().nonnegative(), - lastMessageId: z.string().min(1).optional(), + lastMessageId: z.string().min(1).nullish(), lastMessageAt: z.string().min(1), }) .strict(); @@ -84,7 +84,7 @@ export const storedChatMessageSchema = z profileId: z.string().min(1), slot: activeSlotKindSchema, serverInstanceId: z.string().min(1), - remoteUsername: z.string().min(1).optional(), + remoteUsername: z.string().min(1).nullish(), sessionId: z.string().min(1), messageId: z.string().min(1), role: z.enum(["user", "assistant", "system"]), @@ -95,6 +95,62 @@ export const storedChatMessageSchema = z }) .strict(); +export type StoredChatMessage = z.infer; + +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(); + 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(); + 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({ id: z.string().min(1), name: z.string().min(1).optional(), diff --git a/src/styles.css b/src/styles.css index eb00f34..3ba9d28 100644 --- a/src/styles.css +++ b/src/styles.css @@ -1,4 +1,4 @@ -:root { +:root { font-family: Inter, ui-sans-serif, @@ -3086,3 +3086,300 @@ button:disabled { 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; +}