Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: no retry after a stopped compaction

Samrat Talukdar067d483c12c5
diff --git a/apps/app/src/app/lib/good-session.ts b/apps/app/src/app/lib/good-session.ts
index 1e740aac..3e2c32e8 100644
--- a/apps/app/src/app/lib/good-session.ts
+++ b/apps/app/src/app/lib/good-session.ts
@@ -849,6 +849,14 @@ function lastTurnEnd(messages: readonly UIMessage[]): TurnEnding {
const turn = messages.slice(start).filter((message) => message.role === "assistant");
const last = turn.at(-1);
if (!last) return { ended: "none", endedAt: null, retryable: false };
+ // A compaction (its request or summary, also one being stopped) is no agent turn: never retried.
+ const request = start > 0 ? messages[start - 1] : undefined;
+ const compaction = (request && messageOpencode(request).compaction === true) || turn.some((message) => messageOpencode(message).compaction === true);
+ const ending = turnEndOf(turn, last);
+ return compaction ? { ...ending, retryable: false } : ending;
+}
+
+function turnEndOf(turn: readonly UIMessage[], last: UIMessage): TurnEnding {
const completed = messageOpencode(last).completed;
const endedAt = typeof completed === "number" ? completed : null;
const error = sessionErrorOf(last);
diff --git a/apps/app/src/react-app/domains/session/sync/session-sync.ts b/apps/app/src/react-app/domains/session/sync/session-sync.ts
index e7f27970..72ab1f91 100644
--- a/apps/app/src/react-app/domains/session/sync/session-sync.ts
+++ b/apps/app/src/react-app/domains/session/sync/session-sync.ts
@@ -16,6 +16,7 @@ import { SYNTHETIC_SESSION_ERROR_MESSAGE_PREFIX, type OpencodeEvent, type Pendin
import {
attachmentNoteToUIParts,
createSessionErrorUIMessage,
+ isCompactionInfo,
snapshotToUIMessages,
} from "./usechat-adapter";
import {
@@ -1121,11 +1122,13 @@ function applyEvent(entry: SyncEntry, workspaceId: string, event: OpencodeEvent)
if (!isTrackedSession(entry, info.sessionID)) return;
const created = info.time?.created;
const completed = info.time?.completed;
+ // A compaction's summary (the auto-retry never answers one: good-session.ts).
+ const compaction = isCompactionInfo(info);
const next = {
id: info.id,
role: info.role,
...(typeof created === "number"
- ? { metadata: { opencode: { created, ...(typeof completed === "number" ? { completed } : {}) } } }
+ ? { metadata: { opencode: { created, ...(typeof completed === "number" ? { completed } : {}), ...(compaction ? { compaction } : {}) } } }
: {}),
parts: [],
} satisfies UIMessage;
diff --git a/apps/app/src/react-app/domains/session/sync/usechat-adapter.ts b/apps/app/src/react-app/domains/session/sync/usechat-adapter.ts
index 18a5df65..3b116b92 100644
--- a/apps/app/src/react-app/domains/session/sync/usechat-adapter.ts
+++ b/apps/app/src/react-app/domains/session/sync/usechat-adapter.ts
@@ -141,6 +141,13 @@ export function attachmentNoteToUIParts(part: TextPart): UIMessage["parts"] {
});
}
+/** An assistant message that is a compaction's summary (the engine's compaction agent). */
+export function isCompactionInfo(info: unknown): boolean {
+ if (!info || typeof info !== "object") return false;
+ const value = info as { role?: unknown; summary?: unknown; mode?: unknown; agent?: unknown };
+ return value.role === "assistant" && (value.summary === true || value.mode === "compaction" || value.agent === "compaction");
+}
+
export function snapshotToUIMessages(snapshot: OmniRushSessionSnapshot): UIMessage[] {
return snapshot.messages.flatMap((message) => {
const created = message.info.time?.created;
@@ -148,11 +155,13 @@ export function snapshotToUIMessages(snapshot: OmniRushSessionSnapshot): UIMessa
const completed = time && "completed" in time ? time.completed : undefined;
// The engine's finish reason ("stop", "length", "tool-calls", ...): the Good session checklist reads it.
const finish = message.info.role === "assistant" ? message.info.finish : undefined;
+ // A compaction's request or summary (the auto-retry never answers one: good-session.ts).
+ const compaction = isCompactionInfo(message.info) || (message.info.role === "user" && message.parts.some((part) => part.type === "compaction"));
const uiMessage = {
id: message.info.id,
role: message.info.role,
...(typeof created === "number"
- ? { metadata: { opencode: { created, ...(typeof completed === "number" ? { completed } : {}), ...(finish ? { finish } : {}) } } }
+ ? { metadata: { opencode: { created, ...(typeof completed === "number" ? { completed } : {}), ...(finish ? { finish } : {}), ...(compaction ? { compaction } : {}) } } }
: {}),
parts: message.parts.flatMap<UIMessage["parts"][number]>((part) => {
if (part.type === "text") {
diff --git a/apps/app/tests/good-session.test.tsx b/apps/app/tests/good-session.test.tsx
index 2eec47f5..5542724a 100644
--- a/apps/app/tests/good-session.test.tsx
+++ b/apps/app/tests/good-session.test.tsx
@@ -573,6 +573,16 @@ describe("how the last turn ended (session_qc._completion)", () => {
expect(messageFacts([prompt(), assistant("a1", [tool("bash", { command: "npm test" })], { finish: "tool-calls" }), assistant("a2", [{ type: "text", text: "Done." }], { finish: "stop" })]).ended).toBe("pass");
});
+ test("a compaction's request or summary is never retried, also one being stopped (no closed summary yet)", () => {
+ // The summary of a compaction the person stops: no text, not closed yet, read as a cut-off step.
+ const stopping = [prompt(), assistant("a", [{ type: "text", text: "Done." }], { finish: "stop" }), { id: "c", role: "user", metadata: { opencode: { compaction: true } }, parts: [] } as UIMessage, assistant("s", [], { compaction: true })];
+ expect(messageFacts(stopping).retryable).toBe(false);
+ const request = [prompt(), { id: "c", role: "user", metadata: { opencode: { compaction: true } }, parts: [] } as UIMessage, assistant("s", [tool("bash", { command: "x" }, "input-streaming")])];
+ expect(messageFacts(request).retryable).toBe(false);
+ // The same cut-off step after a prompt someone sent is retryable.
+ expect(messageFacts([prompt(), assistant("s", [tool("bash", { command: "x" }, "input-streaming")])]).retryable).toBe(true);
+ });
+
test("the Stop button and gateway errors are excused; other errors cut; no answer yet is none", () => {
expect(messageFacts([prompt(), errorMessage({ kind: "aborted", title: "Task interrupted", technicalDetails: "Error type: MessageAbortedError" })]).ended).toBe("stopped");
expect(messageFacts([prompt(), errorMessage({ kind: "generic", title: "Bad gateway", technicalDetails: "Error type: APIError\nStatus: 502" })]).ended).toBe("gateway");
diff --git a/apps/server/src/session-archive/PARITY.sha256 b/apps/server/src/session-archive/PARITY.sha256
index 7ac92929..984cc0c1 100644
--- a/apps/server/src/session-archive/PARITY.sha256
+++ b/apps/server/src/session-archive/PARITY.sha256
@@ -1,6 +1,6 @@
# Session-archive modules that are the same files in omnirush-cli (assets/extensions/omnirush/capture/session-archive/)
# and omnirush-gui (apps/server/src/session-archive/). A change to one must be ported to the other and this list updated in both.
-5e4f36aa539098e179edcadae2284a7698ed4efb9cd3a91e69f9000c0d839353 auto-compact.ts
+c7f2e9a9c126ea9dfef714d36385e611e2190b0af8043cd52368a08bd0590af5 auto-compact.ts
8fd84683b5542236f0c88750e3d9bd756e15a304d263141b57998b17c4a1ab9c late-writes.ts
4d9a13a5df136cd6e13d0aeb67983249ca4a6913b66c5a8f768daa63da511dda tool-start.ts
38dc65a461de6905134c22837f5230d03383ec0bdd6df35090dd269160446edf turn-overlap.ts
diff --git a/apps/server/src/session-archive/auto-compact.test.ts b/apps/server/src/session-archive/auto-compact.test.ts
index 3a8e9b98..3d37d031 100644
--- a/apps/server/src/session-archive/auto-compact.test.ts
+++ b/apps/server/src/session-archive/auto-compact.test.ts
@@ -92,6 +92,26 @@ describe("auto compaction", () => {
expect(removed).toEqual(["s1", "c1"]);
expect(compactor.count("s")).toBe(1);
});
+
+ test("the grace runs out before the engine closed the stopped summary: still broken, removed", async () => {
+ let list: unknown[] = chat(3);
+ const removed: string[] = [];
+ const unclosed = { info: { id: "s1", parentID: "c1", role: "assistant", summary: true, mode: "compaction", agent: "compaction", time: { created: 401 } }, parts: [] };
+ const engine: AutoCompactEngine = {
+ messages: async () => list,
+ session: async () => ({ id: "ses" }),
+ busy: async () => false,
+ summarize: (_model, signal) => new Promise<void>((_resolve, reject) => signal.addEventListener("abort", () => reject(signal.reason))),
+ removeMessage: async (id) => { removed.push(id); },
+ };
+ const compactor = new AutoCompactor({ policy: async () => ({ enabled: true, afterTurns: 3, minContextTokens: 0 }), stopGraceMs: 20 });
+ const held = compactor.beforePrompt("s", engine, { model: MODEL });
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ list = [...chat(3), compactRequest("c1", 400), unclosed];
+ compactor.stopped("s");
+ expect((await held).action).toBe("failed");
+ expect(removed).toEqual(["s1", "c1"]);
+ });
});
describe("the desktop's glue", () => {
diff --git a/apps/server/src/session-archive/auto-compact.ts b/apps/server/src/session-archive/auto-compact.ts
index 9db24e80..4c4ebca7 100644
--- a/apps/server/src/session-archive/auto-compact.ts
+++ b/apps/server/src/session-archive/auto-compact.ts
@@ -233,9 +233,10 @@ export type CompactionResult = {
/**
* How the compaction that just ran ended, from the chat's messages read
* after it: its summary is the newest one not in `before` (the ids seen
- * before it started).
+ * before it started). `cut`: our wait for it ended early (stopped, timed
+ * out, failed), so a summary the engine never closed is broken too.
*/
-export function compactionResult(messages: unknown, before: Set<string>): CompactionResult {
+export function compactionResult(messages: unknown, before: Set<string>, options: { cut?: boolean } = {}): CompactionResult {
if (!Array.isArray(messages)) return { state: "none", leftovers: [] };
for (let index = messages.length - 1; index >= 0; index -= 1) {
const message = messages[index];
@@ -243,8 +244,9 @@ export function compactionResult(messages: unknown, before: Set<string>): Compac
const id = idOf(message);
if (!id || before.has(id)) return { state: "none", leftovers: [] };
const info = infoOf(message as Json);
- if (info.error == null) return { state: "summarized", leftovers: [] };
- const error = isRecord(info.error) && typeof info.error.name === "string" ? info.error.name : "error";
+ const closed = isRecord(info.time) && typeof info.time.completed === "number";
+ if (info.error == null && (closed || !options.cut)) return { state: "summarized", leftovers: [] };
+ const error = info.error == null ? "unfinished" : isRecord(info.error) && typeof info.error.name === "string" ? info.error.name : "error";
const leftovers = [id];
const parentID = typeof info.parentID === "string" ? info.parentID : null;
const request = parentID ? messages.find((entry) => idOf(entry) === parentID) : undefined;
@@ -331,6 +333,15 @@ export class AutoCompactor {
return run;
}
+ /** Waits (at most `ms`) until the engine runs nothing for the chat. */
+ private async idle(engine: AutoCompactEngine, ms: number): Promise<void> {
+ const until = Date.now() + ms;
+ while (Date.now() < until) {
+ if (await engine.busy().catch(() => null) === false) return;
+ await new Promise((resolve) => { const timer = setTimeout(resolve, Math.min(250, Math.max(0, until - Date.now()))); (timer as { unref?: () => void }).unref?.(); });
+ }
+ }
+
/** Removes a broken compaction's summary and request; resolves how many went. */
private async removeLeftovers(engine: AutoCompactEngine, ids: string[]): Promise<number> {
if (!engine.removeMessage || ids.length === 0) return 0;
@@ -440,8 +451,10 @@ export class AutoCompactor {
() => null,
(error: unknown) => error ?? new Error("summarize failed"),
).then(async (failure) => {
+ // Our wait ended early: give the engine a moment to finish stopping, so its summary is closed before it is read.
+ if (failure !== null) await this.idle(engine, this.options.stopGraceMs ?? STOP_GRACE_MS);
// Summarize answers once the engine is done, also when it was stopped: the chat says how it ended.
- const result = compactionResult(await engine.messages().catch(() => null), before);
+ const result = compactionResult(await engine.messages().catch(() => null), before, { cut: failure !== null || stoppedByPerson });
if (failure === null && result.state !== "broken") {
this.log("info", "auto compaction finished", { sessionId, elapsed_ms: Date.now() - started });
this.notify(sessionId, "finished");