diff --git a/CHANGELOG.md b/CHANGELOG.md index 0884b4c..4099318 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,7 @@ ### Added +- Q10-Q15 chat experience increment: lightweight Markdown rendering, message actions, generation controls, session actions, connection controls, and responsive chat layout. - AstrBot OpenAPI adapter foundation: SSE mapper, dual-slot runtime skeleton, credential enrollment IPC, transport-aware profiles (ADR-0005). All notable changes to this project will be documented in this file. diff --git a/docs/progress.md b/docs/progress.md index b5dad34..7e7388d 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -300,3 +300,11 @@ Still not claimed complete: automatic startup activation, real Tauri multi-windo - Fixed AstrBot runtime event dispatch to expose the inner payload directly instead of nesting it under the protocol envelope. - This restores frontend and database access to `delta`, `content`, and error `message` fields. - Validation: Rust workspace tests, Clippy with warnings denied, TypeScript, ESLint, and NSIS bundle build pass. + +## 2026-07-21: Q10-Q15 chat experience increment + +- Added safe lightweight Markdown rendering for headings, lists, links, inline code, and fenced code blocks. +- Added copy, retry, read-aloud, stop-generation, new-chat, refresh, reconnect, disconnect, and runtime-error actions. +- Added responsive runtime metadata and chat layout refinements; preserved the existing pet event bus for Q13 state synchronization. +- Updated frontend test mocks for runtime status schema changes. +- Validation: Vitest (6), TypeScript, ESLint, and targeted Prettier checks pass. diff --git a/src/App.test.tsx b/src/App.test.tsx index 7644f6b..439c7d1 100644 --- a/src/App.test.tsx +++ b/src/App.test.tsx @@ -76,6 +76,25 @@ function mockBaseCommands(options?: { if (command === "connection_policy_status") { return policy; } + if (command === "connection_runtime_status") { + const toRuntimeSnapshot = (slot: ConnectionSlot) => ({ + slot: slot.slot, + profileId: slot.profileId, + transport: null, + state: slot.state, + serverInstanceId: slot.serverInstanceId, + activeSessionId: null, + lastError: null, + }); + return { + companion: toRuntimeSnapshot( + slots.find((slot) => slot.slot === "companion") ?? emptySlots[0], + ), + operations: toRuntimeSnapshot( + slots.find((slot) => slot.slot === "operations") ?? emptySlots[1], + ), + }; + } if (command === "assign_connection_slot") { const { request } = args as { request: AssignConnectionSlotRequest }; const saved: ConnectionSlot = { diff --git a/src/features/chat/ChatPanel.tsx b/src/features/chat/ChatPanel.tsx index 4d88464..3a1a538 100644 --- a/src/features/chat/ChatPanel.tsx +++ b/src/features/chat/ChatPanel.tsx @@ -2,6 +2,8 @@ import { invoke } from "@tauri-apps/api/core"; import { listen } from "@tauri-apps/api/event"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { MessageContent } from "./MessageContent"; + import { astrbotAttachmentSchema, astrbotCapabilitySnapshotSchema, @@ -70,6 +72,10 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { >([]); const [uploading, setUploading] = useState(false); const [voiceListening, setVoiceListening] = useState(false); + const [sending, setSending] = useState>({ + companion: false, + operations: false, + }); const speechRecognition = useRef<{ start: () => void; stop: () => void; @@ -91,7 +97,10 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { const visibleMessages = useMemo( () => activeMessages.filter( - (message) => message.content.trim().length > 0 || message.streaming || message.error, + (message) => + message.content.trim().length > 0 || + message.streaming || + message.error, ), [activeMessages], ); @@ -202,7 +211,8 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { transport: selectedTransport, }; setCapabilities(null); - if (!snapshot.profileId || snapshot.transport !== "astr-bot-open-api") return; + if (!snapshot.profileId || snapshot.transport !== "astr-bot-open-api") + return; let cancelled = false; void invoke("connection_slot_capabilities", { request: { slot: selectedSlot }, @@ -360,15 +370,17 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { } }; - const send = async () => { + const send = async (messageOverride?: string) => { const message = + messageOverride?.trim() || draft.trim() || - (pendingAttachments.length > 0 ? "请查看我发送的附件。" : ""); - if (!message || uploading) return; + (pendingAttachments.length > 0 ? "Please check the attachment." : ""); + if (!message || uploading || sending[selectedSlot]) return; const id = `local-${Date.now()}`; - const attachments = pendingAttachments; + const attachments = messageOverride ? [] : pendingAttachments; setDraft(""); - setPendingAttachments([]); + if (!messageOverride) setPendingAttachments([]); + setSending((current) => ({ ...current, [selectedSlot]: true })); setMessages((current) => current.concat({ id, @@ -404,6 +416,113 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) { item.id === id ? { ...item, error: true } : item, ), ); + } finally { + setSending((current) => ({ ...current, [selectedSlot]: false })); + } + }; + + const stopGeneration = async () => { + try { + await invoke("cancel_connection_slot_message", { + request: { slot: selectedSlot }, + }); + setSending((current) => ({ ...current, [selectedSlot]: false })); + setMessages((current) => + current.map((item) => + item.slot === selectedSlot && item.streaming + ? { + ...item, + streaming: false, + content: item.content || "Generation stopped.", + error: true, + } + : item, + ), + ); + setError(null); + } catch (reason) { + setError(reason instanceof Error ? reason.message : String(reason)); + } + }; + + const copyMessage = async (content: string) => { + try { + await navigator.clipboard.writeText(content); + setError(null); + } catch { + setError("Copy failed. Check clipboard permissions."); + } + }; + + const retryMessage = (messageId: string) => { + const index = messages.findIndex((item) => item.id === messageId); + const previousUser = [...messages] + .slice(0, index) + .reverse() + .find((item) => item.role === "user" && item.slot === selectedSlot); + if (previousUser) void send(previousUser.content); + }; + + const startNewSession = async () => { + if ( + !status[selectedSlot].state || + status[selectedSlot].state === "disconnected" + ) { + setError("Connect the selected slot first."); + return; + } + try { + const sessionId = crypto.randomUUID(); + const result = slotRuntimeSnapshotSchema.parse( + await invoke("switch_connection_slot_session", { + request: { slot: selectedSlot, sessionId }, + }), + ); + setMessages((current) => + current.filter( + (item) => + item.slot !== selectedSlot || + item.sessionId !== status[selectedSlot].activeSessionId, + ), + ); + setStatus((current) => ({ ...current, [selectedSlot]: result })); + setError(null); + } catch (reason) { + setError(reason instanceof Error ? reason.message : String(reason)); + } + }; + + const refreshConnection = async () => { + await refresh(); + }; + + const reconnectConnection = async () => { + const profileId = status[selectedSlot].profileId; + if (!profileId) { + setError("No Profile is assigned to the selected slot."); + return; + } + try { + const result = slotRuntimeSnapshotSchema.parse( + await invoke("probe_connection_slot", { + request: { slot: selectedSlot, profileId }, + }), + ); + setStatus((current) => ({ ...current, [selectedSlot]: result })); + setError(null); + } catch (reason) { + setError(reason instanceof Error ? reason.message : String(reason)); + } + }; + + const disconnectConnection = async () => { + try { + await invoke("disconnect_connection_slot", { + request: { slot: selectedSlot }, + }); + await refresh(); + } catch (reason) { + setError(reason instanceof Error ? reason.message : String(reason)); } }; @@ -485,10 +604,44 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
- Profile:{status[selectedSlot].profileId ?? "未连接"} - Session:{status[selectedSlot].activeSessionId ?? "未建立"} - 状态:{connectionStateLabel(status[selectedSlot].state)} +
+ Profile + {status[selectedSlot].profileId ?? "Not connected"} +
+
+ Session + + {status[selectedSlot].activeSessionId ?? "New session"} + +
+
+ Status + {connectionStateLabel(status[selectedSlot].state)} +
+
+ + + + +
+ {status[selectedSlot].lastError ? ( +

+ {status[selectedSlot].lastError} +

+ ) : null} {status[selectedSlot].state === "authExpired" ? (
认证已过期 @@ -532,35 +685,75 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
{visibleMessages.length === 0 ? (

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

) : ( - visibleMessages.map((message) => ( -
- -
-
- {message.role === "user" ? "我" : message.role === "assistant" ? "AstrBot" : "系统"} - {message.streaming ? 生成中… : null} + visibleMessages.map((message) => { + return ( +
+ -

{message.content || "生成中…"}

- {message.role === "assistant" && message.content ? ( - - ) : null} -
-
- )) +
+
+ + {message.role === "user" + ? "You" + : message.role === "assistant" + ? "AstrBot" + : "System"} + + {message.streaming ? Generating : null} +
+ {message.content ? ( + + ) : ( +

Generating?

+ )} + {message.role === "assistant" && + message.content && + !message.streaming ? ( +
+ + + +
+ ) : null} + {message.streaming && sending[selectedSlot] ? ( + + ) : null} +
+ + ); + }) )}
{error ?

{error}

: null} diff --git a/src/features/chat/MessageContent.tsx b/src/features/chat/MessageContent.tsx new file mode 100644 index 0000000..d0dd789 --- /dev/null +++ b/src/features/chat/MessageContent.tsx @@ -0,0 +1,122 @@ +import { Fragment, type ReactNode } from "react"; + +type MessageContentProps = { + content: string; +}; + +function renderInline(text: string, keyPrefix: string): ReactNode[] { + const tokens = text.split(/(`[^`]+`|\*\*[^*]+\*\*|\[[^\]]+\]\([^)]+\))/g); + return tokens.map((token, index) => { + const key = `${keyPrefix}-${index}`; + if (token.startsWith("`") && token.endsWith("`")) { + return {token.slice(1, -1)}; + } + if (token.startsWith("**") && token.endsWith("**")) { + return {token.slice(2, -2)}; + } + const link = token.match(/^\[([^\]]+)\]\(([^)]+)\)$/); + if (link) { + return ( + + {link[1]} + + ); + } + return {token}; + }); +} + +export function MessageContent({ content }: MessageContentProps) { + const lines = content.replaceAll("\r\n", "\n").split("\n"); + const blocks: ReactNode[] = []; + let codeLines: string[] | null = null; + let codeLanguage = ""; + let paragraph: string[] = []; + let list: string[] = []; + + const flushParagraph = () => { + if (!paragraph.length) return; + blocks.push( +

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

, + ); + paragraph = []; + }; + const flushList = () => { + if (!list.length) return; + blocks.push( +
    + {list.map((item, index) => ( +
  • + {renderInline(item, `list-${blocks.length}-${index}`)} +
  • + ))} +
, + ); + list = []; + }; + + lines.forEach((line, index) => { + if (line.trimStart().startsWith("```") && codeLines === null) { + flushParagraph(); + flushList(); + codeLines = []; + codeLanguage = line.trim().slice(3).trim(); + return; + } + if (line.trimStart().startsWith("```") && codeLines !== null) { + blocks.push( +
+          {codeLines.join("\n")}
+        
, + ); + codeLines = null; + codeLanguage = ""; + return; + } + if (codeLines !== null) { + codeLines.push(line); + return; + } + if (!line.trim()) { + flushParagraph(); + flushList(); + return; + } + const heading = line.match(/^(#{1,3})\s+(.+)$/); + if (heading) { + flushParagraph(); + flushList(); + const level = heading[1].length; + const Heading = `h${level}` as "h1" | "h2" | "h3"; + blocks.push( + + {renderInline(heading[2], `heading-${index}`)} + , + ); + return; + } + const item = line.match(/^\s*[-*]\s+(.+)$/); + if (item) { + flushParagraph(); + list.push(item[1]); + return; + } + flushList(); + paragraph.push(line.trim()); + }); + + const finalCodeText = (codeLines as string[] | null)?.join("\n"); + if (finalCodeText !== undefined) { + blocks.push( +
+        {finalCodeText}
+      
, + ); + } + flushParagraph(); + flushList(); + + return
{blocks}
; +} diff --git a/src/styles.css b/src/styles.css index b607248..b10f69f 100644 --- a/src/styles.css +++ b/src/styles.css @@ -2142,3 +2142,156 @@ body, :root[data-theme="light"] .chat-message-row.user .chat-bubble-header { color: #376b9f; } +.chat-runtime-strip { + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto; + gap: 10px; + align-items: center; +} + +.chat-runtime-strip > div { + min-width: 0; +} + +.chat-runtime-strip span, +.chat-runtime-strip strong { + display: block; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.chat-runtime-strip span { + color: var(--muted-text, #6b7d92); + font-size: 11px; +} + +.chat-runtime-strip strong { + color: var(--ink, #24344d); + font-size: 12px; + font-weight: 600; +} + +.chat-runtime-actions, +.chat-message-actions { + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.chat-runtime-actions button, +.chat-message-actions button, +.chat-stop-button { + border: 1px solid var(--line, #c8d8ea); + border-radius: 999px; + background: transparent; + color: var(--muted-text, #6b7d92); + cursor: pointer; + font-size: 11px; + padding: 4px 9px; +} + +.chat-runtime-actions button:hover, +.chat-message-actions button:hover, +.chat-stop-button:hover { + background: var(--soft-accent, #eaf3ff); + color: var(--accent, #2f6fb2); +} + +.chat-runtime-actions button:disabled { + cursor: not-allowed; + opacity: 0.5; +} + +.message-content { + color: inherit; + line-height: 1.58; + overflow-wrap: anywhere; +} + +.message-content p, +.message-content h1, +.message-content h2, +.message-content h3, +.message-content ul, +.message-content pre { + margin: 0 0 8px; +} + +.message-content p:last-child, +.message-content ul:last-child, +.message-content pre:last-child { + margin-bottom: 0; +} + +.message-content h1, +.message-content h2, +.message-content h3 { + color: inherit; + font-size: 14px; +} + +.message-content ul { + padding-left: 18px; +} + +.message-content code { + border-radius: 5px; + background: rgba(50, 80, 110, 0.1); + font-family: "Cascadia Code", Consolas, monospace; + font-size: 0.92em; + padding: 2px 4px; +} + +.message-content pre { + max-width: 100%; + overflow-x: auto; + border-radius: 9px; + background: #152234; + color: #e8f1ff; + padding: 10px 12px; +} + +.message-content pre code { + display: block; + background: transparent; + padding: 0; + white-space: pre; +} + +.message-content a { + color: var(--accent, #2f6fb2); +} + +.chat-message-actions { + margin-top: 8px; +} + +.chat-stop-button { + margin-top: 8px; + border-color: #d88d8d; + color: #a43f47; +} + +.message-placeholder { + color: var(--muted-text, #6b7d92); + margin: 0; +} + +@media (max-width: 760px) { + .chat-runtime-strip { + grid-template-columns: 1fr; + } + + .chat-runtime-actions { + justify-content: flex-start; + } +} +.chat-runtime-error { + margin: 8px 0 0; + border-radius: 8px; + background: rgba(180, 70, 75, 0.09); + color: #a43f47; + font-size: 12px; + padding: 8px 10px; +}