feat(web): show native context compaction activity in chat

This commit is contained in:
2026-10-20 22:15:03 +01:00
parent aa57fe8a04
commit d8b111913e
9 changed files with 216 additions and 11 deletions
+68
View File
@@ -0,0 +1,68 @@
// Native compaction fixture through the real chat fold/view; no harness calls.
import assert from "node:assert/strict";
import { createServer } from "node:http";
import { readFile, mkdir } from "node:fs/promises";
import { resolve, extname, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { launchChrome } from "./browser.mjs";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const out = resolve(process.argv[2] ?? "captures-chat-compaction");
await mkdir(out, {recursive:true});
const html = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
${["design/tokens/tokens","base","shell","lists","run-detail","chat","dialogs"].map(n=>`<link rel="stylesheet" href="/${n}.css">`).join("")}
<div class="app-root"><main class="workspace"><div class="pane-main"><div class="content" id="content"></div></div></main></div>
<script type="module">
import { createChatView } from '/src/views/chat.js';
import { newChatThread, applyChatEvent, resumedThread } from '/src/chat.js';
const id='scratch';
const state={view:'chat',chatActiveId:id,chatSessions:[{id,title:'Context compaction',backend:'opencode'}],chatOverrides:{},chatDrafts:{},chatThreads:new Map()};
const rt={state,repo:{},renderContent:()=>paint(),closeDetail:()=>{}};
const view=createChatView(rt);
window.paint=()=>document.querySelector('#content').replaceChildren(view.renderChatConversation());
window.setup=(history)=>{
const messages=[{id:'user',role:'user',parts:[{type:'text',text:'Continue the task.'}]}];
if(history)messages.push({id:'assistant',role:'assistant',parts:[{id:'reason',type:'reasoning',text:'Inspecting the existing context.'},{id:'tool',type:'tool',name:'read',state:{status:'completed'}},{type:'text',text:'Continuing after checking the files.'}]});
state.chatThreads.set(id,{...newChatThread(id),loaded:true,messages});paint();};
window.event=(status)=>{state.chatThreads.set(id,applyChatEvent(state.chatThreads.get(id),{session_id:id,kind:'compaction',compaction:{id:'native-compaction',status}}));paint();};
window.end=()=>{state.chatThreads.set(id,applyChatEvent(state.chatThreads.get(id),{session_id:id,kind:'step',step:{status:'ended'}}));paint();};
window.drop=()=>{state.chatThreads.set(id,resumedThread(state.chatThreads.get(id)));paint();};
window.messageCount=()=>state.chatThreads.get(id).messages.length;
setup(true);
</script>`;
const server=createServer(async(req,res)=>{try{
const path=new URL(req.url,"http://fixture").pathname;
if(path==="/"){res.setHeader("Content-Type","text/html");res.end(html);return;}
const file=resolve(root,`.${path}`);if(!file.startsWith(root+"/"))throw Error("outside fixture");
res.setHeader("Content-Type",extname(file)===".css"?"text/css":"text/javascript");res.end(await readFile(file));
}catch{res.writeHead(404);res.end();}});
await new Promise(r=>server.listen(0,"127.0.0.1",r));
let browser;
try {
browser=await launchChrome();
const page=await browser.openPage(`http://127.0.0.1:${server.address().port}/`);
await page.waitForSelector("#chatInput");
for(const width of [390,1100]) {
await page.resize(width,844);
for(const history of [false,true]) {
await page.evaluate(`setup(${history});event('running')`);
await page.waitForSelector(".chat-compaction-status");
assert.equal(await page.evaluate("document.querySelector('.chat-compaction-status').textContent"),"Compacting context…");
assert.equal(await page.evaluate("document.querySelector('.chat-compaction-status').getAttribute('role')"),"status");
assert.equal(await page.evaluate("messageCount()"),history?2:1);
assert.equal(await page.evaluate("document.querySelectorAll('#chatStop').length"),1);
if(history) assert.equal(await page.evaluate("document.querySelector('.chat-reasoning-label').textContent"),"Reasoning");
assert.equal(await page.evaluate("document.documentElement.scrollWidth>innerWidth"),false);
await page.screenshot(resolve(out,`compacting-${history?'with-history':'before-answer'}-${width}.png`));
await page.evaluate("event('completed')");
assert.equal(await page.evaluate("document.querySelectorAll('.chat-compaction-status').length"),0);
assert.equal(await page.evaluate("document.querySelectorAll('#chatStop').length"),1);
await page.evaluate("end()");
assert.equal(await page.evaluate("document.querySelectorAll('#chatStop').length"),0);
}
}
await page.evaluate("setup(true);event('running');drop()");
assert.equal(await page.evaluate("document.querySelectorAll('.chat-compaction-status').length"),0);
await page.screenshot(resolve(out,"compaction-clears-on-disconnect.png"));
console.log("PASS: compaction is visible before the first answer and alongside reasoning/tools, clears on completion/disconnect, and never creates a fake message or ends the turn.");
} finally {await browser?.close();await new Promise(r=>server.close(r));}
+70
View File
@@ -0,0 +1,70 @@
import test from "node:test";
import assert from "node:assert/strict";
import { applyChatEvent, newChatThread, threadPhase, turnPhaseLabel, settledThread, resumedThread, historyResync, runningAfterFrame, queuedAfterFrame } from "../src/chat.js";
const compact = (status, id="compact-1", session="session-1") => ({session_id:session,kind:"compaction",compaction:{status,id}});
test("silence or model-authored text never invents compaction activity", () => {
const thread={...newChatThread("session-1"),running:true,runningSince:1,messages:[{role:"assistant",parts:[{type:"text",text:"Compacting context"}]}]};
assert.equal(threadPhase(thread,10_000_000),"thinking");
});
test("native compaction shows an explicit phase without inventing a tool or message", () => {
const original={...newChatThread("session-1"),loaded:true,queued:true};
const current=applyChatEvent(original,compact("running"),100);
assert.equal(current.running,true);
assert.equal(current.queued,true);
assert.equal(threadPhase(current,200),"compacting");
assert.equal(turnPhaseLabel(threadPhase(current,200)),"Compacting context…");
assert.deepEqual(current.messages,[]);
assert.equal(runningAfterFrame(false,compact("running")),true);
assert.equal(queuedAfterFrame(true,compact("running")),true);
});
test("compaction takes priority over old reasoning and tool activity", () => {
const current=applyChatEvent({...newChatThread("session-1"),running:true,messages:[{role:"assistant",parts:[{type:"tool",state:{status:"running"}}]}]},compact("running"),100);
assert.equal(threadPhase(current,200),"compacting");
const completed=applyChatEvent(current,compact("completed"),300);
assert.equal(completed.compaction,null);
assert.equal(completed.running,true);
assert.equal(threadPhase(completed,400),"tool");
});
test("a terminal compaction update does not complete the surrounding model turn", () => {
for (const status of ["completed","failed"]) {
const current=applyChatEvent(newChatThread("session-1"),compact("running"),100);
const next=applyChatEvent(current,compact(status),200);
assert.equal(next.compaction,null);
assert.equal(next.running,true);
assert.equal(threadPhase(next,250),"thinking");
assert.equal(runningAfterFrame(true,compact(status)),true);
}
});
test("other-session events and late completions cannot clear a newer compaction", () => {
const current=applyChatEvent(newChatThread("session-1"),compact("running","new"),100);
assert.equal(applyChatEvent(current,compact("completed","old"),200),current);
assert.equal(applyChatEvent(current,compact("running","other","session-2"),200),current);
assert.equal(applyChatEvent(current,compact("unrecognised"),200),current);
});
test("turn completion, interruption, and reconnect clear stale compaction state", () => {
const current=applyChatEvent(newChatThread("session-1"),compact("running"),100);
for (const next of [settledThread(current),resumedThread(current),historyResync(current,{messages:[]}),applyChatEvent(current,{kind:"step",step:{status:"ended"}},200)]) {
assert.equal(next.compaction,null);
assert.equal(threadPhase(next,300),null);
}
const intermediate=applyChatEvent(current,{kind:"step",step:{status:"ended",intermediate:true}},200);
assert.equal(threadPhase(intermediate,300),"compacting");
});
test("authoritative history cannot erase fresh compaction replayed after reconnect reset", () => {
const old=applyChatEvent(newChatThread("session-1"),compact("running","old"),100);
const reset=resumedThread(old);
const replayed=applyChatEvent(reset,compact("running","fresh"),200);
const synced=historyResync(replayed,{messages:[{id:"native-history",role:"user",parts:[]}]},{preserveActivity:true});
assert.equal(threadPhase(synced,300),"compacting");
assert.equal(synced.compaction.id,"fresh");
assert.deepEqual(synced.messages,[{id:"native-history",role:"user",parts:[]}]);
assert.equal(historyResync(reset,{messages:[]},{preserveActivity:true}).compaction,null);
});
+2 -2
View File
@@ -9,9 +9,9 @@ test("shell updates retain unrelated caches and the current app cache", async ()
let activation;
vm.runInNewContext(await readFile(new URL("../sw.js", import.meta.url), "utf8"), {
self: { addEventListener: (type, handler) => handlers.set(type, handler), clients: { claim: async () => {} } },
caches: { keys: async () => ["pipelines-shell-v9", "pipelines-shell-v10", "unrelated-user-cache"], delete: async (key) => deleted.push(key) },
caches: { keys: async () => ["pipelines-shell-v10", "pipelines-shell-v11", "unrelated-user-cache"], delete: async (key) => deleted.push(key) },
});
handlers.get("activate")({ waitUntil: (promise) => { activation = promise; } });
await activation;
assert.deepEqual(deleted, ["pipelines-shell-v9"]);
assert.deepEqual(deleted, ["pipelines-shell-v10"]);
});