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
+9
View File
@@ -336,6 +336,15 @@ history refresh without inventing text deltas or ending a queued prompt. Native
step markers may include `step.turn_id`; a terminal marker for an older turn
must not clear a newer turn's Stop control or release its queue slot.
Native context compaction is reported as `chat_event.kind="compaction"`, with
`compaction: {status: "running" | "completed" | "failed", id?: string}`.
This is session activity and may have no `message_id`: clients must not invent
an assistant message or tool call for it. Show **Compacting context…** while
running; completion clears that phase but does not itself end the model turn.
A new subscriber receives any retained active compaction. Clear stale activity
before reconnecting, then preserve fresh replayed activity while history loads.
This reports native observations only; it does not request or trigger compaction.
The brokered OpenCode chat exposes the operator's own sessions, separate from the
sessions pipeline runs create. The protocol types are:
+18
View File
@@ -8,6 +8,24 @@ test, or a code change without a capture, is `partial` at best.
Status legend: `todo` · `partial` (some of it works) · `done` (working + captured).
### Context compaction activity (2026-10-20)
**Partial against the live-provider gate.** A native compaction frame shows
**Compacting context…** with the active turn's spinner and Stop control, even
before the first answer or alongside existing reasoning/tools. Previously stored
reasoning is labeled Reasoning, not actively Thinking, while context compacts.
The label clears on compaction completion/failure; that does not finish the
surrounding model turn or count as a tool/message. Disconnect/turn settlement
clear stale activity. Reconnect clears stale state before subscribing, then keeps
fresh replayed activity while authoritative history loads.
`test/chat-compaction-browser.mjs` captures before-answer and with-history states
at 390/1100px plus cleared-on-disconnect. It checks polite status announcements,
no horizontal overflow, preserved message counts and Stop lifecycle. Captures:
approved OpenCode temporary `chat-compaction-captures/` directory. Fixtures do not
trigger compaction, inference or changes to real chats. A server update is needed
for the new native activity frames; shell cache v11 refreshes the browser modules.
### Tool summary error scope (2026-10-20)
The aggregate **N tools** label stays neutral and borderless even when a call
+3
View File
@@ -512,6 +512,9 @@
.chat-activity-elapsed { flex: none; }
.chat-activity-sep { color: var(--muted); flex: none; }
.chat-activity-head > .chat-tool-chip { min-width: 0; overflow: hidden; }
.chat-activity-compacting { flex-wrap: wrap; row-gap: 0; }
.chat-compaction-break { flex-basis: 100%; height: 0; }
.chat-compaction-status { color: var(--accent); }
.chat-jump { position: absolute; right: 14px; bottom: 14px; border-color: var(--accent); color: var(--accent); }
+28 -3
View File
@@ -1209,6 +1209,7 @@ export function mergeHistoryPage(previous, page, { older = false } = {}) {
/** ChatEvent.Kind values pushed on the `chat_event` stream (internal/protocol/chat.go). */
export const EVENT_STEP = "step";
export const EVENT_COMPACTION = "compaction";
export const EVENT_USAGE = "usage";
export const EVENT_USER = "user";
export const EVENT_SHELL = "shell";
@@ -1222,6 +1223,7 @@ export const STEP_ENDED = "ended";
export const TURN_PHASE_THINKING = "thinking";
export const TURN_PHASE_TOOL = "tool";
export const TURN_PHASE_WAITING = "waiting";
export const TURN_PHASE_COMPACTING = "compacting";
/**
* The live-stream badge words, shared verbatim with `liveBadgeState` /
@@ -1396,6 +1398,7 @@ export function newChatThread(sessionId = "") {
error: "",
running: false,
runningSince: 0,
compaction: null,
toolStartedAt: {},
lastDeltaAt: 0,
queued: false,
@@ -1430,6 +1433,7 @@ export function settledThread(thread) {
...(thread ?? {}),
running: false,
runningSince: 0,
compaction: null,
toolStartedAt: {},
lastDeltaAt: 0,
queued: false,
@@ -1555,6 +1559,7 @@ export function turnPhase(tools) {
/** The running indicator's headline for [phase], naming what is happening. */
export function turnPhaseLabel(phase) {
if (phase === TURN_PHASE_COMPACTING) return "Compacting context…";
if (phase === TURN_PHASE_THINKING) return "Thinking…";
if (phase === TURN_PHASE_TOOL) return "Running a tool…";
return "Waiting…";
@@ -1567,6 +1572,7 @@ export function turnPhaseLabel(phase) {
*/
export function threadPhase(thread, nowMillis) {
if (!thread?.running) return null;
if (thread.compaction?.status === "running") return TURN_PHASE_COMPACTING;
if (thread.queued) return TURN_PHASE_WAITING;
return turnPhase(threadRunningTools(thread.messages));
}
@@ -1609,6 +1615,7 @@ export function applyChatForm(thread, form) {
* targets is created on first sight, so a live turn never gains a second bubble.
*/
export function applyChatEvent(thread, frame, now = Date.now()) {
if (frame?.kind === EVENT_COMPACTION) return applyChatCompaction(thread, frame, now);
if (frame?.kind === EVENT_RESYNC) return thread ?? newChatThread(str(frame?.session_id));
if (frame?.kind === EVENT_STEP && frame.step?.status === STEP_ENDED && frame.step?.turn_id && frame.step.turn_id !== thread?.nativeTurnId) return thread ?? newChatThread(str(frame?.session_id));
const current = thread?.queued
@@ -1641,6 +1648,21 @@ export function applyChatEvent(thread, frame, now = Date.now()) {
}
}
/** Native session activity, not a synthetic tool call or assistant message. */
function applyChatCompaction(thread, frame, now) {
const current = thread ?? newChatThread(str(frame?.session_id));
if (current.sessionId && frame.session_id !== current.sessionId) return current;
const incoming = frame.compaction;
if (!incoming || !["running", "completed", "failed"].includes(incoming.status)) return current;
if (incoming.status === "running") {
return setThreadRunning({ ...current, compaction: { id: str(incoming.id), status: "running" } }, true, now);
}
if (!current.compaction || (incoming.id && current.compaction.id && incoming.id !== current.compaction.id)) return current;
// A compacted context can immediately continue the same model turn. Only a
// real final step/interrupt/disconnect settles the turn and its Stop control.
return { ...current, compaction: null };
}
/**
* Folds a user turn another client sent into the transcript, in place, once. The
* server never echoes this client's own prompts, so the sender's own message is
@@ -1740,8 +1762,10 @@ function upsertParts(thread, frame, now, deltaArrivedAt, upsert) {
* dropped too (the reconnect re-fetches `chat_shells`), exactly like the Android
* `streamResumed` path.
*/
export function historyResync(thread, page) {
const settled = resumedThread(thread ?? newChatThread());
export function historyResync(thread, page, { preserveActivity = false } = {}) {
// Reconnect callers clear stale activity BEFORE reattaching. Anything learned
// after that reset is fresh native state and must survive the history read.
const settled = preserveActivity ? (thread ?? newChatThread()) : resumedThread(thread ?? newChatThread());
return {
...settled,
messages: (page?.messages ?? []).slice(),
@@ -1951,7 +1975,7 @@ export function composerSubmit(thread, selected = 0) {
* (mirrors ChatStore.event). A null frame leaves the flag untouched.
*/
export function queuedAfterFrame(queued, frame) {
if (frame == null) return queued === true;
if (frame == null || frame.kind === EVENT_COMPACTION) return queued === true;
return false;
}
@@ -1962,6 +1986,7 @@ export function queuedAfterFrame(queued, frame) {
* running bit, which the composer's Stop control reads.
*/
export function runningAfterFrame(running, frame) {
if (frame?.kind === EVENT_COMPACTION && frame.compaction?.status === "running") return true;
if (frame?.kind === "step" && frame?.step?.status === "ended" && !frame?.step?.intermediate) return false;
return running === true;
}
+17 -5
View File
@@ -158,6 +158,7 @@ import {
threadPhase,
threadToolElapsedMillis,
TURN_PHASE_WAITING,
TURN_PHASE_COMPACTING,
toolCallCount,
toolCallRow,
toolCallsAnnouncement,
@@ -1017,12 +1018,12 @@ function shellOutputFailed(sessionId, shellId, message) {
async function resyncOpenChat() {
const id = state.chatActiveId;
if (!id || state.connection.kind !== "connected") return;
await subscribeChatSession(id);
const previous = state.chatThreads.get(id) ?? newChatThread(id);
state.chatThreads.set(id, resumedThread(previous));
await subscribeChatSession(id);
try {
const page = await repo.chatHistory(id);
state.chatThreads.set(id, historyResync(previous, page));
state.chatThreads.set(id, historyResync(state.chatThreads.get(id), page, { preserveActivity: true }));
} catch {
// The history refresh failed; the settled thread stands and the badge is honest.
}
@@ -3400,6 +3401,8 @@ function renderChatActivity(turn, streaming = false, elapsedMillis = () => 0, th
class: `chat-reasoning chat-activity${streaming ? " chat-reasoning-live" : ""}`,
});
const head = h("div", { class: "chat-activity-head" });
const compacting = streaming && threadPhase(thread, Date.now()) === TURN_PHASE_COMPACTING;
if (compacting) head.classList.add("chat-activity-compacting");
if (streaming) {
const spinner = h("span", {
class: "spinner chat-activity-spinner",
@@ -3409,9 +3412,18 @@ function renderChatActivity(turn, streaming = false, elapsedMillis = () => 0, th
spinner.style.animationDelay = `-${(performance.now() % 800) / 1000}s`;
head.append(spinner);
}
if (compacting) {
head.append(h("span", {
class: "chat-activity-phase chat-compaction-status",
role: "status",
"aria-live": "polite",
text: turnPhaseLabel(TURN_PHASE_COMPACTING),
}));
if (steps.length || parts.length) head.append(h("span", { class: "chat-compaction-break", "aria-hidden": "true" }));
}
if (steps.length > 0) {
head.append(renderChatReasoningToggle(turn, streaming, steps));
} else if (streaming) {
head.append(renderChatReasoningToggle(turn, streaming && !compacting, steps));
} else if (streaming && !compacting) {
head.append(
h("span", {
class: "chat-activity-phase",
@@ -3420,7 +3432,7 @@ function renderChatActivity(turn, streaming = false, elapsedMillis = () => 0, th
);
}
if (parts.length > 0) {
if (head.childElementCount > 0) head.append(h("span", { class: "chat-activity-sep", text: "\u00b7" }));
if (steps.length > 0 || (streaming && !compacting)) head.append(h("span", { class: "chat-activity-sep", text: "\u00b7" }));
head.append(renderChatToolChip(turn, { streaming, elapsedMillis }));
}
const elapsed = streaming
+1 -1
View File
@@ -1,7 +1,7 @@
// A shell cache for an installed Pipelines app. The API (the WebSocket proxy and
// artifact files) is never cached; static files prefer the network and fall back
// to the last good copy so an installed app still opens when the server is away.
const CACHE = "pipelines-shell-v10";
const CACHE = "pipelines-shell-v11";
const SHELL = ["/", "/index.html", "/manifest.webmanifest", "/favicon.svg"];
self.addEventListener("install", (event) => {
+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"]);
});