优化claude code系统消息显示

This commit is contained in:
xintaofei
2026-03-24 21:13:25 +08:00
parent af6d8dd9a8
commit 0d16d82eb9
12 changed files with 92 additions and 20 deletions

View File

@@ -24,6 +24,8 @@ fn system_tag_regex() -> &'static Regex {
r"|<command-args>.*?</command-args>", r"|<command-args>.*?</command-args>",
r"|<local-command-stdout>.*?</local-command-stdout>", r"|<local-command-stdout>.*?</local-command-stdout>",
r"|<user-prompt-submit-hook>.*?</user-prompt-submit-hook>", r"|<user-prompt-submit-hook>.*?</user-prompt-submit-hook>",
r"|<task-notification>.*?</task-notification>",
r"|<fast_mode_info>.*?</fast_mode_info>",
)) ))
.unwrap() .unwrap()
}) })
@@ -62,6 +64,21 @@ fn is_meta_message(value: &serde_json::Value) -> bool {
/// Claude Code for local commands like `/context` or `/model`). /// Claude Code for local commands like `/context` or `/model`).
/// These carry `model: "<synthetic>"` and all-zero usage, so they should be /// These carry `model: "<synthetic>"` and all-zero usage, so they should be
/// excluded from conversation turns and stats. /// excluded from conversation turns and stats.
const CONTEXT_CONTINUATION_PREFIX: &str =
"This session is being continued from a previous conversation";
/// Detect Claude Code context continuation summary messages.
/// These are injected as "user" type but are actually system context.
fn is_context_continuation(content: &[ContentBlock]) -> bool {
content.iter().any(|block| {
if let ContentBlock::Text { text } = block {
text.starts_with(CONTEXT_CONTINUATION_PREFIX)
} else {
false
}
})
}
fn is_synthetic_assistant(value: &serde_json::Value) -> bool { fn is_synthetic_assistant(value: &serde_json::Value) -> bool {
value value
.get("message") .get("message")
@@ -486,18 +503,24 @@ impl ClaudeParser {
.unwrap_or("") .unwrap_or("")
.to_string(); .to_string();
if title.is_none() { // Detect context continuation summary and treat as system message
if let Some(first_text) = content.iter().find_map(|c| match c { let role = if is_context_continuation(&content) {
ContentBlock::Text { text } => Some(text.clone()), MessageRole::System
_ => None, } else {
}) { if title.is_none() {
title = Some(truncate_str(&first_text, 100)); if let Some(first_text) = content.iter().find_map(|c| match c {
ContentBlock::Text { text } => Some(text.clone()),
_ => None,
}) {
title = Some(truncate_str(&first_text, 100));
}
} }
} MessageRole::User
};
messages.push(UnifiedMessage { messages.push(UnifiedMessage {
id: uuid, id: uuid,
role: MessageRole::User, role,
content, content,
timestamp, timestamp,
usage: None, usage: None,

View File

@@ -1,6 +1,6 @@
"use client" "use client"
import { memo, useCallback, useEffect, useMemo, useRef } from "react" import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"
import { useConversationRuntime } from "@/contexts/conversation-runtime-context" import { useConversationRuntime } from "@/contexts/conversation-runtime-context"
import { ContentPartsRenderer } from "./content-parts-renderer" import { ContentPartsRenderer } from "./content-parts-renderer"
import { import {
@@ -20,7 +20,7 @@ import {
MessageThreadScrollButton, MessageThreadScrollButton,
} from "@/components/ai-elements/message-thread" } from "@/components/ai-elements/message-thread"
import { Message, MessageContent } from "@/components/ai-elements/message" import { Message, MessageContent } from "@/components/ai-elements/message"
import { Loader2 } from "lucide-react" import { ChevronDown, ChevronRight, Info, Loader2 } from "lucide-react"
import { useTranslations } from "next-intl" import { useTranslations } from "next-intl"
import { import {
buildPlanKey, buildPlanKey,
@@ -68,6 +68,41 @@ type ThreadRenderItem =
kind: "typing" kind: "typing"
} }
const CollapsibleSystemMessage = memo(function CollapsibleSystemMessage({
group,
}: {
group: ResolvedMessageGroup
}) {
const [expanded, setExpanded] = useState(false)
const t = useTranslations("Folder.chat.messageList")
return (
<div className="border rounded-md text-sm border-yellow-500/30 bg-yellow-500/5">
<button
onClick={() => setExpanded(!expanded)}
className="flex items-center gap-2 w-full px-3 py-2.5 text-left hover:bg-yellow-500/10 transition-colors"
>
{expanded ? (
<ChevronDown className="h-3.5 w-3.5 shrink-0 text-yellow-600 dark:text-yellow-500" />
) : (
<ChevronRight className="h-3.5 w-3.5 shrink-0 text-yellow-600 dark:text-yellow-500" />
)}
<Info className="h-3.5 w-3.5 shrink-0 text-yellow-600 dark:text-yellow-500" />
<span className="font-medium text-yellow-700 dark:text-yellow-400">
{t("systemMessage")}
</span>
</button>
{expanded && (
<div className="px-3 pb-3 border-t border-yellow-500/20">
<div className="text-sm text-muted-foreground mt-2.5 max-h-96 overflow-auto">
<ContentPartsRenderer parts={group.parts} role={group.role} />
</div>
</div>
)}
</div>
)
})
const HistoricalMessageGroup = memo(function HistoricalMessageGroup({ const HistoricalMessageGroup = memo(function HistoricalMessageGroup({
group, group,
dimmed = false, dimmed = false,
@@ -77,6 +112,10 @@ const HistoricalMessageGroup = memo(function HistoricalMessageGroup({
dimmed?: boolean dimmed?: boolean
showStats?: boolean showStats?: boolean
}) { }) {
if (group.role === "system") {
return <CollapsibleSystemMessage group={group} />
}
return ( return (
<div className={dimmed ? "opacity-70" : undefined}> <div className={dimmed ? "opacity-70" : undefined}>
<Message from={group.role}> <Message from={group.role}>

View File

@@ -1445,7 +1445,8 @@
"attachedResources": "الموارد المرفقة", "attachedResources": "الموارد المرفقة",
"loading": "جارٍ التحميل...", "loading": "جارٍ التحميل...",
"error": "خطأ: {message}", "error": "خطأ: {message}",
"emptyConversation": "لا توجد رسائل في هذه المحادثة." "emptyConversation": "لا توجد رسائل في هذه المحادثة.",
"systemMessage": "رسالة النظام"
}, },
"liveTurnStats": { "liveTurnStats": {
"thinking": "جارٍ التفكير...", "thinking": "جارٍ التفكير...",

View File

@@ -1445,7 +1445,8 @@
"attachedResources": "Angehängte Ressourcen", "attachedResources": "Angehängte Ressourcen",
"loading": "Lädt...", "loading": "Lädt...",
"error": "Fehler: {message}", "error": "Fehler: {message}",
"emptyConversation": "Keine Nachrichten in dieser Unterhaltung." "emptyConversation": "Keine Nachrichten in dieser Unterhaltung.",
"systemMessage": "Systemnachricht"
}, },
"liveTurnStats": { "liveTurnStats": {
"thinking": "Denkt nach...", "thinking": "Denkt nach...",

View File

@@ -1445,7 +1445,8 @@
"attachedResources": "Attached resources", "attachedResources": "Attached resources",
"loading": "Loading...", "loading": "Loading...",
"error": "Error: {message}", "error": "Error: {message}",
"emptyConversation": "No messages in this conversation." "emptyConversation": "No messages in this conversation.",
"systemMessage": "System message"
}, },
"liveTurnStats": { "liveTurnStats": {
"thinking": "Thinking...", "thinking": "Thinking...",

View File

@@ -1445,7 +1445,8 @@
"attachedResources": "Recursos adjuntos", "attachedResources": "Recursos adjuntos",
"loading": "Cargando...", "loading": "Cargando...",
"error": "Error del chat: {message}", "error": "Error del chat: {message}",
"emptyConversation": "No hay mensajes en esta conversación." "emptyConversation": "No hay mensajes en esta conversación.",
"systemMessage": "Mensaje del sistema"
}, },
"liveTurnStats": { "liveTurnStats": {
"thinking": "Pensando...", "thinking": "Pensando...",

View File

@@ -1445,7 +1445,8 @@
"attachedResources": "Ressources jointes", "attachedResources": "Ressources jointes",
"loading": "Chargement...", "loading": "Chargement...",
"error": "Erreur : {message}", "error": "Erreur : {message}",
"emptyConversation": "Aucun message dans cette conversation." "emptyConversation": "Aucun message dans cette conversation.",
"systemMessage": "Message système"
}, },
"liveTurnStats": { "liveTurnStats": {
"thinking": "Réflexion...", "thinking": "Réflexion...",

View File

@@ -1445,7 +1445,8 @@
"attachedResources": "添付リソース", "attachedResources": "添付リソース",
"loading": "読み込み中...", "loading": "読み込み中...",
"error": "エラー: {message}", "error": "エラー: {message}",
"emptyConversation": "この会話にはメッセージがありません。" "emptyConversation": "この会話にはメッセージがありません。",
"systemMessage": "システムメッセージ"
}, },
"liveTurnStats": { "liveTurnStats": {
"thinking": "考え中...", "thinking": "考え中...",

View File

@@ -1445,7 +1445,8 @@
"attachedResources": "첨부된 리소스", "attachedResources": "첨부된 리소스",
"loading": "불러오는 중...", "loading": "불러오는 중...",
"error": "오류: {message}", "error": "오류: {message}",
"emptyConversation": "이 대화에는 메시지가 없습니다." "emptyConversation": "이 대화에는 메시지가 없습니다.",
"systemMessage": "시스템 메시지"
}, },
"liveTurnStats": { "liveTurnStats": {
"thinking": "생각 중...", "thinking": "생각 중...",

View File

@@ -1445,7 +1445,8 @@
"attachedResources": "Recursos anexados", "attachedResources": "Recursos anexados",
"loading": "Carregando...", "loading": "Carregando...",
"error": "Erro: {message}", "error": "Erro: {message}",
"emptyConversation": "Nenhuma mensagem nesta conversa." "emptyConversation": "Nenhuma mensagem nesta conversa.",
"systemMessage": "Mensagem do sistema"
}, },
"liveTurnStats": { "liveTurnStats": {
"thinking": "Pensando...", "thinking": "Pensando...",

View File

@@ -1445,7 +1445,8 @@
"attachedResources": "附加资源", "attachedResources": "附加资源",
"loading": "加载中...", "loading": "加载中...",
"error": "错误:{message}", "error": "错误:{message}",
"emptyConversation": "当前会话暂无消息。" "emptyConversation": "当前会话暂无消息。",
"systemMessage": "系统消息"
}, },
"liveTurnStats": { "liveTurnStats": {
"thinking": "思考中...", "thinking": "思考中...",

View File

@@ -1445,7 +1445,8 @@
"attachedResources": "附加資源", "attachedResources": "附加資源",
"loading": "載入中...", "loading": "載入中...",
"error": "錯誤:{message}", "error": "錯誤:{message}",
"emptyConversation": "目前會話暫無訊息。" "emptyConversation": "目前會話暫無訊息。",
"systemMessage": "系統訊息"
}, },
"liveTurnStats": { "liveTurnStats": {
"thinking": "思考中...", "thinking": "思考中...",