feat: make context compaction visible in channels (#5656)
* feat: surface context compaction lifecycle * fix: complete and simplify context compaction notifications
This commit is contained in:
1 parent
455533169d
commit
5229989f28
52 files changed
+1849
-140
No files matched your search
@@ -25,6 +25,7 @@ import { ImageLightbox } from "@/components/ImageLightbox";
|
||||
import { MarkdownText } from "@/components/MarkdownText";
|
||||
import { SlashCommandText } from "@/components/SlashCommandText";
|
||||
import { ReasoningRow } from "@/components/thread/activity/ReasoningRow";
|
||||
import { ContextCompactionNotice } from "@/components/thread/ContextCompactionNotice";
|
||||
import { UserMessageText } from "@/components/UserMessageText";
|
||||
import {
|
||||
Tooltip,
|
||||
@@ -343,6 +344,10 @@ export function MessageBubble({
|
||||
[mcpPresets, message.mcpPresets],
|
||||
);
|
||||
|
||||
if (message.kind === "compaction" && message.compaction) {
|
||||
return <ContextCompactionNotice compaction={message.compaction} />;
|
||||
}
|
||||
|
||||
if (message.kind === "trace") {
|
||||
return <TraceGroup message={message} />;
|
||||
}
|
||||
@@ -440,7 +445,12 @@ export function MessageBubble({
|
||||
);
|
||||
}
|
||||
|
||||
const empty = message.content.trim().length === 0;
|
||||
const assistantContent = message.compactReply === "empty"
|
||||
? t("thread.compaction.empty")
|
||||
: message.compactReply === "failed"
|
||||
? t("thread.compaction.failed")
|
||||
: message.content;
|
||||
const empty = assistantContent.trim().length === 0;
|
||||
const media = message.media ?? [];
|
||||
const reasoning = message.role === "assistant" ? message.reasoning ?? "" : "";
|
||||
const reasoningStreaming = !!(message.role === "assistant" && message.reasoningStreaming);
|
||||
@@ -507,7 +517,7 @@ export function MessageBubble({
|
||||
preserveStreamingLayout
|
||||
onOpenFilePreview={onOpenFilePreview}
|
||||
>
|
||||
{message.content}
|
||||
{assistantContent}
|
||||
</MarkdownText>
|
||||
</div>
|
||||
{media.length > 0 ? <MessageMedia media={media} align="left" /> : null}
|
||||
@@ -528,7 +538,7 @@ export function MessageBubble({
|
||||
)}
|
||||
>
|
||||
{showCopyButton ? (
|
||||
<MessageCopyButton content={message.content} />
|
||||
<MessageCopyButton content={assistantContent} />
|
||||
) : null}
|
||||
{showForkButton ? (
|
||||
<Tooltip>
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { Archive, CircleAlert, LoaderCircle } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { UIContextCompaction } from "@/lib/types";
|
||||
|
||||
interface ContextCompactionNoticeProps {
|
||||
compaction: UIContextCompaction;
|
||||
}
|
||||
|
||||
export function ContextCompactionNotice({ compaction }: ContextCompactionNoticeProps) {
|
||||
const { t } = useTranslation();
|
||||
const title = compaction.phase === "started"
|
||||
? t("thread.compaction.started", { defaultValue: "Compressing context…" })
|
||||
: compaction.phase === "failed"
|
||||
? t("thread.compaction.failed", { defaultValue: "Context compaction failed" })
|
||||
: compaction.phase === "cancelled"
|
||||
? t("thread.compaction.cancelled", { defaultValue: "Context compaction cancelled" })
|
||||
: t("thread.compaction.succeeded", { defaultValue: "Context compacted" });
|
||||
const Icon = compaction.phase === "started"
|
||||
? LoaderCircle
|
||||
: compaction.phase === "failed"
|
||||
? CircleAlert
|
||||
: Archive;
|
||||
|
||||
return (
|
||||
<div
|
||||
role={compaction.announce ? "status" : undefined}
|
||||
aria-live={compaction.announce ? "polite" : undefined}
|
||||
aria-busy={compaction.phase === "started"}
|
||||
data-context-compaction={compaction.phase}
|
||||
className="mx-auto flex w-full max-w-[49.5rem] items-center gap-2.5 py-1 text-xs text-muted-foreground"
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"flex size-6 shrink-0 items-center justify-center rounded-full bg-muted/60",
|
||||
compaction.phase === "failed" && "text-destructive",
|
||||
)}
|
||||
>
|
||||
<Icon
|
||||
className={cn(
|
||||
"size-3.5",
|
||||
compaction.phase === "started" && "animate-spin motion-reduce:animate-none",
|
||||
)}
|
||||
aria-hidden
|
||||
/>
|
||||
</span>
|
||||
<p className="min-w-0 font-medium leading-5 text-foreground/80">{title}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
import { INLINE_TOKEN_HIGHLIGHT_COLOR } from "@/components/InlineTokenHighlight";
|
||||
import {
|
||||
Activity,
|
||||
Archive,
|
||||
ArrowUp,
|
||||
BookOpen,
|
||||
Brain,
|
||||
@@ -235,6 +236,7 @@ interface ThreadComposerProps {
|
||||
|
||||
const COMMAND_ICONS: Record<string, LucideIcon> = {
|
||||
activity: Activity,
|
||||
archive: Archive,
|
||||
"book-open": BookOpen,
|
||||
brain: Brain,
|
||||
"circle-help": CircleHelp,
|
||||
|
||||
@@ -39,6 +39,16 @@ export function assistantForkFlags(units: DisplayUnit[]): boolean[] {
|
||||
hasLaterUnitBeforeUser = false;
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
unit.type === "message"
|
||||
&& unit.message.role === "assistant"
|
||||
&& unit.message.kind === "compaction"
|
||||
) {
|
||||
// Compaction notices are session lifecycle markers, not assistant answers.
|
||||
// They must neither expose nor displace the answer-level fork action.
|
||||
flags[i] = false;
|
||||
continue;
|
||||
}
|
||||
if (unit.type === "message" && unit.message.role === "assistant") {
|
||||
flags[i] = !hasLaterUnitBeforeUser;
|
||||
}
|
||||
|
||||
@@ -771,6 +771,35 @@ export function useNanobotStream(
|
||||
return;
|
||||
}
|
||||
const sideChannelEvent = isSideChannelEvent(ev);
|
||||
if (ev.event === "context_compaction") {
|
||||
flushPendingStreamEvents({ closeAnswerSegment: true });
|
||||
clearActivitySegment();
|
||||
const compaction = {
|
||||
id: ev.compaction_id,
|
||||
phase: ev.phase,
|
||||
announce: true,
|
||||
};
|
||||
setMessages((prev) => {
|
||||
const id = `compaction-${ev.compaction_id}`;
|
||||
const existing = prev.findIndex((message) => message.id === id);
|
||||
const next = {
|
||||
id,
|
||||
role: "assistant" as const,
|
||||
content: "",
|
||||
kind: "compaction" as const,
|
||||
createdAt: Date.now(),
|
||||
compaction,
|
||||
...turnFieldsFromEvent(ev, "activity"),
|
||||
};
|
||||
if (existing < 0) return [...prev, next];
|
||||
return prev.map((message, index) => (
|
||||
index === existing
|
||||
? { ...next, createdAt: message.createdAt }
|
||||
: message
|
||||
));
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (ev.event === "delta") {
|
||||
if (suppressStreamUntilTurnEndRef.current) return;
|
||||
const chunk = typeof ev.text === "string" ? ev.text : "";
|
||||
@@ -854,6 +883,7 @@ export function useNanobotStream(
|
||||
}
|
||||
|
||||
if (ev.event === "turn_end") {
|
||||
if (typeof ev.turn_id === "string") sideChannelTurnIdsRef.current.delete(ev.turn_id);
|
||||
if ("goal_state" in ev && ev.goal_state != null && typeof ev.goal_state === "object") {
|
||||
setGoalState(ev.goal_state);
|
||||
}
|
||||
|
||||
@@ -1083,6 +1083,13 @@
|
||||
"error": "Connection error"
|
||||
},
|
||||
"thread": {
|
||||
"compaction": {
|
||||
"cancelled": "Context compaction cancelled",
|
||||
"empty": "Nothing to compact.",
|
||||
"started": "Compressing context…",
|
||||
"failed": "Context compaction failed",
|
||||
"succeeded": "Context compacted"
|
||||
},
|
||||
"loadingConversation": "Loading conversation…",
|
||||
"empty": {
|
||||
"greetings": {
|
||||
@@ -1277,6 +1284,10 @@
|
||||
"title": "New chat",
|
||||
"description": "Reset this chat and start a fresh conversation."
|
||||
},
|
||||
"compact": {
|
||||
"title": "Compact context",
|
||||
"description": "Compact this chat's context and continue the conversation."
|
||||
},
|
||||
"stop": {
|
||||
"title": "Stop current task",
|
||||
"description": "Cancel the active agent turn for this chat."
|
||||
|
||||
@@ -1070,6 +1070,13 @@
|
||||
"error": "Error de conexión"
|
||||
},
|
||||
"thread": {
|
||||
"compaction": {
|
||||
"cancelled": "Compresión de contexto cancelada",
|
||||
"empty": "No hay contexto que comprimir.",
|
||||
"started": "Comprimiendo el contexto…",
|
||||
"failed": "La compresión del contexto falló",
|
||||
"succeeded": "Contexto comprimido"
|
||||
},
|
||||
"loadingConversation": "Cargando conversación…",
|
||||
"empty": {
|
||||
"greetings": {
|
||||
@@ -1254,6 +1261,10 @@
|
||||
"title": "Nuevo chat",
|
||||
"description": "Restablece este chat e inicia una conversación nueva."
|
||||
},
|
||||
"compact": {
|
||||
"title": "Compactar contexto",
|
||||
"description": "Compacta el contexto de este chat y continúa la conversación."
|
||||
},
|
||||
"stop": {
|
||||
"title": "Detener tarea actual",
|
||||
"description": "Cancela el turno activo del agente en este chat."
|
||||
|
||||
@@ -1069,6 +1069,13 @@
|
||||
"error": "Erreur de connexion"
|
||||
},
|
||||
"thread": {
|
||||
"compaction": {
|
||||
"cancelled": "Compression du contexte annulée",
|
||||
"empty": "Aucun contexte à compresser.",
|
||||
"started": "Compression du contexte…",
|
||||
"failed": "Échec de la compression du contexte",
|
||||
"succeeded": "Contexte compressé"
|
||||
},
|
||||
"loadingConversation": "Chargement de la conversation…",
|
||||
"empty": {
|
||||
"greetings": {
|
||||
@@ -1253,6 +1260,10 @@
|
||||
"title": "Nouvelle discussion",
|
||||
"description": "Réinitialiser cette discussion et démarrer une nouvelle conversation."
|
||||
},
|
||||
"compact": {
|
||||
"title": "Compacter le contexte",
|
||||
"description": "Compacter le contexte de cette discussion et poursuivre la conversation."
|
||||
},
|
||||
"stop": {
|
||||
"title": "Arrêter la tâche en cours",
|
||||
"description": "Annuler le tour actif de l’agent pour cette discussion."
|
||||
|
||||
@@ -1069,6 +1069,13 @@
|
||||
"error": "Kesalahan koneksi"
|
||||
},
|
||||
"thread": {
|
||||
"compaction": {
|
||||
"cancelled": "Pemadatan konteks dibatalkan",
|
||||
"empty": "Tidak ada konteks yang perlu dipadatkan.",
|
||||
"started": "Memadatkan konteks…",
|
||||
"failed": "Pemadatan konteks gagal",
|
||||
"succeeded": "Konteks dipadatkan"
|
||||
},
|
||||
"loadingConversation": "Memuat percakapan…",
|
||||
"empty": {
|
||||
"greetings": {
|
||||
@@ -1253,6 +1260,10 @@
|
||||
"title": "Obrolan baru",
|
||||
"description": "Reset chat ini dan mulai percakapan baru."
|
||||
},
|
||||
"compact": {
|
||||
"title": "Ringkas konteks",
|
||||
"description": "Ringkas konteks chat ini, lalu lanjutkan percakapan."
|
||||
},
|
||||
"stop": {
|
||||
"title": "Hentikan tugas saat ini",
|
||||
"description": "Batalkan giliran agen yang sedang aktif di chat ini."
|
||||
|
||||
@@ -1069,6 +1069,13 @@
|
||||
"error": "接続エラー"
|
||||
},
|
||||
"thread": {
|
||||
"compaction": {
|
||||
"cancelled": "コンテキストの圧縮をキャンセルしました",
|
||||
"empty": "圧縮するコンテキストはありません。",
|
||||
"started": "コンテキストを圧縮中…",
|
||||
"failed": "コンテキストの圧縮に失敗しました",
|
||||
"succeeded": "コンテキストを圧縮しました"
|
||||
},
|
||||
"loadingConversation": "会話を読み込み中…",
|
||||
"empty": {
|
||||
"greetings": {
|
||||
@@ -1253,6 +1260,10 @@
|
||||
"title": "新しいチャット",
|
||||
"description": "このチャットをリセットして、新しい会話を開始します。"
|
||||
},
|
||||
"compact": {
|
||||
"title": "コンテキストを圧縮",
|
||||
"description": "このチャットのコンテキストを圧縮して、会話を続けます。"
|
||||
},
|
||||
"stop": {
|
||||
"title": "現在のタスクを停止",
|
||||
"description": "このチャットで実行中のエージェントのターンをキャンセルします。"
|
||||
|
||||
@@ -1069,6 +1069,13 @@
|
||||
"error": "연결 오류"
|
||||
},
|
||||
"thread": {
|
||||
"compaction": {
|
||||
"cancelled": "컨텍스트 압축이 취소되었습니다",
|
||||
"empty": "압축할 컨텍스트가 없습니다.",
|
||||
"started": "컨텍스트 압축 중…",
|
||||
"failed": "컨텍스트 압축 실패",
|
||||
"succeeded": "컨텍스트를 압축했습니다"
|
||||
},
|
||||
"loadingConversation": "대화 불러오는 중…",
|
||||
"empty": {
|
||||
"greetings": {
|
||||
@@ -1253,6 +1260,10 @@
|
||||
"title": "새 채팅",
|
||||
"description": "이 채팅을 초기화하고 새 대화를 시작합니다."
|
||||
},
|
||||
"compact": {
|
||||
"title": "컨텍스트 압축",
|
||||
"description": "이 채팅의 컨텍스트를 압축하고 대화를 계속합니다."
|
||||
},
|
||||
"stop": {
|
||||
"title": "현재 작업 중지",
|
||||
"description": "이 채팅에서 실행 중인 에이전트 턴을 취소합니다."
|
||||
|
||||
@@ -1083,6 +1083,13 @@
|
||||
"error": "Erro de conexão"
|
||||
},
|
||||
"thread": {
|
||||
"compaction": {
|
||||
"cancelled": "Compactação do contexto cancelada",
|
||||
"empty": "Não há contexto para compactar.",
|
||||
"started": "Compactando contexto…",
|
||||
"failed": "Falha ao compactar o contexto",
|
||||
"succeeded": "Contexto compactado"
|
||||
},
|
||||
"loadingConversation": "Carregando conversa…",
|
||||
"empty": {
|
||||
"greetings": {
|
||||
@@ -1277,6 +1284,10 @@
|
||||
"title": "Nova conversa",
|
||||
"description": "Reinicia esta conversa e inicia uma conversa nova."
|
||||
},
|
||||
"compact": {
|
||||
"title": "Compactar contexto",
|
||||
"description": "Compacte o contexto desta conversa e continue conversando."
|
||||
},
|
||||
"stop": {
|
||||
"title": "Parar tarefa atual",
|
||||
"description": "Cancela o turno ativo do agente nesta conversa."
|
||||
|
||||
@@ -1069,6 +1069,13 @@
|
||||
"error": "Lỗi kết nối"
|
||||
},
|
||||
"thread": {
|
||||
"compaction": {
|
||||
"cancelled": "Đã hủy nén ngữ cảnh",
|
||||
"empty": "Không có ngữ cảnh cần nén.",
|
||||
"started": "Đang nén ngữ cảnh…",
|
||||
"failed": "Nén ngữ cảnh không thành công",
|
||||
"succeeded": "Đã nén ngữ cảnh"
|
||||
},
|
||||
"loadingConversation": "Đang tải cuộc trò chuyện…",
|
||||
"empty": {
|
||||
"greetings": {
|
||||
@@ -1253,6 +1260,10 @@
|
||||
"title": "Cuộc trò chuyện mới",
|
||||
"description": "Đặt lại cuộc trò chuyện này và bắt đầu một cuộc trò chuyện mới."
|
||||
},
|
||||
"compact": {
|
||||
"title": "Nén ngữ cảnh",
|
||||
"description": "Nén ngữ cảnh của cuộc trò chuyện này và tiếp tục hội thoại."
|
||||
},
|
||||
"stop": {
|
||||
"title": "Dừng tác vụ hiện tại",
|
||||
"description": "Hủy lượt của tác nhân đang chạy trong cuộc trò chuyện này."
|
||||
|
||||
@@ -1083,6 +1083,13 @@
|
||||
"error": "连接出错"
|
||||
},
|
||||
"thread": {
|
||||
"compaction": {
|
||||
"cancelled": "上下文压缩已取消",
|
||||
"empty": "无需压缩上下文",
|
||||
"started": "正在压缩上下文…",
|
||||
"failed": "上下文压缩失败",
|
||||
"succeeded": "上下文已压缩"
|
||||
},
|
||||
"loadingConversation": "正在加载话题…",
|
||||
"empty": {
|
||||
"greetings": {
|
||||
@@ -1276,6 +1283,10 @@
|
||||
"title": "新建话题",
|
||||
"description": "重置当前话题,并开始一个新的话题。"
|
||||
},
|
||||
"compact": {
|
||||
"title": "压缩上下文",
|
||||
"description": "压缩当前对话的上下文并继续对话。"
|
||||
},
|
||||
"stop": {
|
||||
"title": "停止当前任务",
|
||||
"description": "取消这个对话中正在运行的智能体回合。"
|
||||
|
||||
@@ -1069,6 +1069,13 @@
|
||||
"error": "連線錯誤"
|
||||
},
|
||||
"thread": {
|
||||
"compaction": {
|
||||
"cancelled": "上下文壓縮已取消",
|
||||
"empty": "無需壓縮上下文",
|
||||
"started": "正在壓縮上下文…",
|
||||
"failed": "上下文壓縮失敗",
|
||||
"succeeded": "上下文已壓縮"
|
||||
},
|
||||
"loadingConversation": "正在載入話題…",
|
||||
"empty": {
|
||||
"greetings": {
|
||||
@@ -1253,6 +1260,10 @@
|
||||
"title": "新增話題",
|
||||
"description": "重置目前話題,並開始新的話題。"
|
||||
},
|
||||
"compact": {
|
||||
"title": "壓縮上下文",
|
||||
"description": "壓縮目前對話的上下文並繼續對話。"
|
||||
},
|
||||
"stop": {
|
||||
"title": "停止目前任務",
|
||||
"description": "取消這個對話中正在執行的智能體回合。"
|
||||
|
||||
@@ -175,6 +175,16 @@ function projectOrderedTurn(
|
||||
};
|
||||
|
||||
for (const message of messages) {
|
||||
if (message.kind === "compaction") {
|
||||
flushActivity();
|
||||
flushAnswers();
|
||||
units.push({
|
||||
type: "message",
|
||||
message,
|
||||
sourceMessageCount: 1 + claimLeadingNoops(),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (isCompletedDisplayNoop(message)) {
|
||||
absorbDisplayNoop();
|
||||
continue;
|
||||
|
||||
@@ -62,6 +62,23 @@ function deriveAssistantCompletionTimes(messages: UIMessage[]): UIMessage[] {
|
||||
});
|
||||
}
|
||||
|
||||
function identifyCompactReplies(messages: UIMessage[]): UIMessage[] {
|
||||
const turns = new Set(messages.flatMap((message) => (
|
||||
message.role === "user" && message.content.trim().toLowerCase() === "/compact" && message.turnId
|
||||
? [message.turnId]
|
||||
: []
|
||||
)));
|
||||
return messages.map((message) => {
|
||||
if (message.role !== "assistant" || message.kind || message.isStreaming
|
||||
|| !message.turnId || !turns.has(message.turnId)) return message;
|
||||
if (message.content === "Nothing to compact.") return { ...message, compactReply: "empty" };
|
||||
if (message.content === "Unable to compact context. Check the logs and try again.") {
|
||||
return { ...message, compactReply: "failed" };
|
||||
}
|
||||
return message;
|
||||
});
|
||||
}
|
||||
|
||||
export function projectWebuiThreadMessages(messages: UIMessage[]): UIMessage[] {
|
||||
const normalized = scrubSubagentUiMessages(normalizeLegacyLongTaskMessages(messages));
|
||||
const hiddenTurns = new Set(normalized.flatMap((message) => (
|
||||
@@ -75,5 +92,5 @@ export function projectWebuiThreadMessages(messages: UIMessage[]): UIMessage[] {
|
||||
&& !(message.role === "user" && isModelCommandText(message.content))
|
||||
&& !(message.role === "assistant" && isModelCommandResponseText(message.content))
|
||||
));
|
||||
return deriveAssistantCompletionTimes(visible);
|
||||
return deriveAssistantCompletionTimes(identifyCompactReplies(visible));
|
||||
}
|
||||
+18
-1
@@ -2,7 +2,14 @@ type Role = "user" | "assistant" | "tool" | "system";
|
||||
|
||||
/** "trace" rows are intermediate agent breadcrumbs (tool-call hints,
|
||||
* progress pings) that should not be rendered as conversational replies. */
|
||||
type MessageKind = "message" | "trace";
|
||||
type MessageKind = "message" | "trace" | "compaction";
|
||||
|
||||
export interface UIContextCompaction {
|
||||
id: string;
|
||||
phase: "started" | "succeeded" | "failed" | "cancelled";
|
||||
/** Live wire transitions announce; hydrated transcript rows stay silent. */
|
||||
announce?: boolean;
|
||||
}
|
||||
|
||||
export type UITurnPhase = "user" | "reasoning" | "activity" | "answer" | "complete";
|
||||
export type MessageDeliveryStatus = "sending" | "accepted" | "failed";
|
||||
@@ -86,6 +93,10 @@ export interface UIMessage {
|
||||
/** Internal projection marker for assistant text emitted before a later tool.
|
||||
* It is not a wire message and is rendered as a compact activity row. */
|
||||
activityKind?: "model";
|
||||
/** Context-compaction lifecycle rendered as a standalone channel notice. */
|
||||
compaction?: UIContextCompaction;
|
||||
/** Display-only localization marker for fixed /compact command replies. */
|
||||
compactReply?: "empty" | "failed";
|
||||
/** User turn: optimistic blob URLs for preview. Replay: placeholder chips. */
|
||||
images?: UIImage[];
|
||||
/** Signed or local UI-renderable media attachments. */
|
||||
@@ -1375,6 +1386,12 @@ export type InboundEvent =
|
||||
event: "recovery_state";
|
||||
chat_id: string;
|
||||
} & RecoveryState)
|
||||
| ({
|
||||
event: "context_compaction";
|
||||
chat_id: string;
|
||||
compaction_id: string;
|
||||
phase: UIContextCompaction["phase"];
|
||||
} & InboundTurnMetadata)
|
||||
| ({
|
||||
event: "file_edit";
|
||||
chat_id: string;
|
||||
|
||||
@@ -2,13 +2,15 @@ import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { runInNewContext } from "node:vm";
|
||||
|
||||
import { act, render, screen, waitFor } from "@testing-library/react";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { LanguageSwitcher } from "@/components/LanguageSwitcher";
|
||||
import { MessageBubble } from "@/components/MessageBubble";
|
||||
import { ContextCompactionNotice } from "@/components/thread/ContextCompactionNotice";
|
||||
import { ThreadComposer } from "@/components/thread/ThreadComposer";
|
||||
import { resources } from "@/i18n";
|
||||
import { resources, setAppLanguage } from "@/i18n";
|
||||
import {
|
||||
LOCALE_STORAGE_KEY,
|
||||
resolveInitialLocale,
|
||||
@@ -20,6 +22,7 @@ const IMAGE_QUICK_ACTION_KEYS = ["icon", "sticker", "poster", "product", "portra
|
||||
const HERO_GREETING_KEYS = ["workOn", "start", "build", "tackle"];
|
||||
const SLASH_COMMAND_KEYS = [
|
||||
"new",
|
||||
"compact",
|
||||
"stop",
|
||||
"restart",
|
||||
"status",
|
||||
@@ -418,6 +421,30 @@ describe("webui i18n", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.each(supportedLocales)("localizes compaction states in $code", async ({ code }) => {
|
||||
await setAppLanguage(code);
|
||||
const copy = resources[code].common.thread.compaction;
|
||||
const { container, rerender } = render(
|
||||
<ContextCompactionNotice compaction={{ id: "compact-1", phase: "started", announce: true }} />,
|
||||
);
|
||||
for (const phase of ["started", "succeeded", "failed", "cancelled"] as const) {
|
||||
rerender(<ContextCompactionNotice compaction={{
|
||||
id: "compact-1", phase, announce: true,
|
||||
}} />);
|
||||
const notice = container.querySelector("[data-context-compaction]");
|
||||
expect(copy[phase]).toBeTruthy();
|
||||
expect(notice?.textContent).toBe(copy[phase]);
|
||||
expect(notice).toHaveAttribute("aria-busy", String(phase === "started"));
|
||||
}
|
||||
for (const compactReply of ["empty", "failed"] as const) {
|
||||
rerender(<MessageBubble message={{
|
||||
id: "reply", role: "assistant", content: "original command reply",
|
||||
compactReply, createdAt: 1,
|
||||
}} />);
|
||||
expect(screen.getByText(copy[compactReply])).toBeInTheDocument();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps preboot copy aligned with every registered locale", () => {
|
||||
for (const { code } of supportedLocales) {
|
||||
const result = runPrebootLocale(code);
|
||||
@@ -499,6 +526,36 @@ describe("webui i18n", () => {
|
||||
expect(screen.getByLabelText("メッセージ入力欄")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("localizes a backend-provided compact slash command", async () => {
|
||||
await act(async () => {
|
||||
const { setAppLanguage } = await import("@/i18n");
|
||||
await setAppLanguage("zh-CN");
|
||||
});
|
||||
|
||||
render(
|
||||
<ThreadComposer
|
||||
onSend={vi.fn()}
|
||||
slashCommands={[{
|
||||
command: "/compact",
|
||||
title: "Compact context",
|
||||
description: "Compact this chat's context and continue the conversation.",
|
||||
icon: "archive",
|
||||
lifecycle: "side_channel",
|
||||
acceptsArgs: false,
|
||||
}]}
|
||||
/>,
|
||||
);
|
||||
|
||||
fireEvent.change(screen.getByLabelText("消息输入框"), {
|
||||
target: { value: "/co" },
|
||||
});
|
||||
|
||||
expect(screen.getByRole("listbox", { name: "斜杠命令" })).toBeInTheDocument();
|
||||
expect(screen.getByText("压缩上下文")).toBeInTheDocument();
|
||||
expect(screen.getByText("压缩当前对话的上下文并继续对话。")).toBeInTheDocument();
|
||||
expect(screen.getByText("/compact")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("keeps empty landing resources localized for every registered locale", () => {
|
||||
for (const resource of Object.values(resources)) {
|
||||
const empty = resource.common.thread.empty;
|
||||
|
||||
@@ -2,6 +2,7 @@ import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { MessageBubble } from "@/components/MessageBubble";
|
||||
import { setAppLanguage } from "@/i18n";
|
||||
import { fmtDateTime, formatMessageEndTime } from "@/lib/format";
|
||||
import type {
|
||||
CliAppInfo,
|
||||
@@ -95,6 +96,46 @@ const SLASH_COMMANDS: SlashCommand[] = [
|
||||
];
|
||||
|
||||
describe("MessageBubble", () => {
|
||||
it("copies the localized compact reply instead of the stored English text", async () => {
|
||||
await setAppLanguage("zh-CN");
|
||||
const writeText = vi.fn().mockResolvedValue(undefined);
|
||||
Object.defineProperty(navigator, "clipboard", {
|
||||
configurable: true,
|
||||
value: { writeText },
|
||||
});
|
||||
render(<MessageBubble message={{
|
||||
id: "compact-empty", role: "assistant", content: "Nothing to compact.",
|
||||
compactReply: "empty", createdAt: 1,
|
||||
}} />);
|
||||
expect(screen.getByText("无需压缩上下文")).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "复制" }));
|
||||
await waitFor(() => expect(writeText).toHaveBeenCalledWith("无需压缩上下文"));
|
||||
});
|
||||
|
||||
it("renders a compacted context notice", () => {
|
||||
const message: UIMessage = {
|
||||
id: "compaction-1",
|
||||
role: "assistant",
|
||||
content: "",
|
||||
kind: "compaction",
|
||||
createdAt: Date.now(),
|
||||
compaction: {
|
||||
id: "compact-1",
|
||||
phase: "succeeded",
|
||||
announce: true,
|
||||
},
|
||||
};
|
||||
|
||||
const { container } = render(<MessageBubble message={message} />);
|
||||
|
||||
const notice = container.querySelector("[data-context-compaction='succeeded']");
|
||||
expect(notice).toHaveAttribute("role", "status");
|
||||
expect(notice).toHaveAttribute("aria-live", "polite");
|
||||
expect(screen.getByText("Context compacted")).toBeInTheDocument();
|
||||
expect(notice).toHaveTextContent(/^Context compacted$/);
|
||||
expect(notice?.querySelector(".lucide-archive")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders user messages as right-aligned pills", () => {
|
||||
const message: UIMessage = {
|
||||
id: "u1",
|
||||
|
||||
@@ -66,6 +66,26 @@ describe("normalizeLegacyLongTaskMessages", () => {
|
||||
});
|
||||
|
||||
describe("projectWebuiThreadMessages", () => {
|
||||
it("marks only fixed replies belonging to a compact command turn", () => {
|
||||
const rows = [
|
||||
message("user", { content: " /COMPACT ", turnId: "compact" }),
|
||||
message("assistant", { content: "Nothing to compact.", turnId: "compact" }),
|
||||
message("assistant", {
|
||||
content: "Unable to compact context. Check the logs and try again.", turnId: "compact",
|
||||
}),
|
||||
message("assistant", { content: "Nothing to compact.", turnId: "unrelated" }),
|
||||
message("assistant", { content: "Nothing to compact." }),
|
||||
message("assistant", { content: "Nothing to compact.", turnId: "compact", isStreaming: true }),
|
||||
message("assistant", { content: "Quoted: Nothing to compact.", turnId: "compact" }),
|
||||
];
|
||||
const projected = projectWebuiThreadMessages(rows);
|
||||
expect(projected.map(({ compactReply }) => compactReply)).toEqual([
|
||||
undefined, "empty", "failed", undefined, undefined, undefined, undefined,
|
||||
]);
|
||||
expect(projected.map(({ content }) => content)).toEqual(rows.map(({ content }) => content));
|
||||
expect(projectWebuiThreadMessages(projected)).toEqual(projected);
|
||||
});
|
||||
|
||||
it("derives replayed completion time from the matching user turn", () => {
|
||||
const firstOutputAt = STARTED_AT + 5_000;
|
||||
const latencyMs = 13_000;
|
||||
|
||||
@@ -1678,4 +1678,32 @@ describe("ThreadMessages", () => {
|
||||
["a3", true],
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps compaction notices out of assistant fork selection", () => {
|
||||
const units = buildDisplayUnits([
|
||||
{ id: "u1", role: "user", content: "one", createdAt: 1 },
|
||||
{ id: "a1", role: "assistant", content: "answer", createdAt: 2 },
|
||||
{
|
||||
id: "compaction-1",
|
||||
role: "assistant",
|
||||
content: "",
|
||||
kind: "compaction",
|
||||
createdAt: 3,
|
||||
compaction: {
|
||||
id: "compact-1",
|
||||
phase: "succeeded",
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
const flags = assistantForkFlags(units);
|
||||
expect(units.map((unit, index) => [
|
||||
unit.type === "message" ? unit.message.id : "activity",
|
||||
flags[index],
|
||||
])).toEqual([
|
||||
["u1", true],
|
||||
["a1", true],
|
||||
["compaction-1", false],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -197,6 +197,54 @@ async function flushStreamFrame() {
|
||||
}
|
||||
|
||||
describe("useNanobotStream", () => {
|
||||
it.each(["succeeded", "cancelled"] as const)("updates one stable compaction row to %s", (phase) => {
|
||||
const fake = fakeClient();
|
||||
const { result } = renderHook(
|
||||
() => useNanobotStream("chat-compaction", EMPTY_MESSAGES),
|
||||
{ wrapper: wrap(fake.client) },
|
||||
);
|
||||
|
||||
act(() => {
|
||||
fake.emit("chat-compaction", {
|
||||
event: "context_compaction",
|
||||
chat_id: "chat-compaction",
|
||||
compaction_id: "compact-1",
|
||||
phase: "started",
|
||||
});
|
||||
});
|
||||
|
||||
expect(result.current.messages).toHaveLength(1);
|
||||
const createdAt = result.current.messages[0].createdAt;
|
||||
expect(result.current.messages[0]).toMatchObject({
|
||||
id: "compaction-compact-1",
|
||||
kind: "compaction",
|
||||
compaction: {
|
||||
id: "compact-1",
|
||||
phase: "started",
|
||||
announce: true,
|
||||
},
|
||||
});
|
||||
|
||||
act(() => {
|
||||
fake.emit("chat-compaction", {
|
||||
event: "context_compaction",
|
||||
chat_id: "chat-compaction",
|
||||
compaction_id: "compact-1",
|
||||
phase,
|
||||
});
|
||||
});
|
||||
|
||||
expect(result.current.messages).toHaveLength(1);
|
||||
expect(result.current.messages[0]).toMatchObject({
|
||||
id: "compaction-compact-1",
|
||||
createdAt,
|
||||
compaction: {
|
||||
phase,
|
||||
announce: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("batches answer deltas into one animation-frame update", async () => {
|
||||
const fake = fakeClient();
|
||||
const requestFrame = vi.spyOn(window, "requestAnimationFrame");
|
||||
|
||||
Reference in new issue
Block a user