fix(chat): preserve fresh compaction state across reconnect history
This commit is contained in:
@@ -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
|
Native context compaction is reported as `chat_event.kind="compaction"`, with
|
||||||
`compaction: {status: "running" | "completed" | "failed", id?: string}`.
|
`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
|
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
|
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.
|
running; completion clears that phase but does not itself end the model turn.
|
||||||
|
|||||||
+7
-1
@@ -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
|
surrounding model turn or count as a tool/message. Disconnect/turn settlement
|
||||||
clear stale activity. Reconnect clears stale state before subscribing, then keeps
|
clear stale activity. Reconnect clears stale state before subscribing, then keeps
|
||||||
fresh replayed activity while authoritative history loads.
|
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
|
`test/chat-compaction-browser.mjs` captures before-answer and with-history states
|
||||||
at 390/1100px plus cleared-on-disconnect. It checks polite status announcements,
|
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
|
approved OpenCode temporary `chat-compaction-captures/` directory. Fixtures do not
|
||||||
trigger compaction, inference or changes to real chats. A server update is needed
|
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.
|
for the new native activity frames; shell cache v11 refreshes the browser modules.
|
||||||
|
|||||||
+11
-4
@@ -1219,7 +1219,7 @@ export const EVENT_RESYNC = "resync";
|
|||||||
/** ChatStep.Status values. `ended` is the one status that settles a turn. */
|
/** ChatStep.Status values. `ended` is the one status that settles a turn. */
|
||||||
export const STEP_ENDED = "ended";
|
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_THINKING = "thinking";
|
||||||
export const TURN_PHASE_TOOL = "tool";
|
export const TURN_PHASE_TOOL = "tool";
|
||||||
export const TURN_PHASE_WAITING = "waiting";
|
export const TURN_PHASE_WAITING = "waiting";
|
||||||
@@ -1397,6 +1397,7 @@ export function newChatThread(sessionId = "") {
|
|||||||
loading: false,
|
loading: false,
|
||||||
error: "",
|
error: "",
|
||||||
running: false,
|
running: false,
|
||||||
|
nativeTurnId: "",
|
||||||
runningSince: 0,
|
runningSince: 0,
|
||||||
compaction: null,
|
compaction: null,
|
||||||
toolStartedAt: {},
|
toolStartedAt: {},
|
||||||
@@ -1432,6 +1433,7 @@ export function settledThread(thread) {
|
|||||||
return {
|
return {
|
||||||
...(thread ?? {}),
|
...(thread ?? {}),
|
||||||
running: false,
|
running: false,
|
||||||
|
nativeTurnId: "",
|
||||||
runningSince: 0,
|
runningSince: 0,
|
||||||
compaction: null,
|
compaction: null,
|
||||||
toolStartedAt: {},
|
toolStartedAt: {},
|
||||||
@@ -1607,7 +1609,8 @@ export function applyChatForm(thread, form) {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Applies one pushed `chat_event` frame to a conversation and returns the next
|
* 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
|
* 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
|
* 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
|
* 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;
|
if (current.sessionId && frame.session_id !== current.sessionId) return current;
|
||||||
const incoming = frame.compaction;
|
const incoming = frame.compaction;
|
||||||
if (!incoming || !["running", "completed", "failed"].includes(incoming.status)) return current;
|
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") {
|
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;
|
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
|
// 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
|
* 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
|
* 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) {
|
export function queuedAfterFrame(queued, frame) {
|
||||||
if (frame == null || frame.kind === EVENT_COMPACTION) return queued === true;
|
if (frame == null || frame.kind === EVENT_COMPACTION) return queued === true;
|
||||||
|
|||||||
@@ -1025,7 +1025,7 @@ async function resyncOpenChat() {
|
|||||||
const page = await repo.chatHistory(id);
|
const page = await repo.chatHistory(id);
|
||||||
state.chatThreads.set(id, historyResync(state.chatThreads.get(id), page, { preserveActivity: true }));
|
state.chatThreads.set(id, historyResync(state.chatThreads.get(id), page, { preserveActivity: true }));
|
||||||
} catch {
|
} 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);
|
await loadChatShells(id);
|
||||||
renderContent();
|
renderContent();
|
||||||
@@ -1382,6 +1382,9 @@ function refreshChatComposerState(sessionId) {
|
|||||||
function onChatFrame(message) {
|
function onChatFrame(message) {
|
||||||
const frame = message?.chat_event;
|
const frame = message?.chat_event;
|
||||||
if (!frame || !frame.session_id) return;
|
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");
|
rt.touchView?.("chat");
|
||||||
const sessionId = frame.session_id;
|
const sessionId = frame.session_id;
|
||||||
const thread = state.chatThreads.get(sessionId);
|
const thread = state.chatThreads.get(sessionId);
|
||||||
@@ -4330,7 +4333,8 @@ function updateChatIndicator(now) {
|
|||||||
}
|
}
|
||||||
const phase = [...document.querySelectorAll("#chatTranscript .chat-activity-phase")].at(-1);
|
const phase = [...document.querySelectorAll("#chatTranscript .chat-activity-phase")].at(-1);
|
||||||
if (phase) {
|
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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -16,8 +16,9 @@ ${["design/tokens/tokens","base","shell","lists","run-detail","chat","dialogs"].
|
|||||||
import { createChatView } from '/src/views/chat.js';
|
import { createChatView } from '/src/views/chat.js';
|
||||||
import { newChatThread, applyChatEvent, resumedThread } from '/src/chat.js';
|
import { newChatThread, applyChatEvent, resumedThread } from '/src/chat.js';
|
||||||
const id='scratch';
|
const id='scratch';
|
||||||
const state={view:'chat',chatActiveId:id,chatSessions:[{id,title:'Context compaction',backend:'opencode'}],chatOverrides:{},chatDrafts:{},chatThreads:new Map()};
|
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 rt={state,repo:{},renderContent:()=>paint(),closeDetail:()=>{}};
|
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);
|
const view=createChatView(rt);
|
||||||
window.paint=()=>document.querySelector('#content').replaceChildren(view.renderChatConversation());
|
window.paint=()=>document.querySelector('#content').replaceChildren(view.renderChatConversation());
|
||||||
window.setup=(history)=>{
|
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.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.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.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;
|
window.messageCount=()=>state.chatThreads.get(id).messages.length;
|
||||||
setup(true);
|
setup(true);
|
||||||
</script>`;
|
</script>`;
|
||||||
@@ -64,5 +66,8 @@ try {
|
|||||||
await page.evaluate("setup(true);event('running');drop()");
|
await page.evaluate("setup(true);event('running');drop()");
|
||||||
assert.equal(await page.evaluate("document.querySelectorAll('.chat-compaction-status').length"),0);
|
assert.equal(await page.evaluate("document.querySelectorAll('.chat-compaction-status').length"),0);
|
||||||
await page.screenshot(resolve(out,"compaction-clears-on-disconnect.png"));
|
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));}
|
} finally {await browser?.close();await new Promise(r=>server.close(r));}
|
||||||
|
|||||||
@@ -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.deepEqual(synced.messages,[{id:"native-history",role:"user",parts:[]}]);
|
||||||
assert.equal(historyResync(reset,{messages:[]},{preserveActivity:true}).compaction,null);
|
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);
|
||||||
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user