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
@@ -2878,6 +2878,136 @@ describe("NanobotTui layout", () => {
|
||||
expect(ui.status.plainText).not.toContain("attempt")
|
||||
})
|
||||
|
||||
test.each([
|
||||
["succeeded", "Conversation compacted"],
|
||||
["cancelled", "Conversation compaction cancelled"],
|
||||
] as const)("updates idle compaction in place to %s", async (phase, copy) => {
|
||||
setup = await createRenderer({ width: 80, height: 24, screenMode: "alternate-screen" })
|
||||
const app = mount(setup)
|
||||
const ui = app as unknown as {
|
||||
activeTurn: boolean
|
||||
transcript: Transcript
|
||||
composer: TextareaRenderable
|
||||
}
|
||||
ui.composer.setText("unfinished draft")
|
||||
const event = { event: "context_compaction", chat_id: "chat", compaction_id: "idle" } as const
|
||||
app.accept({ ...event, phase: "started" })
|
||||
await setup.renderOnce()
|
||||
expect(setup.captureCharFrame()).toContain("Compacting conversation…")
|
||||
const rows = ui.transcript.root.getChildren()
|
||||
app.accept({ ...event, phase })
|
||||
app.accept({ ...event, phase })
|
||||
app.accept({ ...event, phase: "started" })
|
||||
app.accept({ ...event, chat_id: "another-chat", compaction_id: "other", phase: "failed" })
|
||||
await setup.renderOnce()
|
||||
const frame = setup.captureCharFrame()
|
||||
expect(occurrences(frame, copy)).toBe(1)
|
||||
expect(frame).not.toContain("Compacting conversation")
|
||||
expect(frame).not.toContain("Could not compact")
|
||||
expect(ui.transcript.root.getChildren()).toEqual(rows)
|
||||
expect(ui.activeTurn).toBe(false)
|
||||
expect(ui.composer.plainText).toBe("unfinished draft")
|
||||
})
|
||||
|
||||
test("keeps compaction separate from progress and streamed answers", async () => {
|
||||
setup = await createRenderer({ width: 80, height: 30, screenMode: "alternate-screen" })
|
||||
const app = mount(setup)
|
||||
app.accept({ event: "delta", chat_id: "chat", text: "Answer before " })
|
||||
app.accept({ event: "message", chat_id: "chat", text: "First step", kind: "progress" })
|
||||
const event = { event: "context_compaction", chat_id: "chat", compaction_id: "capacity" } as const
|
||||
app.accept({ ...event, phase: "started" })
|
||||
app.accept({ event: "message", chat_id: "chat", text: "Second step", kind: "progress" })
|
||||
app.accept({ ...event, phase: "succeeded" })
|
||||
app.accept({ event: "delta", chat_id: "chat", text: "and after compaction" })
|
||||
expect((app as unknown as { activeTurn: boolean }).activeTurn).toBe(true)
|
||||
app.accept({ event: "stream_end", chat_id: "chat" })
|
||||
app.accept({ event: "turn_end", chat_id: "chat" })
|
||||
await setup.flush()
|
||||
const frame = setup.captureCharFrame()
|
||||
expect(frame).toContain("Answer before and after compaction")
|
||||
expect(frame.indexOf("First step")).toBeLessThan(frame.indexOf("Conversation compacted"))
|
||||
expect(frame.indexOf("Conversation compacted")).toBeLessThan(frame.indexOf("Second step"))
|
||||
expect(occurrences(frame, "Conversation compacted")).toBe(1)
|
||||
})
|
||||
|
||||
test("preserves compaction rows through pagination, theming, and session reset", async () => {
|
||||
setup = await createRenderer({ width: 80, height: 28, screenMode: "alternate-screen" })
|
||||
const app = mount(setup)
|
||||
const ui = app as unknown as {
|
||||
transcript: Transcript
|
||||
palette: { error: string }
|
||||
}
|
||||
ui.transcript.history([
|
||||
{ role: "activity", content: "", compaction: { id: "recent", phase: "succeeded" } },
|
||||
{ role: "assistant", content: "Recent answer" },
|
||||
])
|
||||
await setup.flush()
|
||||
await ui.transcript.prependHistory([
|
||||
{ role: "assistant", content: "Earlier answer" },
|
||||
{ role: "activity", content: "", compaction: { id: "older", phase: "failed" } },
|
||||
{ role: "activity", content: "", compaction: { id: "recent", phase: "started" } },
|
||||
])
|
||||
await setup.flush()
|
||||
ui.transcript.scrollToEdge("top")
|
||||
await setup.renderOnce()
|
||||
const frame = setup.captureCharFrame()
|
||||
expect(occurrences(frame, "Conversation compacted")).toBe(1)
|
||||
expect(frame).not.toContain("Compacting conversation")
|
||||
expect(frame).toContain("Earlier answer")
|
||||
expect(frame.indexOf("Earlier answer")).toBeLessThan(frame.indexOf("Could not compact conversation"))
|
||||
expect(frame).toContain("Recent answer")
|
||||
expect(frame.indexOf("Could not compact conversation")).toBeLessThan(frame.indexOf("Recent answer"))
|
||||
setup.renderer.emit(CliRenderEvents.THEME_MODE, "light")
|
||||
await setup.flush()
|
||||
const failure = ui.transcript.root.getChildren()
|
||||
.flatMap((row) => row.getChildren())
|
||||
.find((child) => child instanceof TextRenderable && child.plainText.includes("Could not compact"))
|
||||
expect(failure).toBeInstanceOf(TextRenderable)
|
||||
expect((failure as TextRenderable).fg.toInts().slice(0, 3)).toEqual([
|
||||
1, 3, 5,
|
||||
].map((offset) => Number.parseInt(ui.palette.error.slice(offset, offset + 2), 16)))
|
||||
ui.transcript.reset({ model: "model", workspace: "workspace", version: "test", access: "workspace" })
|
||||
app.accept({ event: "context_compaction", chat_id: "chat", compaction_id: "recent", phase: "started" })
|
||||
await setup.renderOnce()
|
||||
expect(setup.captureCharFrame()).toContain("Compacting conversation…")
|
||||
expect(setup.captureCharFrame()).not.toContain("Conversation compacted")
|
||||
})
|
||||
|
||||
test("deduplicates compaction history against events queued during hydration", async () => {
|
||||
setup = await createRenderer({ width: 80, height: 22, screenMode: "alternate-screen" })
|
||||
const original = globalThis.fetch
|
||||
let resolveFetch: (value: Response) => void = () => undefined
|
||||
globalThis.fetch = (() => new Promise<Response>((resolve) => {
|
||||
resolveFetch = resolve
|
||||
})) as unknown as typeof fetch
|
||||
const app = NanobotTui.mount(
|
||||
setup.renderer,
|
||||
{ ...options, apiUrl: "http://nanobot.test", apiToken: "token", chatId: "chat" },
|
||||
client(),
|
||||
new MockTreeSitterClient({ autoResolveTimeout: 0 }),
|
||||
)
|
||||
try {
|
||||
app.accept({ event: "attached", chat_id: "chat" })
|
||||
const event = { event: "context_compaction", chat_id: "chat", compaction_id: "idle" } as const
|
||||
app.accept({ ...event, phase: "started" })
|
||||
app.accept({ ...event, phase: "succeeded" })
|
||||
resolveFetch(Response.json({
|
||||
messages: [{
|
||||
role: "assistant", kind: "compaction", content: "",
|
||||
compaction: { id: "idle", phase: "succeeded" },
|
||||
}],
|
||||
}))
|
||||
await waitUntil(() => (app as unknown as { ready: boolean }).ready)
|
||||
await setup.renderOnce()
|
||||
const frame = setup.captureCharFrame()
|
||||
expect(occurrences(frame, "Conversation compacted")).toBe(1)
|
||||
expect(frame).not.toContain("Compacting conversation")
|
||||
expect((app as unknown as { activeTurn: boolean }).activeTurn).toBe(false)
|
||||
} finally {
|
||||
globalThis.fetch = original
|
||||
}
|
||||
})
|
||||
|
||||
test("replays events after asynchronous history hydration", async () => {
|
||||
setup = await createRenderer({ width: 80, height: 22, screenMode: "alternate-screen" })
|
||||
const original = globalThis.fetch
|
||||
|
||||
@@ -1063,6 +1063,9 @@ export class NanobotTui {
|
||||
}
|
||||
|
||||
switch (event.event) {
|
||||
case "context_compaction":
|
||||
this.transcript.compaction({ id: event.compaction_id, phase: event.phase })
|
||||
return
|
||||
case "message_accepted":
|
||||
this.reconcileTurnOwnership(event)
|
||||
return
|
||||
|
||||
@@ -706,6 +706,54 @@ describe("gateway protocol", () => {
|
||||
}
|
||||
})
|
||||
|
||||
test("receives compaction phases and rejects malformed compaction events", () => {
|
||||
const original = globalThis.WebSocket
|
||||
let socket: FakeSocket | undefined
|
||||
Object.defineProperty(globalThis, "WebSocket", {
|
||||
configurable: true,
|
||||
value: class extends FakeSocket {
|
||||
constructor() {
|
||||
super()
|
||||
socket = this
|
||||
}
|
||||
},
|
||||
})
|
||||
const events: InboundEvent[] = []
|
||||
const statuses: string[] = []
|
||||
const client = new NanobotClient({
|
||||
url: "ws://nanobot.test/ws",
|
||||
onEvent: (event) => events.push(event),
|
||||
onStatus: (status, detail) => statuses.push(`${status}:${detail || ""}`),
|
||||
})
|
||||
try {
|
||||
client.connect()
|
||||
if (!socket) throw new Error("socket was not created")
|
||||
const base = { event: "context_compaction", chat_id: "chat", compaction_id: "compact-1" }
|
||||
for (const phase of ["started", "succeeded", "failed", "cancelled"]) {
|
||||
socket.emit("message", { data: JSON.stringify({
|
||||
...base, phase,
|
||||
}) })
|
||||
}
|
||||
for (const invalid of [
|
||||
{ phase: "unknown" },
|
||||
{ phase: "started", compaction_id: "" },
|
||||
{ phase: "started", compaction_id: 42 },
|
||||
{ phase: "started", compaction_id: undefined },
|
||||
{ phase: "started", chat_id: undefined },
|
||||
]) {
|
||||
socket.emit("message", { data: JSON.stringify({ ...base, ...invalid }) })
|
||||
}
|
||||
expect(events.map((event) => event.event)).toEqual(Array(4).fill("context_compaction"))
|
||||
expect(events.map((event) => "phase" in event ? event.phase : null)).toEqual([
|
||||
"started", "succeeded", "failed", "cancelled",
|
||||
])
|
||||
expect(statuses.filter((status) => status.includes("invalid event"))).toHaveLength(5)
|
||||
} finally {
|
||||
client.close()
|
||||
Object.defineProperty(globalThis, "WebSocket", { configurable: true, value: original })
|
||||
}
|
||||
})
|
||||
|
||||
test("validates nested unified diff payloads at the websocket boundary", () => {
|
||||
const original = globalThis.WebSocket
|
||||
let socket: FakeSocket | undefined
|
||||
@@ -927,6 +975,43 @@ describe("gateway protocol", () => {
|
||||
}
|
||||
})
|
||||
|
||||
test("loads compaction history as activity rows", async () => {
|
||||
const original = globalThis.fetch
|
||||
globalThis.fetch = Object.assign(async () => Response.json({
|
||||
messages: [
|
||||
{ role: "assistant", content: "before" },
|
||||
...["started", "succeeded", "failed", "cancelled"].map((phase) => ({
|
||||
role: "assistant",
|
||||
kind: "compaction",
|
||||
content: "",
|
||||
compaction: { id: phase, phase },
|
||||
})),
|
||||
{ role: "assistant", kind: "compaction", content: "invalid", compaction: null },
|
||||
{
|
||||
role: "assistant", kind: "compaction", content: "invalid",
|
||||
compaction: { id: "", phase: "succeeded" },
|
||||
},
|
||||
{
|
||||
role: "assistant", kind: "compaction", content: "invalid",
|
||||
compaction: { id: "unknown", phase: "unknown" },
|
||||
},
|
||||
{ role: "assistant", content: "after" },
|
||||
],
|
||||
}), { preconnect: original.preconnect })
|
||||
try {
|
||||
const history = await fetchHistory("http://nanobot.test", "token", "chat")
|
||||
expect(history.messages).toEqual([
|
||||
{ role: "assistant", content: "before", forkIndex: 0 },
|
||||
...(["started", "succeeded", "failed", "cancelled"] as const).map((phase) => ({
|
||||
role: "activity" as const, content: "", compaction: { id: phase, phase },
|
||||
})),
|
||||
{ role: "assistant", content: "after", forkIndex: 0 },
|
||||
])
|
||||
} finally {
|
||||
globalThis.fetch = original
|
||||
}
|
||||
})
|
||||
|
||||
test("loads the explainable session context projection", async () => {
|
||||
const original = globalThis.fetch
|
||||
globalThis.fetch = (() => Promise.resolve(new Response(JSON.stringify({
|
||||
|
||||
@@ -86,6 +86,11 @@ export interface RecoveryState {
|
||||
can_continue?: boolean
|
||||
}
|
||||
|
||||
export interface ContextCompaction {
|
||||
id: string
|
||||
phase: "started" | "succeeded" | "failed" | "cancelled"
|
||||
}
|
||||
|
||||
export type InboundEvent =
|
||||
| { event: "ready"; chat_id: string; client_id: string }
|
||||
| {
|
||||
@@ -152,6 +157,12 @@ export type InboundEvent =
|
||||
}
|
||||
| { event: "goal_state"; chat_id: string; goal_state: Record<string, unknown> }
|
||||
| ({ event: "recovery_state"; chat_id: string } & RecoveryState)
|
||||
| {
|
||||
event: "context_compaction"
|
||||
chat_id: string
|
||||
compaction_id: string
|
||||
phase: ContextCompaction["phase"]
|
||||
}
|
||||
| {
|
||||
event: "session_updated"
|
||||
chat_id: string
|
||||
@@ -234,6 +245,7 @@ export interface HistoryMessage {
|
||||
media?: MediaAttachment[]
|
||||
toolEvents?: ToolProgressEvent[]
|
||||
fileEdits?: FileEditEvent[]
|
||||
compaction?: ContextCompaction
|
||||
forkIndex?: number
|
||||
}
|
||||
|
||||
@@ -356,6 +368,7 @@ const CHAT_EVENTS = new Set([
|
||||
"goal_status",
|
||||
"goal_state",
|
||||
"recovery_state",
|
||||
"context_compaction",
|
||||
"session_updated",
|
||||
"turn_model_updated",
|
||||
"error",
|
||||
@@ -369,6 +382,10 @@ function optional(value: unknown, type: "boolean" | "number" | "string"): boolea
|
||||
return value === undefined || typeof value === type
|
||||
}
|
||||
|
||||
function isCompactionPhase(value: unknown): value is ContextCompaction["phase"] {
|
||||
return value === "started" || value === "succeeded" || value === "failed" || value === "cancelled"
|
||||
}
|
||||
|
||||
function isToolEvent(value: unknown): value is ToolProgressEvent {
|
||||
if (!isRecord(value)) return false
|
||||
return optional(value.version, "number")
|
||||
@@ -544,6 +561,12 @@ function decodeInboundEvent(value: unknown): InboundEvent | null | undefined {
|
||||
if (name === "goal_status" && record.status !== "running" && record.status !== "idle") return null
|
||||
if (name === "goal_state" && !isRecord(record.goal_state)) return null
|
||||
if (name === "recovery_state" && !isRecoveryState(record)) return null
|
||||
if (
|
||||
name === "context_compaction"
|
||||
&& (typeof record.compaction_id !== "string"
|
||||
|| !record.compaction_id
|
||||
|| !isCompactionPhase(record.phase))
|
||||
) return null
|
||||
if (
|
||||
name === "session_updated"
|
||||
&& (!optional(record.scope, "string")
|
||||
@@ -608,6 +631,20 @@ export async function fetchHistory(
|
||||
for (const message of payload.messages || []) {
|
||||
const role = message.role
|
||||
const content = message.content
|
||||
if (message.kind === "compaction") {
|
||||
const compaction = message.compaction
|
||||
if (isRecord(compaction)
|
||||
&& typeof compaction.id === "string"
|
||||
&& compaction.id
|
||||
&& isCompactionPhase(compaction.phase)) {
|
||||
messages.push({
|
||||
role: "activity",
|
||||
content: "",
|
||||
compaction: { id: compaction.id, phase: compaction.phase },
|
||||
})
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (role === "tool" && message.kind === "trace") {
|
||||
const traces = Array.isArray(message.traces)
|
||||
? message.traces.filter((value): value is string => typeof value === "string")
|
||||
|
||||
+45
-2
@@ -14,6 +14,7 @@ import {
|
||||
} from "@opentui/core"
|
||||
|
||||
import type {
|
||||
ContextCompaction,
|
||||
FileEditEvent,
|
||||
HistoryMessage,
|
||||
MediaAttachment,
|
||||
@@ -126,6 +127,10 @@ export class Transcript {
|
||||
}> = []
|
||||
private readonly markdown = new Set<MarkdownRenderable>()
|
||||
private readonly activities = new Set<Activity>()
|
||||
private readonly compactions = new Map<string, {
|
||||
phase: ContextCompaction["phase"]
|
||||
text: TextRenderable
|
||||
}>()
|
||||
private readonly frames = new Set<BoxRenderable>()
|
||||
private readonly userRows = new Set<BoxRenderable>()
|
||||
private readonly userMessages = new Set<{
|
||||
@@ -181,6 +186,9 @@ export class Transcript {
|
||||
this.theme = theme
|
||||
this.codeRailColor = RGBA.fromHex(theme.border)
|
||||
for (const { renderable, tone } of this.styledText) renderable.fg = theme[tone]
|
||||
for (const { text, phase } of this.compactions.values()) {
|
||||
text.fg = phase === "failed" ? theme.error : theme.muted
|
||||
}
|
||||
for (const message of this.userMessages) {
|
||||
message.renderable.content = this.userMessageContent(
|
||||
message.content,
|
||||
@@ -243,6 +251,7 @@ export class Transcript {
|
||||
this.styledText.length = 0
|
||||
this.markdown.clear()
|
||||
this.activities.clear()
|
||||
this.compactions.clear()
|
||||
this.frames.clear()
|
||||
this.userRows.clear()
|
||||
this.userMessages.clear()
|
||||
@@ -257,7 +266,8 @@ export class Transcript {
|
||||
|
||||
history(messages: HistoryMessage[]): void {
|
||||
for (const message of messages) {
|
||||
if (message.role === "user") {
|
||||
if (message.compaction) this.compaction(message.compaction)
|
||||
else if (message.role === "user") {
|
||||
this.user(message.content, message.turnId, message.media)
|
||||
}
|
||||
else if (message.role === "assistant") this.assistant(message.content)
|
||||
@@ -273,7 +283,9 @@ export class Transcript {
|
||||
const previousHeight = this.root.scrollHeight
|
||||
let index = 1 // Keep the launch header first.
|
||||
for (const message of messages) {
|
||||
if (message.role === "user") {
|
||||
if (message.compaction) {
|
||||
if (this.compaction(message.compaction, index)) index += 1
|
||||
} else if (message.role === "user") {
|
||||
if (message.turnId && this.userTurnIds.has(message.turnId)) continue
|
||||
this.writeUser(message.content, message.media, index++)
|
||||
if (message.turnId) this.userTurnIds.add(message.turnId)
|
||||
@@ -328,6 +340,36 @@ export class Transcript {
|
||||
this.writeRole(error ? "×" : "·", content, error ? "error" : "muted")
|
||||
}
|
||||
|
||||
compaction(compaction: ContextCompaction, index?: number): boolean {
|
||||
let entry = this.compactions.get(compaction.id)
|
||||
// Hydration can replay a terminal state before an already queued start event.
|
||||
if (entry && (entry.phase !== "started" || entry.phase === compaction.phase)) return false
|
||||
const added = !entry
|
||||
if (index === undefined) {
|
||||
this.noteOutput()
|
||||
if (added) this.finishActivity()
|
||||
}
|
||||
if (!entry) {
|
||||
const row = this.createRow("compaction")
|
||||
const text = this.createText("", "muted", false, "compaction-status")
|
||||
row.add(text)
|
||||
this.root.add(row, index)
|
||||
this.wrote = true
|
||||
entry = { phase: compaction.phase, text }
|
||||
this.compactions.set(compaction.id, entry)
|
||||
}
|
||||
entry.phase = compaction.phase
|
||||
entry.text.content = compaction.phase === "started"
|
||||
? " ≋ Compacting conversation…"
|
||||
: compaction.phase === "succeeded"
|
||||
? " ✓ Conversation compacted"
|
||||
: compaction.phase === "cancelled"
|
||||
? " · Conversation compaction cancelled"
|
||||
: " × Could not compact conversation"
|
||||
entry.text.fg = compaction.phase === "failed" ? this.theme.error : this.theme.muted
|
||||
return added
|
||||
}
|
||||
|
||||
stream(delta: string): void {
|
||||
if (!delta) return
|
||||
this.noteOutput()
|
||||
@@ -416,6 +458,7 @@ export class Transcript {
|
||||
this.pendingStream = ""
|
||||
this.live = null
|
||||
this.activity = null
|
||||
this.compactions.clear()
|
||||
this.frames.clear()
|
||||
this.userRows.clear()
|
||||
this.userMessages.clear()
|
||||
|
||||
Reference in new issue
Block a user