feat(webui): distinguish context compaction reasons (NAN-324) (#6389)
* feat(webui): distinguish context compaction reasons (NAN-324) * fix(webui): describe idle compaction cancellation as interruption * docs: omit compaction notice details from configuration guide * fix(i18n): make compaction notices read naturally * fix(i18n): keep CJK compaction notices concise * fix(i18n): describe idle compaction as unfinished
This commit is contained in:
1 parent
084b6bb394
commit
bc5c58d239
38 files changed
+540
-23
No files matched your search
@@ -0,0 +1,90 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { expect, test, type WebSocketRoute } from "@playwright/test";
|
||||
import { supportedLocales } from "../src/i18n/config";
|
||||
import type { ThreadProjectionEvent } from "../src/lib/types";
|
||||
|
||||
const reasons = ["idle", "context_pressure", "manual", "provider_native"] as const;
|
||||
const phases = ["started", "succeeded", "failed", "cancelled"] as const;
|
||||
|
||||
// Synthetic HTTP history and WebSocket delivery through the production client,
|
||||
// projection, cache, and thread. No model/provider execution is involved.
|
||||
for (const { code } of supportedLocales) {
|
||||
test(`compaction reasons survive live updates and session reentry in ${code}`, async ({ page }, info) => {
|
||||
await page.setViewportSize({ width: 390, height: 900 });
|
||||
const messages: typeof import("../src/i18n/locales/en/common.json") = JSON.parse(
|
||||
readFileSync(new URL(`../src/i18n/locales/${code}/common.json`, import.meta.url), "utf8"),
|
||||
);
|
||||
const copy = messages.thread.compaction;
|
||||
await page.addInitScript((locale) => localStorage.setItem("nanobot.locale", locale), code);
|
||||
const errors: string[] = [];
|
||||
page.on("pageerror", (error) => errors.push(error.message));
|
||||
let history: ThreadProjectionEvent[] = [{ event: "context_compaction", chat_id: "answer-order",
|
||||
compaction_id: "legacy", phase: "succeeded", created_at_ms: 100,
|
||||
projection_id: "legacy", turn_id: "legacy-turn", turn_seq: 1 }];
|
||||
await page.route("**/api/**", (route) => route.fulfill({ status: 404, json: {} }));
|
||||
await page.route("**/api/commands", (route) => route.fulfill({ json: { commands: [] } }));
|
||||
await page.route("**/api/sessions/*/webui-thread?*", (route) => route.fulfill({ json: {
|
||||
schemaVersion: 3, projection: "events", has_more: false,
|
||||
events: decodeURIComponent(route.request().url()).includes("websocket:answer-order/") ? history : [],
|
||||
} }));
|
||||
let socket!: WebSocketRoute;
|
||||
const attached = new Set<string>();
|
||||
await page.routeWebSocket("**/answer-order-socket", (route) => {
|
||||
socket = route;
|
||||
route.onMessage((raw) => {
|
||||
const frame = JSON.parse(String(raw));
|
||||
if (frame.type === "attach") {
|
||||
attached.add(frame.chat_id);
|
||||
route.send(JSON.stringify({ event: "attached", chat_id: frame.chat_id }));
|
||||
}
|
||||
});
|
||||
});
|
||||
await page.goto("/browser/fixture.html?case=answer-order");
|
||||
await expect.poll(() => attached.has("answer-order")).toBe(true);
|
||||
const notices = page.locator("[data-context-compaction]");
|
||||
await expect(notices).toHaveCount(1);
|
||||
await expect(notices.first()).toHaveText(copy.succeeded);
|
||||
await expect(notices.first()).not.toHaveAttribute("role", "status");
|
||||
for (const [index, reason] of reasons.entries()) {
|
||||
const start: ThreadProjectionEvent = { event: "context_compaction", chat_id: "answer-order",
|
||||
compaction_id: reason, phase: "started", reason,
|
||||
projection_id: `${reason}-start`, turn_id: `${reason}-turn`, turn_seq: 1 };
|
||||
socket.send(JSON.stringify(start));
|
||||
const notice = notices.nth(index + 1);
|
||||
await expect(notices).toHaveCount(index + 2);
|
||||
await expect(notice).toHaveText(copy.reasons[reason].started);
|
||||
await expect(notice).toHaveAttribute("aria-busy", "true");
|
||||
const handle = await notice.elementHandle();
|
||||
const phase = phases[index === 3 ? 1 : index + 1]!;
|
||||
const finish = { ...start, phase, projection_id: `${reason}-finish`, turn_seq: 2 };
|
||||
socket.send(JSON.stringify(finish));
|
||||
await expect(notice).toHaveText(copy.reasons[reason][phase]);
|
||||
await expect(notice).toHaveAttribute("aria-busy", "false");
|
||||
expect(await notice.evaluate((node, original) => node === original, handle)).toBe(true);
|
||||
await expect(notices).toHaveCount(index + 2);
|
||||
history = [...history, start, finish];
|
||||
}
|
||||
const text = await notices.allTextContents();
|
||||
await page.getByRole("button", { name: "Switch topic" }).click();
|
||||
await expect(notices).toHaveCount(0);
|
||||
await page.getByRole("button", { name: "Switch topic" }).click();
|
||||
await expect(notices).toHaveText(text);
|
||||
await page.reload();
|
||||
await expect(notices).toHaveText(text);
|
||||
await expect(page.locator('[data-context-compaction][role="status"]')).toHaveCount(0);
|
||||
for (const theme of ["light", "dark"]) {
|
||||
await page.evaluate((value) => document.documentElement.classList.toggle("dark", value === "dark"), theme);
|
||||
expect(await page.locator("html").evaluate((node) => node.classList.contains("dark"))).toBe(theme === "dark");
|
||||
await expect(notices).toHaveText(text);
|
||||
for (const width of [390, 1280]) {
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
expect(await notices.evaluateAll((nodes) => nodes.every((node) => {
|
||||
const rect = node.getBoundingClientRect();
|
||||
return rect.left >= 0 && rect.right <= innerWidth && node.scrollWidth <= node.clientWidth;
|
||||
}))).toBe(true);
|
||||
await page.screenshot({ path: info.outputPath(`compaction-${code}-${theme}-${width}.png`) });
|
||||
}
|
||||
}
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
}
|
||||
@@ -9,13 +9,9 @@ interface ContextCompactionNoticeProps {
|
||||
|
||||
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 title = t(compaction.reason
|
||||
? `thread.compaction.reasons.${compaction.reason}.${compaction.phase}`
|
||||
: `thread.compaction.${compaction.phase}`);
|
||||
|
||||
return (
|
||||
<div
|
||||
|
||||
@@ -2020,6 +2020,32 @@
|
||||
"messages": "Message status"
|
||||
},
|
||||
"compaction": {
|
||||
"reasons": {
|
||||
"idle": {
|
||||
"started": "Automatically compacting context after inactivity",
|
||||
"succeeded": "Context automatically compacted after inactivity",
|
||||
"failed": "Automatic context compaction failed after inactivity",
|
||||
"cancelled": "Automatic compaction after inactivity did not finish"
|
||||
},
|
||||
"context_pressure": {
|
||||
"started": "Compacting a long context",
|
||||
"succeeded": "Long context compacted",
|
||||
"failed": "Failed to compact a long context",
|
||||
"cancelled": "Compaction of a long context cancelled"
|
||||
},
|
||||
"manual": {
|
||||
"started": "Manual compaction in progress",
|
||||
"succeeded": "Manual compaction complete",
|
||||
"failed": "Manual compaction failed",
|
||||
"cancelled": "Manual compaction cancelled"
|
||||
},
|
||||
"provider_native": {
|
||||
"started": "Compacting context on the provider's server",
|
||||
"succeeded": "Context compacted on the provider's server",
|
||||
"failed": "Failed to compact context on the provider's server",
|
||||
"cancelled": "Context compaction cancelled on the provider's server"
|
||||
}
|
||||
},
|
||||
"cancelled": "Context compaction cancelled",
|
||||
"empty": "Nothing to compact.",
|
||||
"started": "Compressing context",
|
||||
|
||||
@@ -1815,6 +1815,32 @@
|
||||
"messages": "Estado de mensajes"
|
||||
},
|
||||
"compaction": {
|
||||
"reasons": {
|
||||
"idle": {
|
||||
"started": "Compresión automática por inactividad en curso",
|
||||
"succeeded": "Compresión automática por inactividad completada",
|
||||
"failed": "Falló la compresión automática por inactividad",
|
||||
"cancelled": "No se completó la compresión automática por inactividad"
|
||||
},
|
||||
"context_pressure": {
|
||||
"started": "Comprimiendo un contexto extenso",
|
||||
"succeeded": "Contexto extenso comprimido",
|
||||
"failed": "Falló la compresión de un contexto extenso",
|
||||
"cancelled": "Compresión de un contexto extenso cancelada"
|
||||
},
|
||||
"manual": {
|
||||
"started": "Compresión manual en curso",
|
||||
"succeeded": "Compresión manual completada",
|
||||
"failed": "Falló la compresión manual",
|
||||
"cancelled": "Compresión manual cancelada"
|
||||
},
|
||||
"provider_native": {
|
||||
"started": "Comprimiendo el contexto en el servidor del proveedor",
|
||||
"succeeded": "Contexto comprimido en el servidor del proveedor",
|
||||
"failed": "Falló la compresión en el servidor del proveedor",
|
||||
"cancelled": "Compresión cancelada en el servidor del proveedor"
|
||||
}
|
||||
},
|
||||
"cancelled": "Compresión de contexto cancelada",
|
||||
"empty": "No hay contexto que comprimir.",
|
||||
"started": "Comprimiendo el contexto",
|
||||
|
||||
@@ -1814,6 +1814,32 @@
|
||||
"messages": "État des messages"
|
||||
},
|
||||
"compaction": {
|
||||
"reasons": {
|
||||
"idle": {
|
||||
"started": "Conversation inactive : compression automatique en cours",
|
||||
"succeeded": "Conversation inactive : compression automatique terminée",
|
||||
"failed": "Conversation inactive : échec de la compression automatique",
|
||||
"cancelled": "Conversation inactive : compression automatique non terminée"
|
||||
},
|
||||
"context_pressure": {
|
||||
"started": "Compression d’un contexte volumineux en cours",
|
||||
"succeeded": "Contexte volumineux compressé",
|
||||
"failed": "Échec de la compression d’un contexte volumineux",
|
||||
"cancelled": "Compression d’un contexte volumineux annulée"
|
||||
},
|
||||
"manual": {
|
||||
"started": "Compression manuelle en cours",
|
||||
"succeeded": "Compression manuelle terminée",
|
||||
"failed": "Échec de la compression manuelle",
|
||||
"cancelled": "Compression manuelle annulée"
|
||||
},
|
||||
"provider_native": {
|
||||
"started": "Compression en cours sur le serveur du fournisseur",
|
||||
"succeeded": "Contexte compressé sur le serveur du fournisseur",
|
||||
"failed": "Échec de la compression sur le serveur du fournisseur",
|
||||
"cancelled": "Compression annulée sur le serveur du fournisseur"
|
||||
}
|
||||
},
|
||||
"cancelled": "Compression du contexte annulée",
|
||||
"empty": "Aucun contexte à compresser.",
|
||||
"started": "Compression du contexte",
|
||||
|
||||
@@ -1814,6 +1814,32 @@
|
||||
"messages": "Status pesan"
|
||||
},
|
||||
"compaction": {
|
||||
"reasons": {
|
||||
"idle": {
|
||||
"started": "Memadatkan konteks secara otomatis saat tidak ada pesan baru",
|
||||
"succeeded": "Konteks dipadatkan otomatis saat tidak ada pesan baru",
|
||||
"failed": "Gagal memadatkan konteks secara otomatis saat tidak ada pesan baru",
|
||||
"cancelled": "Pemadatan konteks otomatis saat tidak ada pesan baru tidak selesai"
|
||||
},
|
||||
"context_pressure": {
|
||||
"started": "Memadatkan konteks karena sudah panjang",
|
||||
"succeeded": "Konteks yang panjang telah dipadatkan",
|
||||
"failed": "Gagal memadatkan konteks yang panjang",
|
||||
"cancelled": "Pemadatan konteks yang panjang dibatalkan"
|
||||
},
|
||||
"manual": {
|
||||
"started": "Memadatkan konteks atas permintaan Anda",
|
||||
"succeeded": "Konteks dipadatkan atas permintaan Anda",
|
||||
"failed": "Pemadatan konteks yang Anda minta gagal",
|
||||
"cancelled": "Pemadatan konteks yang Anda minta dibatalkan"
|
||||
},
|
||||
"provider_native": {
|
||||
"started": "Penyedia model sedang memadatkan konteks",
|
||||
"succeeded": "Penyedia model telah memadatkan konteks",
|
||||
"failed": "Pemadatan konteks di server penyedia model gagal",
|
||||
"cancelled": "Pemadatan konteks di server penyedia model dibatalkan"
|
||||
}
|
||||
},
|
||||
"cancelled": "Pemadatan konteks dibatalkan",
|
||||
"empty": "Tidak ada konteks yang perlu dipadatkan.",
|
||||
"started": "Memadatkan konteks",
|
||||
|
||||
@@ -1814,6 +1814,32 @@
|
||||
"messages": "メッセージの状態"
|
||||
},
|
||||
"compaction": {
|
||||
"reasons": {
|
||||
"idle": {
|
||||
"started": "新しいメッセージがないため自動圧縮中",
|
||||
"succeeded": "新しいメッセージがない間に自動圧縮しました",
|
||||
"failed": "メッセージがない間の自動圧縮に失敗しました",
|
||||
"cancelled": "メッセージがない間の自動圧縮は完了しませんでした"
|
||||
},
|
||||
"context_pressure": {
|
||||
"started": "コンテキストが長いため圧縮中",
|
||||
"succeeded": "長いコンテキストを圧縮しました",
|
||||
"failed": "長いコンテキストの圧縮に失敗しました",
|
||||
"cancelled": "長いコンテキストの圧縮をキャンセルしました"
|
||||
},
|
||||
"manual": {
|
||||
"started": "手動でコンテキストを圧縮中",
|
||||
"succeeded": "手動でコンテキストを圧縮しました",
|
||||
"failed": "手動でのコンテキスト圧縮に失敗しました",
|
||||
"cancelled": "手動でのコンテキスト圧縮をキャンセルしました"
|
||||
},
|
||||
"provider_native": {
|
||||
"started": "プロバイダー側でコンテキストを圧縮中",
|
||||
"succeeded": "プロバイダー側でコンテキストを圧縮しました",
|
||||
"failed": "プロバイダー側の圧縮に失敗しました",
|
||||
"cancelled": "プロバイダー側の圧縮をキャンセルしました"
|
||||
}
|
||||
},
|
||||
"cancelled": "コンテキストの圧縮をキャンセルしました",
|
||||
"empty": "圧縮するコンテキストはありません。",
|
||||
"started": "コンテキストを圧縮中",
|
||||
|
||||
@@ -1814,6 +1814,32 @@
|
||||
"messages": "메시지 상태"
|
||||
},
|
||||
"compaction": {
|
||||
"reasons": {
|
||||
"idle": {
|
||||
"started": "새 메시지가 없어 컨텍스트를 자동 압축 중",
|
||||
"succeeded": "새 메시지가 없어 컨텍스트를 자동 압축했습니다",
|
||||
"failed": "새 메시지가 없을 때의 자동 압축에 실패했습니다",
|
||||
"cancelled": "새 메시지가 없을 때의 자동 압축이 완료되지 않았습니다"
|
||||
},
|
||||
"context_pressure": {
|
||||
"started": "컨텍스트가 길어져 압축 중",
|
||||
"succeeded": "길어진 컨텍스트를 압축했습니다",
|
||||
"failed": "길어진 컨텍스트 압축에 실패했습니다",
|
||||
"cancelled": "길어진 컨텍스트 압축이 취소되었습니다"
|
||||
},
|
||||
"manual": {
|
||||
"started": "요청하신 대로 컨텍스트를 압축 중",
|
||||
"succeeded": "요청하신 대로 컨텍스트를 압축했습니다",
|
||||
"failed": "요청하신 컨텍스트 압축에 실패했습니다",
|
||||
"cancelled": "요청하신 컨텍스트 압축이 취소되었습니다"
|
||||
},
|
||||
"provider_native": {
|
||||
"started": "모델 제공업체에서 컨텍스트를 압축 중",
|
||||
"succeeded": "모델 제공업체에서 컨텍스트를 압축했습니다",
|
||||
"failed": "모델 제공업체의 컨텍스트 압축에 실패했습니다",
|
||||
"cancelled": "모델 제공업체의 컨텍스트 압축이 취소되었습니다"
|
||||
}
|
||||
},
|
||||
"cancelled": "컨텍스트 압축이 취소되었습니다",
|
||||
"empty": "압축할 컨텍스트가 없습니다.",
|
||||
"started": "컨텍스트 압축 중",
|
||||
|
||||
@@ -1828,6 +1828,32 @@
|
||||
"messages": "Status das mensagens"
|
||||
},
|
||||
"compaction": {
|
||||
"reasons": {
|
||||
"idle": {
|
||||
"started": "Compactação automática por inatividade em andamento",
|
||||
"succeeded": "Compactação automática por inatividade concluída",
|
||||
"failed": "Falha na compactação automática por inatividade",
|
||||
"cancelled": "A compactação automática por inatividade não foi concluída"
|
||||
},
|
||||
"context_pressure": {
|
||||
"started": "Compactando um contexto longo",
|
||||
"succeeded": "Contexto longo compactado",
|
||||
"failed": "Falha ao compactar um contexto longo",
|
||||
"cancelled": "Compactação de um contexto longo cancelada"
|
||||
},
|
||||
"manual": {
|
||||
"started": "Compactação manual em andamento",
|
||||
"succeeded": "Compactação manual concluída",
|
||||
"failed": "Falha na compactação manual",
|
||||
"cancelled": "Compactação manual cancelada"
|
||||
},
|
||||
"provider_native": {
|
||||
"started": "Compactando o contexto no servidor do provedor",
|
||||
"succeeded": "Contexto compactado no servidor do provedor",
|
||||
"failed": "Falha na compactação no servidor do provedor",
|
||||
"cancelled": "Compactação cancelada no servidor do provedor"
|
||||
}
|
||||
},
|
||||
"cancelled": "Compactação do contexto cancelada",
|
||||
"empty": "Não há contexto para compactar.",
|
||||
"started": "Compactando contexto",
|
||||
|
||||
@@ -1814,6 +1814,32 @@
|
||||
"messages": "Trạng thái tin nhắn"
|
||||
},
|
||||
"compaction": {
|
||||
"reasons": {
|
||||
"idle": {
|
||||
"started": "Đang tự động nén ngữ cảnh khi không có tin nhắn mới",
|
||||
"succeeded": "Đã tự động nén ngữ cảnh khi không có tin nhắn mới",
|
||||
"failed": "Không thể tự động nén ngữ cảnh khi không có tin nhắn mới",
|
||||
"cancelled": "Quá trình tự động nén ngữ cảnh khi không có tin nhắn mới không hoàn tất"
|
||||
},
|
||||
"context_pressure": {
|
||||
"started": "Đang nén vì ngữ cảnh đã dài",
|
||||
"succeeded": "Đã nén ngữ cảnh dài",
|
||||
"failed": "Nén ngữ cảnh dài không thành công",
|
||||
"cancelled": "Đã hủy nén ngữ cảnh dài"
|
||||
},
|
||||
"manual": {
|
||||
"started": "Đang nén ngữ cảnh theo yêu cầu của bạn",
|
||||
"succeeded": "Đã nén ngữ cảnh theo yêu cầu của bạn",
|
||||
"failed": "Không thể nén ngữ cảnh theo yêu cầu của bạn",
|
||||
"cancelled": "Đã hủy lần nén ngữ cảnh bạn yêu cầu"
|
||||
},
|
||||
"provider_native": {
|
||||
"started": "Nhà cung cấp mô hình đang nén ngữ cảnh",
|
||||
"succeeded": "Nhà cung cấp mô hình đã nén ngữ cảnh",
|
||||
"failed": "Nén ngữ cảnh trên máy chủ nhà cung cấp không thành công",
|
||||
"cancelled": "Đã hủy nén ngữ cảnh trên máy chủ nhà cung cấp"
|
||||
}
|
||||
},
|
||||
"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",
|
||||
|
||||
@@ -2020,6 +2020,32 @@
|
||||
"messages": "消息状态"
|
||||
},
|
||||
"compaction": {
|
||||
"reasons": {
|
||||
"idle": {
|
||||
"started": "会话空闲,正在自动压缩上下文",
|
||||
"succeeded": "会话空闲,已自动压缩上下文",
|
||||
"failed": "空闲时自动压缩上下文失败",
|
||||
"cancelled": "空闲期间的自动压缩未完成"
|
||||
},
|
||||
"context_pressure": {
|
||||
"started": "上下文较长,正在压缩",
|
||||
"succeeded": "上下文较长,已自动压缩",
|
||||
"failed": "上下文较长,自动压缩失败",
|
||||
"cancelled": "上下文较长,压缩已取消"
|
||||
},
|
||||
"manual": {
|
||||
"started": "正在手动压缩",
|
||||
"succeeded": "手动压缩完成",
|
||||
"failed": "手动压缩失败",
|
||||
"cancelled": "手动压缩已取消"
|
||||
},
|
||||
"provider_native": {
|
||||
"started": "模型服务正在压缩上下文",
|
||||
"succeeded": "模型服务已压缩上下文",
|
||||
"failed": "模型服务未能完成上下文压缩",
|
||||
"cancelled": "模型服务的上下文压缩已取消"
|
||||
}
|
||||
},
|
||||
"cancelled": "上下文压缩已取消",
|
||||
"empty": "无需压缩上下文",
|
||||
"started": "正在压缩上下文",
|
||||
|
||||
@@ -1814,6 +1814,32 @@
|
||||
"messages": "訊息狀態"
|
||||
},
|
||||
"compaction": {
|
||||
"reasons": {
|
||||
"idle": {
|
||||
"started": "對話閒置,正在自動壓縮上下文",
|
||||
"succeeded": "對話閒置,已自動壓縮上下文",
|
||||
"failed": "閒置時自動壓縮上下文失敗",
|
||||
"cancelled": "閒置期間的自動壓縮未完成"
|
||||
},
|
||||
"context_pressure": {
|
||||
"started": "上下文較長,正在壓縮",
|
||||
"succeeded": "上下文較長,已自動壓縮",
|
||||
"failed": "上下文較長,自動壓縮失敗",
|
||||
"cancelled": "上下文較長,壓縮已取消"
|
||||
},
|
||||
"manual": {
|
||||
"started": "正在手動壓縮",
|
||||
"succeeded": "手動壓縮完成",
|
||||
"failed": "手動壓縮失敗",
|
||||
"cancelled": "手動壓縮已取消"
|
||||
},
|
||||
"provider_native": {
|
||||
"started": "模型服務正在壓縮上下文",
|
||||
"succeeded": "模型服務已壓縮上下文",
|
||||
"failed": "模型服務未能完成上下文壓縮",
|
||||
"cancelled": "模型服務的上下文壓縮已取消"
|
||||
}
|
||||
},
|
||||
"cancelled": "上下文壓縮已取消",
|
||||
"empty": "無需壓縮上下文",
|
||||
"started": "正在壓縮上下文…",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isCompactionPhase, isCompactionReason } from "../../../packages/client-events/notifications";
|
||||
import type {
|
||||
ApiServicePayload,
|
||||
AutomationChatsPayload,
|
||||
@@ -380,7 +381,9 @@ function parseThreadProjectionEvent(value: unknown): ThreadProjectionEvent {
|
||||
if (value.text !== undefined && typeof value.text !== "string") break;
|
||||
return value as unknown as ThreadProjectionEvent;
|
||||
case "context_compaction":
|
||||
if (typeof value.compaction_id !== "string" || typeof value.phase !== "string") break;
|
||||
if (typeof value.compaction_id !== "string" || !value.compaction_id
|
||||
|| !isCompactionPhase(value.phase)
|
||||
|| (value.reason !== undefined && !isCompactionReason(value.reason))) break;
|
||||
return value as unknown as ThreadProjectionEvent;
|
||||
case "turn_end":
|
||||
return value as unknown as ThreadProjectionEvent;
|
||||
|
||||
@@ -1007,6 +1007,7 @@ export function projectThreadEvent(
|
||||
compaction: {
|
||||
id: event.compaction_id,
|
||||
phase: event.phase,
|
||||
reason: event.reason,
|
||||
...(!options.persisted ? { announce: true } : {}),
|
||||
},
|
||||
...positionedTurnFields(state.messages[existing], turnFieldsForProjection(state, event, "activity"), options),
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { decodeNotification } from "../../../packages/client-events/notifications";
|
||||
import { parseWebuiThreadPayload } from "@/lib/api";
|
||||
import { projectThreadEvents } from "@/lib/thread-event-projection";
|
||||
|
||||
const base = { event: "context_compaction", chat_id: "chat", compaction_id: "compact",
|
||||
turn_id: "turn", turn_phase: "activity", turn_seq: 2, created_at_ms: 123 };
|
||||
|
||||
function history(events: unknown[]) {
|
||||
return projectThreadEvents(parseWebuiThreadPayload({ schemaVersion: 3, projection: "events", events }).events);
|
||||
}
|
||||
|
||||
describe("compaction reason wire to history projection", () => {
|
||||
it.each(["idle", "context_pressure", "manual", "provider_native"] as const)(
|
||||
"preserves explicit %s through phase updates and rehydration", (reason) => {
|
||||
const start = { ...base, phase: "started", reason };
|
||||
const finish = { ...base, phase: "succeeded", reason, turn_seq: 3, created_at_ms: 456 };
|
||||
expect(decodeNotification(start)).toEqual(start);
|
||||
const rows = history([start, finish]);
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0]).toMatchObject({ id: "compaction-compact", createdAt: 123,
|
||||
turnId: "turn", turnPhase: "activity", turnSeq: 3,
|
||||
compaction: { id: "compact", phase: "succeeded", reason } });
|
||||
expect(rows[0].compaction?.announce).toBeUndefined();
|
||||
expect(history(JSON.parse(JSON.stringify([start, finish])))).toEqual(rows);
|
||||
expect(history([{ ...finish, reason }])[0].compaction).toMatchObject({ reason, phase: "succeeded" });
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps old records neutral and rejects malformed reasons at the history boundary", () => {
|
||||
expect(history([{ ...base, phase: "succeeded" }])[0].compaction?.reason).toBeUndefined();
|
||||
for (const reason of ["unknown", null, 42]) {
|
||||
expect(() => history([{ ...base, phase: "succeeded", reason }])).toThrow("Invalid WebUI thread projection event");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -434,6 +434,15 @@ describe("webui i18n", () => {
|
||||
expect(notice?.textContent).toBe(copy[phase]);
|
||||
expect(notice).toHaveAttribute("aria-busy", String(phase === "started"));
|
||||
}
|
||||
for (const reason of ["idle", "context_pressure", "manual", "provider_native"] as const) {
|
||||
for (const phase of ["started", "succeeded", "failed", "cancelled"] as const) {
|
||||
rerender(<ContextCompactionNotice compaction={{ id: "compact-1", reason, phase, announce: true }} />);
|
||||
const notice = container.querySelector("[data-context-compaction]");
|
||||
expect(copy.reasons[reason][phase]).toBeTruthy();
|
||||
expect(notice?.textContent).toBe(copy.reasons[reason][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",
|
||||
|
||||
@@ -22,6 +22,9 @@ describe("shared notification contract", () => {
|
||||
expect(decodeNotification({ event: "delta", text: "hello" })).toBeUndefined();
|
||||
expect(decodeNotification({ ...fixtures[0], phase: "unknown" })).toBeNull();
|
||||
expect(decodeNotification({ ...fixtures[0], compaction_id: "" })).toBeNull();
|
||||
for (const reason of [null, 42, "unknown"]) {
|
||||
expect(decodeNotification({ ...fixtures[0], reason })).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it("allows one terminal transition, including terminal-first hydration", () => {
|
||||
|
||||
@@ -65,6 +65,7 @@ function messageEvents(message: UIMessage): ThreadProjectionEvent[] {
|
||||
if (message.kind === "compaction" && message.compaction) {
|
||||
return [{
|
||||
event: "context_compaction",
|
||||
reason: message.compaction.reason,
|
||||
...base,
|
||||
compaction_id: message.compaction.id,
|
||||
phase: message.compaction.phase,
|
||||
|
||||
@@ -349,7 +349,7 @@ describe("useNanobotStream", () => {
|
||||
act(() => fake.emit("sources", { event: "stream_end", chat_id: "sources", response_sources: [] }));
|
||||
expect(result.current.messages[1].responseSources).toEqual([]);
|
||||
});
|
||||
it.each(["succeeded", "cancelled"] as const)("updates one stable compaction row to %s", (phase) => {
|
||||
it.each(["succeeded", "failed", "cancelled"] as const)("updates one stable compaction row to %s", (phase) => {
|
||||
const fake = fakeClient();
|
||||
const { result } = renderHook(
|
||||
() => useNanobotStream("chat-compaction", EMPTY_MESSAGES),
|
||||
@@ -362,6 +362,7 @@ describe("useNanobotStream", () => {
|
||||
chat_id: "chat-compaction",
|
||||
compaction_id: "compact-1",
|
||||
phase: "started",
|
||||
reason: "idle",
|
||||
});
|
||||
});
|
||||
|
||||
@@ -373,6 +374,7 @@ describe("useNanobotStream", () => {
|
||||
compaction: {
|
||||
id: "compact-1",
|
||||
phase: "started",
|
||||
reason: "idle",
|
||||
announce: true,
|
||||
},
|
||||
});
|
||||
@@ -383,6 +385,7 @@ describe("useNanobotStream", () => {
|
||||
chat_id: "chat-compaction",
|
||||
compaction_id: "compact-1",
|
||||
phase,
|
||||
reason: "idle",
|
||||
});
|
||||
});
|
||||
|
||||
@@ -392,6 +395,7 @@ describe("useNanobotStream", () => {
|
||||
createdAt,
|
||||
compaction: {
|
||||
phase,
|
||||
reason: "idle",
|
||||
announce: true,
|
||||
},
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user