);
}
function AssistantBlock({
message,
busy,
onDelete,
onRegenerate,
dreamActions,
}: {
message: ChatMessage;
busy: boolean;
onDelete: QaMessageProps["onDelete"];
onRegenerate: QaMessageProps["onRegenerate"];
dreamActions?: DreamDepositActions;
}) {
const { t } = useI18n();
const [touched, setTouched] = useState(false);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
const [confirmRegenOpen, setConfirmRegenOpen] = useState(false);
const addItem = useAddItem();
const isStreaming = message.status === "streaming";
const hasError = message.status === "error";
const hasReasoningText = (message.reasoning?.length ?? 0) > 0;
const hasContent = (message.content?.length ?? 0) > 0;
const wikiInFlight =
(message.wikiCount ?? 0) > 0 && message.wikiRetrievalDone !== true;
// Render the pill the moment a turn is in flight, **before** any reasoning
// chunk arrives. The server's RAG path runs query rewriting (~1-3s LLM
// call) and retrieval (~0.5-2s) before opening the upstream model stream,
// so `reasoning.delta` can be 2-5s away from the user's send. Without
// this early-render the assistant area sits blank during the entire
// pre-stream gap and the latency reads as a UI bug.
//
// For non-reasoning models the pill stays visible until the first
// `content.delta` arrives — `hasContent` flipping true makes both branches
// false (no reasoning text, content present) and the pill cleanly hands
// off to the streaming text below.
const showReasoningPill =
hasReasoningText || (isStreaming && (!hasContent || wikiInFlight));
// Stage of the pre-reasoning phase, derived from server events that arrive
// before the model's first token. Lets the label move through「检索意图
// 提取 → 正在检索知识库 → 正在思考 → 深度思考中」instead of sitting on
// a single generic word for the multiple seconds the server spends
// rewriting and retrieving.
const intentExtracting = !!message.usingRag && !message.retrievalQuery;
const retrievalInFlight =
!!message.retrievalQuery &&
!message.retrievedChunks &&
message.wikiRetrievalDone !== true;
// Aggregate per-KB retrieval errors so the TurnNotices chip can surface
// them without forcing the user to expand the chunks panel.
const failedKbDetails = (message.retrievalGroups ?? [])
.filter((g) => g.error)
.map((g) => ({ name: g.knowledgeBaseName, reason: g.error ?? "" }));
const failedWikiGroups = (message.wikiRetrievalGroups ?? []).filter(
(group) => (group.errors?.length ?? 0) > 0,
);
const failedWikiDetails = failedWikiGroups.flatMap((group) =>
(group.errors ?? []).map((error) => ({
name: group.wikiName,
reason: `[${error.code}] ${error.message}${
error.requestId ? ` (${error.requestId})` : ""
}`,
})),
);
const handleCopy = useCallback(() => {
if (!message.content) return;
try {
if (navigator.clipboard && window.isSecureContext) {
void navigator.clipboard.writeText(message.content).then(
() => toast.success(t("qa.message.copied")),
() => {
fallbackCopy(message.content, t);
},
);
} else {
fallbackCopy(message.content, t);
}
} catch {
fallbackCopy(message.content, t);
}
}, [message.content, t]);
async function handleSaveToFile() {
if (
!message.memoryFilesWritable ||
!message.memoryFilesStoreName ||
!message.memoryFilesScope
) {
return;
}
const timestamp = new Date(message.createdAt)
.toISOString()
.replace(/[:.]/g, "-");
const suggested = `/conversations/${timestamp}-${message.id.slice(0, 8)}.md`;
const input = window.prompt(t("qa.message.savePathPrompt"), suggested);
if (input === null) return;
const path = normalizeFileMemoryPath(input);
if (
validateFileMemoryPath(path) ||
validateFileMemoryContent(message.content)
) {
toast.error(t("qa.message.saveToFileInvalid"));
return;
}
try {
await addItem.mutateAsync({
memoryStoreName: message.memoryFilesStoreName,
scope: message.memoryFilesScope,
path,
content: message.content,
view: "full",
});
toast.success(t("qa.message.savedToFile", { path }));
} catch (error) {
toast.error(
error instanceof Error
? error.message
: t("qa.message.saveToFileFailed"),
);
}
}
return (
setTouched(true)}
>
{showReasoningPill ? (
) : null}
{/* Rewritten retrieval query — only shown when it differs from the
raw user input, so first-turn questions stay clean. */}
{message.retrievalQueryRewritten && message.retrievalQuery ? (
);
}
/**
* Live-ticking elapsed-seconds counter. Returns null while `start` is
* undefined (reasoning hasn't begun); freezes when `end` is set so the
* "thought for X seconds" indicator stops climbing the moment the model
* moves on. Tick cadence is 250ms — fine enough to feel live, coarse
* enough that React doesn't burn frames re-rendering a string.
*/
function useElapsedMs(start?: number, end?: number): number | null {
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
if (!start || end) return;
const id = window.setInterval(() => setNow(Date.now()), 250);
return () => window.clearInterval(id);
}, [start, end]);
if (!start) return null;
return Math.max(0, (end ?? now) - start);
}
/** Format elapsed milliseconds for the thinking pill. While the model is
* still working the format is `mm:ss` (live counter feel); after settle it
* becomes the friendlier "X 秒" / "X 分 Y 秒" reading conversational
* agents like DeepSeek and Doubao have made the de-facto Chinese standard. */
function formatElapsed(ms: number, settled: boolean, t: TranslateFn): string {
const totalSec = Math.floor(ms / 1000);
const m = Math.floor(totalSec / 60);
const s = totalSec % 60;
if (settled) {
if (m === 0) return t("qa.message.elapsedSeconds", { seconds: s });
return t("qa.message.elapsedMinutes", { minutes: m, seconds: s });
}
return `${m}:${String(s).padStart(2, "0")}`;
}
function ReasoningBlock({
reasoning,
streaming,
startedAt,
completedAt,
intentExtracting,
retrievalInFlight,
wikiInFlight,
wikiCount,
}: {
reasoning: string;
streaming: boolean;
startedAt?: number;
completedAt?: number;
intentExtracting?: boolean;
retrievalInFlight?: boolean;
wikiInFlight?: boolean;
wikiCount?: number;
}) {
const { t } = useI18n();
// Collapse by default; let the user opt in explicitly. Avoids the
// distracting auto-expand while the model is still producing tokens.
const [open, setOpen] = useState(false);
// Elapsed counter is anchored to the first reasoning chunk, NOT the send
// time — measuring "thought for N seconds" should exclude server-side
// pre-thinking work (query rewrite, retrieval). When startedAt is
// undefined the hook returns null, which we render as no time chip.
const elapsedMs = useElapsedMs(startedAt, completedAt);
const settled = !streaming || Boolean(completedAt);
const elapsedLabel =
elapsedMs != null ? formatElapsed(elapsedMs, settled, t) : null;
const active = streaming && !completedAt;
const hasReasoningText = reasoning.length > 0;
// Active label escalates as more state lands. The pre-reasoning labels are
// important: without them, RAG turns sit on a single label for several
// seconds before any model token arrives, which reads as a hang.
//
// Order matters — the most specific (and earliest-firing) state wins:
// intent → server is running the rewriter LLM (RAG turns only)
// retrieve → KB queries are in-flight
// thinking → retrieval done, model preparing first token
// deep → reasoning tokens are streaming
let activeLabel = t("qa.reasoning.thinking");
if (hasReasoningText) {
activeLabel = t("qa.reasoning.deepThinking");
} else if (wikiInFlight) {
activeLabel = t("qa.message.retrievingWikis", {
count: wikiCount ?? 0,
});
} else if (retrievalInFlight) {
activeLabel = t("qa.reasoning.retrieving");
} else if (intentExtracting) {
activeLabel = t("qa.reasoning.intentExtracting");
}
return (
{hasReasoningText && (
{reasoning}
)}
);
}
interface ChunksBlockProps {
chunks: RetrievedChunk[];
groups?: RetrievalGroup[];
}
function ChunksBlock({ chunks, groups }: ChunksBlockProps) {
const { t } = useI18n();
const [open, setOpen] = useState(false);
// Precompute a docId#chunkId -> aggregated index lookup so per-KB sub-lists
// can cite the same bracketed index the model sees in the prompt.
const indexByKey = new Map();
chunks.forEach((c, i) => {
indexByKey.set(`${c.docId}#${c.chunkId}`, i + 1);
});
// Show grouped view only when there are 2+ successful groups or any
// group reported an error; otherwise fall back to a flat list to avoid
// adding chrome for the common single-KB case.
const successful = (groups ?? []).filter((g) => !g.error);
const errored = (groups ?? []).filter((g) => g.error);
const showGrouped = successful.length >= 2 || errored.length > 0;
return (
{group.chunks.map((chunk) => {
// Chunks that fell outside the aggregate topK are not shown in the
// prompt and thus have no bracketed index; mark them with a dash.
const key = `${chunk.docId}#${chunk.chunkId}`;
const idx = indexByKey.get(key) ?? 0;
return (
);
})}