From 06e0b411ead7f8d79b26b3738479fae0a982b597 Mon Sep 17 00:00:00 2001 From: YokiiroBW Date: Mon, 20 Jul 2026 14:32:07 +0800 Subject: [PATCH] feat(chat): add remote session navigation --- docs/implementation-queue.md | 9 ++ docs/progress.md | 7 + src-tauri/src/lib.rs | 2 + src-tauri/src/networking/astrbot_client.rs | 8 ++ src-tauri/src/networking/commands.rs | 42 ++++++ src-tauri/src/networking/runtime.rs | 60 +++++++++ src/features/chat/ChatPanel.tsx | 142 +++++++++++++++++++-- src/features/chat/types.ts | 9 ++ src/styles.css | 4 + 9 files changed, 273 insertions(+), 10 deletions(-) diff --git a/docs/implementation-queue.md b/docs/implementation-queue.md index bc8ca55..80e80c2 100644 --- a/docs/implementation-queue.md +++ b/docs/implementation-queue.md @@ -176,3 +176,12 @@ remote_username 用于远端聊天身份和会话命名,不作为本机权限 - 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. + + +### Q3.2: Remote session navigation + +- Expose the active AstrBot session list through the slot runtime without creating a second network client. +- Allow switching the sticky session ID inside one slot and reload only that session history. +- Keep message identity scoped by slot and session ID so switching sessions cannot mix content. + +Acceptance: a connected slot can display remote sessions and switch between them without affecting the other slot. diff --git a/docs/progress.md b/docs/progress.md index f95d615..4f694a3 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -143,3 +143,10 @@ Still not claimed complete: automatic startup activation, real Tauri multi-windo - First test container accepted text plus config selection and streamed a complete response with no error frame. - The same session accepted text plus config selection plus the uploaded attachment and streamed a complete response with no error frame. - This validates the current model/config and attachment request contract against a real AstrBot instance. + + +## 2026-07-20: remote session navigation + +- Added slot-scoped remote session discovery and sticky session switching IPC. +- ChatPanel now displays remote sessions and reloads history after switching; message filtering includes sessionId. +- Validation: Rust workspace tests, Clippy, TypeScript, ESLint, Vitest, and Vite build passed. diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 6df812a..dbcfa6a 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -208,6 +208,8 @@ pub fn run() { networking::commands::disconnect_connection_slot, networking::commands::send_connection_slot_message, networking::commands::connection_slot_capabilities, + networking::commands::connection_slot_sessions, + networking::commands::switch_connection_slot_session, networking::commands::upload_connection_slot_file, networking::commands::cancel_connection_slot_message, ]) diff --git a/src-tauri/src/networking/astrbot_client.rs b/src-tauri/src/networking/astrbot_client.rs index c11f0e7..b1a9bb8 100644 --- a/src-tauri/src/networking/astrbot_client.rs +++ b/src-tauri/src/networking/astrbot_client.rs @@ -208,6 +208,14 @@ impl AstrBotClient { })) } + pub async fn set_session_id(&self, session_id: String) -> Result<(), AstrBotClientError> { + if session_id.trim().is_empty() { + return Err(AstrBotClientError::InvalidConfig("session_id is required")); + } + *self.session_id.lock().await = Some(session_id); + Ok(()) + } + pub async fn list_sessions(&self) -> Result { let response = self .http diff --git a/src-tauri/src/networking/commands.rs b/src-tauri/src/networking/commands.rs index 43a1e00..da08683 100644 --- a/src-tauri/src/networking/commands.rs +++ b/src-tauri/src/networking/commands.rs @@ -469,6 +469,48 @@ pub async fn cancel_connection_slot_message( ) -> Result<(), RuntimeCommandError> { runtime.cancel_slot_message(request.slot).await } +#[derive(Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ChatRemoteSession { + pub session_id: String, + pub display_name: Option, + pub updated_at: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SwitchChatSessionRequest { + pub slot: SlotKind, + pub session_id: String, +} + +#[tauri::command] +pub async fn connection_slot_sessions( + runtime: State<'_, DualSlotRuntime>, + request: SlotCapabilitiesRequest, +) -> Result, RuntimeCommandError> { + let sessions = runtime.slot_sessions(request.slot).await?; + Ok(sessions + .sessions + .into_iter() + .map(|session| ChatRemoteSession { + session_id: session.session_id, + display_name: session.display_name, + updated_at: session.updated_at, + }) + .collect()) +} + +#[tauri::command] +pub async fn switch_connection_slot_session( + runtime: State<'_, DualSlotRuntime>, + request: SwitchChatSessionRequest, +) -> Result { + runtime + .switch_slot_session(request.slot, request.session_id) + .await +} + #[tauri::command] pub async fn connection_slot_capabilities( runtime: State<'_, DualSlotRuntime>, diff --git a/src-tauri/src/networking/runtime.rs b/src-tauri/src/networking/runtime.rs index 85cfc7c..ceead2a 100644 --- a/src-tauri/src/networking/runtime.rs +++ b/src-tauri/src/networking/runtime.rs @@ -299,6 +299,66 @@ impl DualSlotRuntime { cancellation.cancel(); Ok(()) } + pub async fn slot_sessions( + &self, + slot: SlotKind, + ) -> Result { + 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( + "Session lists are not available for the desktop mock transport.", + )); + } + None => { + return Err(RuntimeCommandError::unavailable( + "Activate the connection before loading sessions.", + )); + } + } + }; + client + .list_sessions() + .await + .map_err(|_| RuntimeCommandError::unavailable("AstrBot sessions are unavailable.")) + } + + pub async fn switch_slot_session( + &self, + slot: SlotKind, + session_id: String, + ) -> Result { + if session_id.trim().is_empty() { + return Err(RuntimeCommandError::validation("session_id is required.")); + } + 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( + "Session switching is not available for the desktop mock transport.", + )); + } + None => { + return Err(RuntimeCommandError::unavailable( + "Activate the connection before switching sessions.", + )); + } + } + }; + client + .set_session_id(session_id.clone()) + .await + .map_err(|_| RuntimeCommandError::validation("The session id is invalid."))?; + let mut guard = self.inner.lock().await; + let runtime = slot_mut(&mut guard, slot); + runtime.snapshot.active_session_id = Some(session_id); + Ok(runtime.snapshot.clone()) + } + pub async fn slot_capabilities( &self, slot: SlotKind, diff --git a/src/features/chat/ChatPanel.tsx b/src/features/chat/ChatPanel.tsx index d6e5e18..db48097 100644 --- a/src/features/chat/ChatPanel.tsx +++ b/src/features/chat/ChatPanel.tsx @@ -11,8 +11,10 @@ import { type AstrBotCapabilitySnapshot, type AstrBotModelOption, type BoundRuntimeEvent, + remoteChatSessionSchema, type ChatMessage, type ChatSlot, + type RemoteChatSession, type ConnectionRuntimeStatus, storedChatMessageSchema, } from "./types"; @@ -38,10 +40,16 @@ export interface ChatPanelProps { export function ChatPanel({ fixedSlot }: ChatPanelProps) { const [status, setStatus] = useState(emptyStatus); const [messages, setMessages] = useState([]); + const [remoteSessions, setRemoteSessions] = useState([]); const [activeSlot, setActiveSlot] = useState( fixedSlot ?? "companion", ); const selectedSlot = fixedSlot ?? activeSlot; + const selectedSnapshot = status[selectedSlot]; + const selectedProfileId = selectedSnapshot.profileId; + const selectedServerInstanceId = selectedSnapshot.serverInstanceId; + const selectedSessionId = selectedSnapshot.activeSessionId; + const selectedTransport = selectedSnapshot.transport; const [draft, setDraft] = useState(""); const [error, setError] = useState(null); const [capabilities, setCapabilities] = @@ -56,8 +64,14 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { operations: 0, }); const activeMessages = useMemo( - () => messages.filter((item) => item.slot === selectedSlot), - [messages, selectedSlot], + () => + messages.filter( + (item) => + item.slot === selectedSlot && + (!status[selectedSlot].activeSessionId || + item.sessionId === status[selectedSlot].activeSessionId), + ), + [messages, selectedSlot, status], ); const refresh = useCallback(async () => { @@ -86,7 +100,12 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { }, []); useEffect(() => { - const snapshot = status[selectedSlot]; + const snapshot = { + profileId: selectedProfileId, + serverInstanceId: selectedServerInstanceId, + activeSessionId: selectedSessionId, + transport: selectedTransport, + }; if (!snapshot.profileId || !snapshot.serverInstanceId) return; let cancelled = false; void invoke("list_chat_sessions", { @@ -110,10 +129,50 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { return () => { cancelled = true; }; - }, [selectedSlot, status]); + }, [ + selectedSlot, + selectedProfileId, + selectedServerInstanceId, + selectedSessionId, + selectedTransport, + ]); useEffect(() => { - const snapshot = status[selectedSlot]; + const snapshot = { + profileId: selectedProfileId, + serverInstanceId: selectedServerInstanceId, + activeSessionId: selectedSessionId, + transport: selectedTransport, + }; + setRemoteSessions([]); + if (!snapshot.profileId) return; + let cancelled = false; + void invoke("connection_slot_sessions", { + request: { slot: selectedSlot }, + }) + .then((result) => { + if (cancelled) return; + setRemoteSessions(remoteChatSessionSchema.array().parse(result)); + }) + .catch(() => undefined); + return () => { + cancelled = true; + }; + }, [ + selectedSlot, + selectedProfileId, + selectedServerInstanceId, + selectedSessionId, + selectedTransport, + ]); + + useEffect(() => { + const snapshot = { + profileId: selectedProfileId, + serverInstanceId: selectedServerInstanceId, + activeSessionId: selectedSessionId, + transport: selectedTransport, + }; setCapabilities(null); setSelectedModel(""); if (!snapshot.profileId || snapshot.transport !== "astrbot-openapi") return; @@ -135,10 +194,21 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { return () => { cancelled = true; }; - }, [selectedSlot, status]); + }, [ + selectedSlot, + selectedProfileId, + selectedServerInstanceId, + selectedSessionId, + selectedTransport, + ]); useEffect(() => { - const snapshot = status[selectedSlot]; + const snapshot = { + profileId: selectedProfileId, + serverInstanceId: selectedServerInstanceId, + activeSessionId: selectedSessionId, + transport: selectedTransport, + }; if ( !snapshot.profileId || !snapshot.serverInstanceId || @@ -153,10 +223,21 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { }, }).catch(() => undefined); setUnreadCounts((current) => ({ ...current, [selectedSlot]: 0 })); - }, [selectedSlot, status]); + }, [ + selectedSlot, + selectedProfileId, + selectedServerInstanceId, + selectedSessionId, + selectedTransport, + ]); useEffect(() => { - const snapshot = status[selectedSlot]; + const snapshot = { + profileId: selectedProfileId, + serverInstanceId: selectedServerInstanceId, + activeSessionId: selectedSessionId, + transport: selectedTransport, + }; if ( !snapshot.profileId || !snapshot.serverInstanceId || @@ -181,6 +262,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { .concat( records.map((record) => ({ id: record.messageId, + sessionId: record.sessionId, slot: record.slot, role: record.role, content: record.content, @@ -194,7 +276,13 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { return () => { cancelled = true; }; - }, [selectedSlot, status]); + }, [ + selectedSlot, + selectedProfileId, + selectedServerInstanceId, + selectedSessionId, + selectedTransport, + ]); useEffect(() => { let timer: number | undefined; @@ -250,6 +338,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { setMessages((current) => current.concat({ id, + sessionId: status[selectedSlot].activeSessionId, slot: selectedSlot, role: "user", content: message, @@ -311,6 +400,35 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { Session:{status[selectedSlot].activeSessionId ?? "未建立"} 状态:{connectionStateLabel(status[selectedSlot].state)} + {remoteSessions.length > 0 ? ( +
+ {remoteSessions.map((session) => ( + + ))} +
+ ) : null}
{activeMessages.length === 0 ? (

@@ -440,6 +558,7 @@ function applyRuntimeEvents( } else next.push({ id, + sessionId: event.sessionId, slot: event.slot, role: "assistant", content: delta, @@ -455,6 +574,7 @@ function applyRuntimeEvents( else next.push({ id, + sessionId: event.sessionId, slot: event.slot, role: "assistant", content: payloadString(event, "content") || "", @@ -462,6 +582,7 @@ function applyRuntimeEvents( } else if (event.eventType === "error") { next.push({ id: event.eventId, + sessionId: event.sessionId, slot: event.slot, role: "system", content: payloadString(event, "message") || "连接错误", @@ -470,6 +591,7 @@ function applyRuntimeEvents( } else if (event.eventType === "message.proactive") { next.push({ id: event.eventId, + sessionId: event.sessionId, slot: event.slot, role: "assistant", content: payloadString(event, "content") || "", diff --git a/src/features/chat/types.ts b/src/features/chat/types.ts index 8efb73f..571cccd 100644 --- a/src/features/chat/types.ts +++ b/src/features/chat/types.ts @@ -58,10 +58,19 @@ export const chatSessionSchema = z .strict(); export type ChatSession = z.infer; + +export const remoteChatSessionSchema = z.object({ + sessionId: z.string().min(1), + displayName: z.string().min(1).optional(), + updatedAt: z.string().min(1).optional(), +}); + +export type RemoteChatSession = z.infer; export type ChatSlot = ActiveSlotKind; export interface ChatMessage { id: string; + sessionId?: string; slot: ChatSlot; role: "user" | "assistant" | "system"; content: string; diff --git a/src/styles.css b/src/styles.css index 7adc15b..d663ea4 100644 --- a/src/styles.css +++ b/src/styles.css @@ -1129,3 +1129,7 @@ select:focus { .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; } +.chat-session-list { display: flex; gap: .55rem; overflow-x: auto; padding: .15rem 0 .35rem; } +.chat-session { display: grid; min-width: 11rem; gap: .2rem; padding: .65rem .75rem; border: 1px solid rgb(137 175 232 / 24%); border-radius: .7rem; color: #c7d4e9; background: rgb(7 18 34 / 55%); text-align: left; } +.chat-session:hover, .chat-session.active { border-color: #7db0ff; background: rgb(36 80 140 / 52%); } +.chat-session small { color: #91a7c9; font-size: .7rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }