feat(chat): advance Q10-Q15 experience
一些检测仍在等待运行
ci / Portable quality checks (push) Waiting to run
ci / Windows Tauri build (push) Waiting to run

这个提交存在于:
YokiiroBW 2026-07-21 15:25:11 +08:00
父节点 5de8bfab03
当前提交 ea332257ac
共有 6 个文件被更改,包括 532 次插入 和 36 次删除

查看文件

@ -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.

查看文件

@ -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.

查看文件

@ -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 = {

查看文件

@ -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<Record<ChatSlot, boolean>>({
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<unknown>("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<unknown>("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<unknown>("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) {
</div>
</div>
<div className="chat-runtime-strip">
<span>Profile:{status[selectedSlot].profileId ?? "未连接"}</span>
<span>Session:{status[selectedSlot].activeSessionId ?? "未建立"}</span>
<span>状态:{connectionStateLabel(status[selectedSlot].state)}</span>
<div>
<span>Profile</span>
<strong>{status[selectedSlot].profileId ?? "Not connected"}</strong>
</div>
<div>
<span>Session</span>
<strong>
{status[selectedSlot].activeSessionId ?? "New session"}
</strong>
</div>
<div>
<span>Status</span>
<strong>{connectionStateLabel(status[selectedSlot].state)}</strong>
</div>
<div className="chat-runtime-actions">
<button type="button" onClick={() => void refreshConnection()}>
Refresh
</button>
<button type="button" onClick={() => void reconnectConnection()}>
Reconnect
</button>
<button
type="button"
onClick={() => void disconnectConnection()}
disabled={status[selectedSlot].state === "disconnected"}
>
Disconnect
</button>
<button type="button" onClick={() => void startNewSession()}>
New chat
</button>
</div>
</div>
{status[selectedSlot].lastError ? (
<p className="chat-runtime-error" role="status">
{status[selectedSlot].lastError}
</p>
) : null}
{status[selectedSlot].state === "authExpired" ? (
<div className="warning-banner" role="alert">
<strong>认证已过期</strong>
@ -532,35 +685,75 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
<div className="chat-message-list" aria-live="polite">
{visibleMessages.length === 0 ? (
<p className="chat-empty">
当前槽位还没有消息。连接 Profile 后即可开始聊天。
No messages in this slot yet. Connect a Profile to start chatting.
</p>
) : (
visibleMessages.map((message) => (
<article
className={`chat-message-row ${message.role}${message.error ? " failed" : ""}`}
key={message.id}
>
<div className="chat-avatar" aria-hidden="true">
{message.role === "user" ? "我" : message.role === "assistant" ? "A" : "!"}
</div>
<div className="chat-bubble">
<div className="chat-bubble-header">
<span>{message.role === "user" ? "我" : message.role === "assistant" ? "AstrBot" : "系统"}</span>
{message.streaming ? <small>生成中…</small> : null}
visibleMessages.map((message) => {
return (
<article
className={`chat-message-row ${message.role}${message.error ? " failed" : ""}`}
key={message.id}
>
<div className="chat-avatar" aria-hidden="true">
{message.role === "user"
? "You"
: message.role === "assistant"
? "A"
: "!"}
</div>
<p>{message.content || "生成中…"}</p>
{message.role === "assistant" && message.content ? (
<button
className="chat-message-read"
type="button"
onClick={() => speakMessage(message.content)}
>
朗读
</button>
) : null}
</div>
</article>
))
<div className="chat-bubble">
<div className="chat-bubble-header">
<span>
{message.role === "user"
? "You"
: message.role === "assistant"
? "AstrBot"
: "System"}
</span>
{message.streaming ? <small>Generating</small> : null}
</div>
{message.content ? (
<MessageContent content={message.content} />
) : (
<p className="message-placeholder">Generating?</p>
)}
{message.role === "assistant" &&
message.content &&
!message.streaming ? (
<div className="chat-message-actions">
<button
type="button"
onClick={() => void copyMessage(message.content)}
>
Copy
</button>
<button
type="button"
onClick={() => retryMessage(message.id)}
>
Retry
</button>
<button
type="button"
onClick={() => speakMessage(message.content)}
>
Read aloud
</button>
</div>
) : null}
{message.streaming && sending[selectedSlot] ? (
<button
className="chat-stop-button"
type="button"
onClick={() => void stopGeneration()}
>
Stop generating
</button>
) : null}
</div>
</article>
);
})
)}
</div>
{error ? <p className="chat-error">{error}</p> : null}

查看文件

@ -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 <code key={key}>{token.slice(1, -1)}</code>;
}
if (token.startsWith("**") && token.endsWith("**")) {
return <strong key={key}>{token.slice(2, -2)}</strong>;
}
const link = token.match(/^\[([^\]]+)\]\(([^)]+)\)$/);
if (link) {
return (
<a key={key} href={link[2]} target="_blank" rel="noreferrer">
{link[1]}
</a>
);
}
return <Fragment key={key}>{token}</Fragment>;
});
}
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(
<p key={`paragraph-${blocks.length}`}>
{renderInline(paragraph.join(" "), `paragraph-${blocks.length}`)}
</p>,
);
paragraph = [];
};
const flushList = () => {
if (!list.length) return;
blocks.push(
<ul key={`list-${blocks.length}`}>
{list.map((item, index) => (
<li key={`list-${blocks.length}-${index}`}>
{renderInline(item, `list-${blocks.length}-${index}`)}
</li>
))}
</ul>,
);
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(
<pre key={`code-${index}`} data-language={codeLanguage || undefined}>
<code>{codeLines.join("\n")}</code>
</pre>,
);
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(
<Heading key={`heading-${index}`}>
{renderInline(heading[2], `heading-${index}`)}
</Heading>,
);
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(
<pre key="code-final">
<code>{finalCodeText}</code>
</pre>,
);
}
flushParagraph();
flushList();
return <div className="message-content">{blocks}</div>;
}

查看文件

@ -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;
}