feat/p02-dual-connections #3
共有 6 个文件被更改,包括 302 次插入 和 9 次删除
|
|
@ -7,7 +7,7 @@ use time::{OffsetDateTime, format_description::well_known::Rfc3339};
|
|||
use rusqlite::{Connection, OptionalExtension, params};
|
||||
use thiserror::Error;
|
||||
|
||||
pub const CURRENT_SCHEMA_VERSION: u32 = 5;
|
||||
pub const CURRENT_SCHEMA_VERSION: u32 = 6;
|
||||
|
||||
pub struct ApplicationDatabase {
|
||||
store: Mutex<ProfileMessageStore>,
|
||||
|
|
@ -67,6 +67,29 @@ impl ApplicationDatabase {
|
|||
)
|
||||
}
|
||||
|
||||
pub fn list_chat_sessions(
|
||||
&self,
|
||||
profile_id: &str,
|
||||
server_instance_id: &str,
|
||||
) -> Result<Vec<StoredChatSession>, DatabaseError> {
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||
.list_chat_sessions(profile_id, server_instance_id)
|
||||
}
|
||||
|
||||
pub fn mark_chat_session_read(
|
||||
&self,
|
||||
profile_id: &str,
|
||||
server_instance_id: &str,
|
||||
session_id: &str,
|
||||
) -> Result<(), DatabaseError> {
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||
.mark_chat_session_read(profile_id, server_instance_id, session_id)
|
||||
}
|
||||
|
||||
pub fn list_chat_messages(
|
||||
&self,
|
||||
profile_id: &str,
|
||||
|
|
@ -86,6 +109,39 @@ pub struct ProfileMessageStore {
|
|||
}
|
||||
|
||||
impl ProfileMessageStore {
|
||||
pub fn list_chat_sessions(
|
||||
&self,
|
||||
profile_id: &str,
|
||||
server_instance_id: &str,
|
||||
) -> Result<Vec<StoredChatSession>, DatabaseError> {
|
||||
let mut statement = self.connection.prepare("SELECT account_id, profile_id, slot, server_instance_id, remote_username, session_id, unread_count, last_message_id, last_message_at FROM chat_sessions WHERE profile_id = ?1 AND server_instance_id = ?2 ORDER BY last_message_at DESC")?;
|
||||
let rows = statement.query_map(params![profile_id, server_instance_id], |row| {
|
||||
Ok(StoredChatSession {
|
||||
account_id: row.get(0)?,
|
||||
profile_id: row.get(1)?,
|
||||
slot: row.get(2)?,
|
||||
server_instance_id: row.get(3)?,
|
||||
remote_username: row.get(4)?,
|
||||
session_id: row.get(5)?,
|
||||
unread_count: row.get::<_, i64>(6)? as u32,
|
||||
last_message_id: row.get(7)?,
|
||||
last_message_at: row.get(8)?,
|
||||
})
|
||||
})?;
|
||||
rows.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(DatabaseError::from)
|
||||
}
|
||||
|
||||
pub fn mark_chat_session_read(
|
||||
&self,
|
||||
profile_id: &str,
|
||||
server_instance_id: &str,
|
||||
session_id: &str,
|
||||
) -> Result<(), DatabaseError> {
|
||||
self.connection.execute("UPDATE chat_sessions SET unread_count = 0 WHERE profile_id = ?1 AND server_instance_id = ?2 AND session_id = ?3", params![profile_id, server_instance_id, session_id])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn open(path: impl AsRef<Path>) -> Result<Self, DatabaseError> {
|
||||
Self::from_connection(Connection::open(path)?, true)
|
||||
}
|
||||
|
|
@ -156,10 +212,23 @@ impl ProfileMessageStore {
|
|||
let timestamp = OffsetDateTime::now_utc()
|
||||
.format(&Rfc3339)
|
||||
.map_err(|_| DatabaseError::InvalidStoredMessage)?;
|
||||
let was_streaming: Option<bool> = self
|
||||
.connection
|
||||
.query_row(
|
||||
"SELECT streaming != 0 FROM chat_messages WHERE profile_id = ?1 AND server_instance_id = ?2 AND session_id = ?3 AND message_id = ?4",
|
||||
params![profile_id, server_instance_id, session_id, message_id],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.optional()?;
|
||||
self.connection.execute(
|
||||
"INSERT INTO chat_messages (account_id, profile_id, slot, server_instance_id, remote_username, session_id, message_id, role, content, streaming, error, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12) ON CONFLICT(profile_id, server_instance_id, session_id, message_id) DO UPDATE SET content = excluded.content, streaming = excluded.streaming, error = excluded.error, updated_at = excluded.updated_at",
|
||||
params![account_id, profile_id, slot, server_instance_id, remote_username, session_id, message_id, role, content, streaming, error, timestamp],
|
||||
)?;
|
||||
let unread = role != "user" && !streaming && !error && was_streaming != Some(false);
|
||||
self.connection.execute(
|
||||
"INSERT INTO chat_sessions (account_id, profile_id, slot, server_instance_id, remote_username, session_id, unread_count, last_message_id, last_message_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9) ON CONFLICT(account_id, profile_id, slot, server_instance_id, session_id) DO UPDATE SET remote_username = COALESCE(excluded.remote_username, chat_sessions.remote_username), unread_count = chat_sessions.unread_count + CASE WHEN ?10 = 1 THEN 1 ELSE 0 END, last_message_id = excluded.last_message_id, last_message_at = excluded.last_message_at",
|
||||
params![account_id, profile_id, slot, server_instance_id, remote_username, session_id, if unread { 1 } else { 0 }, message_id, timestamp, if unread { 1 } else { 0 }],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -237,6 +306,20 @@ pub struct StoredChatMessage {
|
|||
pub updated_at: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct StoredChatSession {
|
||||
pub account_id: String,
|
||||
pub profile_id: String,
|
||||
pub slot: String,
|
||||
pub server_instance_id: String,
|
||||
pub remote_username: Option<String>,
|
||||
pub session_id: String,
|
||||
pub unread_count: u32,
|
||||
pub last_message_id: Option<String>,
|
||||
pub last_message_at: String,
|
||||
}
|
||||
|
||||
fn configure_connection(connection: &Connection, persistent: bool) -> Result<(), DatabaseError> {
|
||||
connection.pragma_update(None, "foreign_keys", "ON")?;
|
||||
connection.busy_timeout(Duration::from_secs(5))?;
|
||||
|
|
@ -358,6 +441,14 @@ fn migrate(connection: &mut Connection) -> Result<(), DatabaseError> {
|
|||
transaction.commit()?;
|
||||
}
|
||||
|
||||
if found <= 5 {
|
||||
let transaction = connection.transaction()?;
|
||||
transaction.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS chat_sessions (account_id TEXT NOT NULL, profile_id TEXT NOT NULL, slot TEXT NOT NULL CHECK(slot IN ('companion', 'operations')), server_instance_id TEXT NOT NULL, remote_username TEXT, session_id TEXT NOT NULL, unread_count INTEGER NOT NULL DEFAULT 0 CHECK(unread_count >= 0), last_message_id TEXT, last_message_at TEXT NOT NULL, PRIMARY KEY (account_id, profile_id, slot, server_instance_id, session_id)); CREATE INDEX IF NOT EXISTS chat_sessions_profile_idx ON chat_sessions(profile_id, server_instance_id, last_message_at); PRAGMA user_version = 6;",
|
||||
)?;
|
||||
transaction.commit()?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -385,6 +476,86 @@ pub enum DatabaseError {
|
|||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn tracks_chat_session_unread_count_and_read_state() {
|
||||
let database = ApplicationDatabase::in_memory().expect("database");
|
||||
database
|
||||
.upsert_chat_message(
|
||||
"account-a",
|
||||
"profile-a",
|
||||
"companion",
|
||||
"server-a",
|
||||
Some("user"),
|
||||
"session-a",
|
||||
"user-1",
|
||||
"user",
|
||||
"hello",
|
||||
false,
|
||||
false,
|
||||
)
|
||||
.expect("user message");
|
||||
database
|
||||
.upsert_chat_message(
|
||||
"account-a",
|
||||
"profile-a",
|
||||
"companion",
|
||||
"server-a",
|
||||
Some("user"),
|
||||
"session-a",
|
||||
"assistant-1",
|
||||
"assistant",
|
||||
"reply",
|
||||
true,
|
||||
false,
|
||||
)
|
||||
.expect("streaming reply");
|
||||
database
|
||||
.upsert_chat_message(
|
||||
"account-a",
|
||||
"profile-a",
|
||||
"companion",
|
||||
"server-a",
|
||||
Some("user"),
|
||||
"session-a",
|
||||
"assistant-1",
|
||||
"assistant",
|
||||
"reply",
|
||||
false,
|
||||
false,
|
||||
)
|
||||
.expect("completed reply");
|
||||
database
|
||||
.upsert_chat_message(
|
||||
"account-a",
|
||||
"profile-a",
|
||||
"companion",
|
||||
"server-a",
|
||||
Some("user"),
|
||||
"session-a",
|
||||
"assistant-1",
|
||||
"assistant",
|
||||
"reply",
|
||||
false,
|
||||
false,
|
||||
)
|
||||
.expect("duplicate completion");
|
||||
let sessions = database
|
||||
.list_chat_sessions("profile-a", "server-a")
|
||||
.expect("sessions");
|
||||
assert_eq!(sessions.len(), 1);
|
||||
assert_eq!(sessions[0].unread_count, 1);
|
||||
database
|
||||
.mark_chat_session_read("profile-a", "server-a", "session-a")
|
||||
.expect("mark read");
|
||||
assert_eq!(
|
||||
database
|
||||
.list_chat_sessions("profile-a", "server-a")
|
||||
.expect("sessions after read")[0]
|
||||
.unread_count,
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
|
|
@ -459,7 +630,10 @@ mod tests {
|
|||
drop(connection);
|
||||
|
||||
let store = ProfileMessageStore::open(&path).expect("migrate database");
|
||||
assert_eq!(store.schema_version().expect("schema version"), 5);
|
||||
assert_eq!(
|
||||
store.schema_version().expect("schema version"),
|
||||
CURRENT_SCHEMA_VERSION
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.message_content("profile-a", "server-a", "conversation-a", "message-a")
|
||||
|
|
@ -531,7 +705,10 @@ mod tests {
|
|||
}
|
||||
|
||||
let reopened = ProfileMessageStore::open(&path).expect("migrate v2 database");
|
||||
assert_eq!(reopened.schema_version().expect("schema version"), 5);
|
||||
assert_eq!(
|
||||
reopened.schema_version().expect("schema version"),
|
||||
CURRENT_SCHEMA_VERSION
|
||||
);
|
||||
let profile_count: u32 = reopened
|
||||
.connection
|
||||
.query_row(
|
||||
|
|
|
|||
|
|
@ -181,9 +181,11 @@ pub fn run() {
|
|||
networking::commands::connection_runtime_status,
|
||||
networking::commands::drain_connection_runtime_events,
|
||||
networking::commands::load_chat_messages,
|
||||
networking::commands::list_chat_sessions,
|
||||
networking::commands::mark_chat_session_read,
|
||||
networking::commands::probe_connection_slot,
|
||||
networking::commands::disconnect_connection_slot,
|
||||
networking::commands::send_connection_slot_message,
|
||||
networking::commands::send_connection_slot_message,
|
||||
networking::commands::cancel_connection_slot_message,
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
|
|
|
|||
|
|
@ -49,6 +49,21 @@ pub struct LoadChatMessagesRequest {
|
|||
pub limit: Option<usize>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct ListChatSessionsRequest {
|
||||
pub profile_id: String,
|
||||
pub server_instance_id: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct MarkChatSessionReadRequest {
|
||||
pub profile_id: String,
|
||||
pub server_instance_id: String,
|
||||
pub session_id: String,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn connection_runtime_status(
|
||||
runtime: State<'_, DualSlotRuntime>,
|
||||
|
|
@ -187,6 +202,36 @@ pub async fn drain_connection_runtime_events(
|
|||
Ok(events)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn list_chat_sessions(
|
||||
database: State<'_, ApplicationDatabase>,
|
||||
request: ListChatSessionsRequest,
|
||||
) -> Result<Vec<crate::database::StoredChatSession>, RuntimeCommandError> {
|
||||
database
|
||||
.list_chat_sessions(&request.profile_id, &request.server_instance_id)
|
||||
.map_err(|_| RuntimeCommandError {
|
||||
code: "databaseUnavailable",
|
||||
message: "Chat sessions are unavailable.",
|
||||
})
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn mark_chat_session_read(
|
||||
database: State<'_, ApplicationDatabase>,
|
||||
request: MarkChatSessionReadRequest,
|
||||
) -> Result<(), RuntimeCommandError> {
|
||||
database
|
||||
.mark_chat_session_read(
|
||||
&request.profile_id,
|
||||
&request.server_instance_id,
|
||||
&request.session_id,
|
||||
)
|
||||
.map_err(|_| RuntimeCommandError {
|
||||
code: "databaseUnavailable",
|
||||
message: "Chat session state is unavailable.",
|
||||
})
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn load_chat_messages(
|
||||
database: State<'_, ApplicationDatabase>,
|
||||
|
|
@ -406,7 +451,7 @@ pub async fn cancel_connection_slot_message(
|
|||
) -> Result<(), RuntimeCommandError> {
|
||||
runtime.cancel_slot_message(request.slot).await
|
||||
}
|
||||
#[tauri::command]
|
||||
#[tauri::command]
|
||||
pub async fn send_connection_slot_message(
|
||||
database: State<'_, ApplicationDatabase>,
|
||||
runtime: State<'_, DualSlotRuntime>,
|
||||
|
|
|
|||
|
|
@ -6,10 +6,11 @@ mod runtime;
|
|||
|
||||
pub use astrbot_client::{AstrBotClient, AstrBotClientConfig, AstrBotClientError};
|
||||
pub use commands::{
|
||||
DisconnectConnectionSlotRequest, DrainConnectionRuntimeEventsRequest,
|
||||
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, 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};
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { useCallback, useEffect, useMemo, useState } from "react";
|
|||
|
||||
import {
|
||||
boundRuntimeEventSchema,
|
||||
chatSessionSchema,
|
||||
connectionRuntimeStatusSchema,
|
||||
type BoundRuntimeEvent,
|
||||
type ChatMessage,
|
||||
|
|
@ -31,6 +32,10 @@ export function ChatPanel() {
|
|||
const [activeSlot, setActiveSlot] = useState<ChatSlot>("companion");
|
||||
const [draft, setDraft] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [unreadCounts, setUnreadCounts] = useState<Record<ChatSlot, number>>({
|
||||
companion: 0,
|
||||
operations: 0,
|
||||
});
|
||||
const activeMessages = useMemo(
|
||||
() => messages.filter((item) => item.slot === activeSlot),
|
||||
[messages, activeSlot],
|
||||
|
|
@ -61,6 +66,51 @@ export function ChatPanel() {
|
|||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const snapshot = status[activeSlot];
|
||||
if (!snapshot.profileId || !snapshot.serverInstanceId) return;
|
||||
let cancelled = false;
|
||||
void invoke<unknown>("list_chat_sessions", {
|
||||
request: {
|
||||
profileId: snapshot.profileId,
|
||||
serverInstanceId: snapshot.serverInstanceId,
|
||||
},
|
||||
})
|
||||
.then((result) => {
|
||||
if (cancelled) return;
|
||||
const sessions = chatSessionSchema.array().parse(result);
|
||||
setUnreadCounts((current) => ({
|
||||
...current,
|
||||
[activeSlot]: sessions.reduce(
|
||||
(total, session) => total + session.unreadCount,
|
||||
0,
|
||||
),
|
||||
}));
|
||||
})
|
||||
.catch(() => undefined);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [activeSlot, status]);
|
||||
|
||||
useEffect(() => {
|
||||
const snapshot = status[activeSlot];
|
||||
if (
|
||||
!snapshot.profileId ||
|
||||
!snapshot.serverInstanceId ||
|
||||
!snapshot.activeSessionId
|
||||
)
|
||||
return;
|
||||
void invoke("mark_chat_session_read", {
|
||||
request: {
|
||||
profileId: snapshot.profileId,
|
||||
serverInstanceId: snapshot.serverInstanceId,
|
||||
sessionId: snapshot.activeSessionId,
|
||||
},
|
||||
}).catch(() => undefined);
|
||||
setUnreadCounts((current) => ({ ...current, [activeSlot]: 0 }));
|
||||
}, [activeSlot, status]);
|
||||
|
||||
useEffect(() => {
|
||||
const snapshot = status[activeSlot];
|
||||
if (
|
||||
|
|
@ -158,6 +208,9 @@ export function ChatPanel() {
|
|||
type="button"
|
||||
>
|
||||
{slot === "companion" ? "陪伴" : "运维"}
|
||||
{unreadCounts[slot] > 0 ? (
|
||||
<strong>{unreadCounts[slot]}</strong>
|
||||
) : null}
|
||||
<span>{connectionStateLabel(status[slot].state)}</span>
|
||||
</button>
|
||||
))}
|
||||
|
|
|
|||
|
|
@ -43,6 +43,21 @@ export type ConnectionRuntimeStatus = z.infer<
|
|||
typeof connectionRuntimeStatusSchema
|
||||
>;
|
||||
export type BoundRuntimeEvent = z.infer<typeof boundRuntimeEventSchema>;
|
||||
export const chatSessionSchema = z
|
||||
.object({
|
||||
accountId: z.string().min(1),
|
||||
profileId: z.string().min(1),
|
||||
slot: activeSlotKindSchema,
|
||||
serverInstanceId: z.string().min(1),
|
||||
remoteUsername: z.string().min(1).optional(),
|
||||
sessionId: z.string().min(1),
|
||||
unreadCount: z.number().int().nonnegative(),
|
||||
lastMessageId: z.string().min(1).optional(),
|
||||
lastMessageAt: z.string().min(1),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export type ChatSession = z.infer<typeof chatSessionSchema>;
|
||||
export type ChatSlot = ActiveSlotKind;
|
||||
|
||||
export interface ChatMessage {
|
||||
|
|
|
|||
正在加载…
添加表格
在新工单中引用