From ba8a981932126b7437ddbaec8f809a25af856dfc Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Tue, 20 Oct 2026 22:24:29 +0100 Subject: [PATCH] fix(chat): preserve fresh compaction state across reconnect history --- docs/cli.md | 2 ++ web/PARITY.md | 8 +++++++- web/src/chat.js | 15 +++++++++++---- web/src/views/chat.js | 8 ++++++-- web/test/chat-compaction-browser.mjs | 11 ++++++++--- web/test/chatCompaction.test.mjs | 14 ++++++++++++++ 6 files changed, 48 insertions(+), 10 deletions(-) diff --git a/docs/cli.md b/docs/cli.md index 189e4584..68071339 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -338,6 +338,8 @@ 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}`. +Optional `native_turn_id` scopes the activity to its real harness turn; ignore +activity for an older turn when a newer native turn is known. 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. diff --git a/web/PARITY.md b/web/PARITY.md index 39703495..ebec43ab 100644 --- a/web/PARITY.md +++ b/web/PARITY.md @@ -18,10 +18,16 @@ 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. +OpenCode V2's native compaction lifecycle and Codex's `contextCompaction` items +are normalized by the server, with retained active replay and native turn/item +identity checks where available. No state is inferred from slow responses or +model-authored text. Backend regression fixtures exercise the native schemas; +no live provider compaction was triggered for verification. `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: +no horizontal overflow, preserved message counts, Stop lifecycle, and actual +reconnect-handler replay surviving the history read. 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. diff --git a/web/src/chat.js b/web/src/chat.js index adace062..3fa9606d 100644 --- a/web/src/chat.js +++ b/web/src/chat.js @@ -1219,7 +1219,7 @@ export const EVENT_RESYNC = "resync"; /** ChatStep.Status values. `ended` is the one status that settles a turn. */ export const STEP_ENDED = "ended"; -/** The three things an in-flight turn can be doing (ChatFormat.kt TurnPhase). */ +/** Native activity phases; compaction extends the ordinary turn phases. */ export const TURN_PHASE_THINKING = "thinking"; export const TURN_PHASE_TOOL = "tool"; export const TURN_PHASE_WAITING = "waiting"; @@ -1397,6 +1397,7 @@ export function newChatThread(sessionId = "") { loading: false, error: "", running: false, + nativeTurnId: "", runningSince: 0, compaction: null, toolStartedAt: {}, @@ -1432,6 +1433,7 @@ export function settledThread(thread) { return { ...(thread ?? {}), running: false, + nativeTurnId: "", runningSince: 0, compaction: null, toolStartedAt: {}, @@ -1607,7 +1609,8 @@ export function applyChatForm(thread, form) { /** * Applies one pushed `chat_event` frame to a conversation and returns the next - * thread. Any frame clears `queued` (the turn moved on); `user` echoes another + * thread. Turn frames clear `queued` (compaction does not admit a queued prompt); + * `user` echoes another * client's prompt once (never this client's own), `text`/`reasoning` append to the * part their kind started, `tool` merges field by field, `step` drives the running * flag, and `shell` folds one background process into the retained set without @@ -1654,8 +1657,11 @@ function applyChatCompaction(thread, frame, now) { if (current.sessionId && frame.session_id !== current.sessionId) return current; const incoming = frame.compaction; if (!incoming || !["running", "completed", "failed"].includes(incoming.status)) return current; + const nativeTurnId = str(frame.native_turn_id); + if (nativeTurnId && current.nativeTurnId && nativeTurnId !== current.nativeTurnId) return current; if (incoming.status === "running") { - return setThreadRunning({ ...current, compaction: { id: str(incoming.id), status: "running" } }, true, now); + return setThreadRunning({ ...current, nativeTurnId: nativeTurnId || current.nativeTurnId || "", + 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 @@ -1972,7 +1978,8 @@ export function composerSubmit(thread, selected = 0) { /** * The queued flag after one pushed frame for the session: any frame means the * turn the prompt was waiting behind has moved on, so the queued notice clears - * (mirrors ChatStore.event). A null frame leaves the flag untouched. + * (mirrors ChatStore.event). Null/compaction frames leave it untouched: context + * maintenance alone does not admit the queued prompt. */ export function queuedAfterFrame(queued, frame) { if (frame == null || frame.kind === EVENT_COMPACTION) return queued === true; diff --git a/web/src/views/chat.js b/web/src/views/chat.js index 6b8a2622..63497547 100644 --- a/web/src/views/chat.js +++ b/web/src/views/chat.js @@ -1025,7 +1025,7 @@ async function resyncOpenChat() { const page = await repo.chatHistory(id); 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. + // Keep fresh replayed activity if any; otherwise the settled reset stands. } await loadChatShells(id); renderContent(); @@ -1382,6 +1382,9 @@ function refreshChatComposerState(sessionId) { function onChatFrame(message) { const frame = message?.chat_event; if (!frame || !frame.session_id) return; + // onChatEvent already folded this session activity with native identity + // checks and refreshed the composer. Do not reapply an ignored stale start. + if (frame.kind === "compaction") return; rt.touchView?.("chat"); const sessionId = frame.session_id; const thread = state.chatThreads.get(sessionId); @@ -4330,7 +4333,8 @@ function updateChatIndicator(now) { } const phase = [...document.querySelectorAll("#chatTranscript .chat-activity-phase")].at(-1); if (phase) { - phase.textContent = turnPhaseLabel(threadPhase(thread, now) ?? TURN_PHASE_WAITING); + const label = turnPhaseLabel(threadPhase(thread, now) ?? TURN_PHASE_WAITING); + if (phase.textContent !== label) phase.textContent = label; } } diff --git a/web/test/chat-compaction-browser.mjs b/web/test/chat-compaction-browser.mjs index 5edaf8ea..26cc256a 100644 --- a/web/test/chat-compaction-browser.mjs +++ b/web/test/chat-compaction-browser.mjs @@ -16,8 +16,9 @@ ${["design/tokens/tokens","base","shell","lists","run-detail","chat","dialogs"]. 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 state={view:'chat',connection:{kind:'connected'},chatSubscriptions:new Set(),chatActiveId:id,chatSessions:[{id,title:'Context compaction',backend:'opencode'}],chatOverrides:{},chatDrafts:{},chatThreads:new Map()}; +const repo={subscribeChat:async()=>{event('running');},chatHistory:async()=>({messages:state.chatThreads.get(id).messages}),chatShells:async()=>[]}; +const rt={state,repo,renderContent:()=>paint(),closeDetail:()=>{}}; const view=createChatView(rt); window.paint=()=>document.querySelector('#content').replaceChildren(view.renderChatConversation()); window.setup=(history)=>{ @@ -27,6 +28,7 @@ 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.reconnect=()=>{state.chatSubscriptions.clear();return view.resyncOpenChat();}; window.messageCount=()=>state.chatThreads.get(id).messages.length; setup(true); `; @@ -64,5 +66,8 @@ try { 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."); + await page.evaluate("reconnect()"); + assert.equal(await page.evaluate("document.querySelector('.chat-compaction-status')?.textContent"),"Compacting context…"); + await page.screenshot(resolve(out,"compaction-replay-survives-history-refresh.png")); + console.log("PASS: native compaction is visible before/alongside answers, clears on completion/disconnect, survives reconnect history refresh, and creates no fake message or premature turn completion."); } finally {await browser?.close();await new Promise(r=>server.close(r));} diff --git a/web/test/chatCompaction.test.mjs b/web/test/chatCompaction.test.mjs index 36632818..43ba1271 100644 --- a/web/test/chatCompaction.test.mjs +++ b/web/test/chatCompaction.test.mjs @@ -68,3 +68,17 @@ test("authoritative history cannot erase fresh compaction replayed after reconne assert.deepEqual(synced.messages,[{id:"native-history",role:"user",parts:[]}]); assert.equal(historyResync(reset,{messages:[]},{preserveActivity:true}).compaction,null); }); + +test("native turn identity protects compaction and allows the reattached turn to settle", () => { + const original={...newChatThread("session-1"),running:true,nativeTurnId:"new-turn"}; + const old={...compact("running"),native_turn_id:"old-turn"}; + assert.equal(applyChatEvent(original,old,100),original); + const reset=resumedThread(original); + assert.equal(reset.nativeTurnId,""); + const replay=applyChatEvent(reset,{...compact("running"),native_turn_id:"current-turn"},200); + assert.equal(replay.nativeTurnId,"current-turn"); + assert.equal(applyChatEvent(replay,{...compact("completed"),native_turn_id:"old-turn"},300),replay); + const ended=applyChatEvent(replay,{kind:"step",step:{status:"ended",turn_id:"current-turn"}},400); + assert.equal(ended.running,false); + assert.equal(ended.compaction,null); +});