Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(agent-runtime): resume active turns from the compaction checkpoint

Kurt Jensenec590a1f7473
diff --git a/packages/agent-runtime/src/pi-runtime-messages.ts b/packages/agent-runtime/src/pi-runtime-messages.ts
index e4a96b737..37981eb99 100644
--- a/packages/agent-runtime/src/pi-runtime-messages.ts
+++ b/packages/agent-runtime/src/pi-runtime-messages.ts
@@ -6,6 +6,7 @@ import { omitOversizedImages } from "./image-admission.js";
export type CompactionSummaryMessage = {
role: "compactionSummary";
summary: string;
+ resumeActiveTurn?: true;
tokensBefore: number;
timestamp: number;
};
@@ -44,6 +45,10 @@ type RuntimeMessage =
export const COMPACTION_SUMMARY_PREFIX =
"The conversation history before this point was compacted into the following summary:\n\n<summary>\n";
+const ACTIVE_TURN_SUMMARY_PREFIX =
+ "This harness-generated checkpoint is newer than the original request above. " +
+ "That request defines the goal, not the current state. Continue from the first unchecked step below; " +
+ "do not restart completed work. Follow any newer user message that comes after this checkpoint.\n\n<summary>\n";
export const COMPACTION_SUMMARY_SUFFIX = "\n</summary>";
export const BRANCH_SUMMARY_PREFIX =
"The following is a summary of a branch that this conversation came back from:\n\n<summary>\n";
@@ -57,10 +62,12 @@ export function createCompactionSummaryMessage(
summary: string,
tokensBefore: number,
timestamp: string | number,
+ resumeActiveTurn = false,
): CompactionSummaryMessage {
return {
role: "compactionSummary",
summary,
+ ...(resumeActiveTurn ? { resumeActiveTurn: true } : {}),
tokensBefore,
timestamp: normalizeTimestamp(timestamp),
};
@@ -126,16 +133,19 @@ export function convertToLlm(messages: AgentMessage[]): Message[] {
timestamp: runtimeMessage.timestamp,
}));
break;
- case "compactionSummary":
+ case "compactionSummary": {
+ const prefix = "resumeActiveTurn" in runtimeMessage && runtimeMessage.resumeActiveTurn
+ ? ACTIVE_TURN_SUMMARY_PREFIX : COMPACTION_SUMMARY_PREFIX;
converted.push(asProviderMessage({
role: "user",
content: [{
type: "text",
- text: `${COMPACTION_SUMMARY_PREFIX}${runtimeMessage.summary}${COMPACTION_SUMMARY_SUFFIX}`,
+ text: `${prefix}${runtimeMessage.summary}${COMPACTION_SUMMARY_SUFFIX}`,
}],
timestamp: runtimeMessage.timestamp,
}));
break;
+ }
case "system":
case "user":
case "assistant":
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.ts
index 6b5a94437..e1ea3b113 100644
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@ -8374,8 +8374,8 @@ describe("DesktopAgentRuntime per-turn context protection", () => {
(runtime as any).entriesWithCompaction(checkpoint),
).messages;
expect(compacted.map((message: any) => message.role)).toEqual([
- "compactionSummary",
"user",
+ "compactionSummary",
]);
// No assistant message means no toolCall block, so no orphaned tool call can
// reach a provider.
diff --git a/packages/agent-runtime/src/session-context.test.ts b/packages/agent-runtime/src/session-context.test.ts
index 618928123..3cf8b4bba 100644
--- a/packages/agent-runtime/src/session-context.test.ts
+++ b/packages/agent-runtime/src/session-context.test.ts
@@ -3,6 +3,7 @@ import type {
AgentMessage,
} from "@earendil-works/pi-agent-core";
import type { CompactionEntry, MessageEntry } from "./pi-runtime-types.js";
+import { convertToLlm } from "./pi-runtime-messages.js";
import { buildSessionContext } from "./session-context.js";
function user(id: string, text: string, seq: number): MessageEntry {
@@ -114,11 +115,48 @@ describe("buildSessionContext", () => {
expect(JSON.stringify(messages)).not.toContain("old answer");
});
+ it("sends the active request before the checkpoint and a new user message after it", () => {
+ const original = user("u1", "This is an empty project", 1);
+ const entry = compaction("c1", 3, [original.message]);
+ entry.summary = "Setup is complete. Verify the homepage.";
+ entry.details = { retainedTailMode: "active_turn" };
+
+ const resumed = convertToLlm(buildSessionContext([original, entry]).messages);
+ expect(resumed.map((message) => message.role)).toEqual(["user", "user"]);
+ expect(resumed[0]).toMatchObject({ content: "This is an empty project" });
+ expect(resumed[1]).toMatchObject({
+ content: [{ type: "text", text: expect.stringContaining(
+ "checkpoint is newer than the original request above",
+ ) }],
+ });
+ expect(JSON.stringify(resumed[1])).toContain(entry.summary);
+
+ const saved = JSON.parse(JSON.stringify(entry)) as CompactionEntry;
+ const next = user("u2", "Change direction", 4);
+ const reopened = convertToLlm(buildSessionContext([original, saved, next]).messages);
+ expect(reopened.slice(0, 2)).toEqual(resumed);
+ expect(reopened[2]).toMatchObject({ role: "user", content: "Change direction" });
+ });
+
+ it("does not add resume framing to completed or empty checkpoints", () => {
+ const completed = compaction("c1", 2);
+ completed.details = { retainedTailMode: "completed_turn" };
+ const empty = compaction("c2", 3, [user("u1", "original", 1).message]);
+ empty.details = { retainedTailMode: "active_turn" };
+ empty.summary = "";
+ for (const entry of [completed, empty]) {
+ const request = convertToLlm(buildSessionContext([entry]).messages);
+ expect(JSON.stringify(request)).not.toContain("checkpoint is newer");
+ expect(JSON.stringify(request[0])).toContain("was compacted into the following summary");
+ }
+ });
+
it("replays retained reasoning between the summary and the user tail", () => {
// #296
const keptUser = user("u2", "keep me", 3).message;
const entry = compaction("c1", 2, [keptUser]);
entry.details = {
+ retainedTailMode: "active_turn",
retainedReasoning: [{ thinking: "prior plan", text: "prior answer" }],
};
const messages = buildSessionContext([
diff --git a/packages/agent-runtime/src/session-context.ts b/packages/agent-runtime/src/session-context.ts
index 0036efa44..08ecade9e 100644
--- a/packages/agent-runtime/src/session-context.ts
+++ b/packages/agent-runtime/src/session-context.ts
@@ -7,10 +7,9 @@ import { recoverMalformedToolCalls } from "./tool-call-recovery.js";
* desktop-only entries and persisted host checkpoints. It keeps the
* `{ messages }` shape consumed by the agent loop.
*
- * The slice-from-latest-compaction and compactionSummary-before-retainedTail
- * order preserve the behavior D203 depends on. Retained
- * reasoning turns (#296) sit between the summary and the user tail so strict
- * DeepSeek relays still see real thinking without replaying tool-call pairs.
+ * An active-turn summary follows the original request so the model resumes
+ * from the checkpoint rather than treating that request as new. Preserve the
+ * existing order when replaying provider-specific reasoning turns (#296).
*/
import type { AgentMessage } from "@earendil-works/pi-agent-core";
@@ -58,25 +57,28 @@ export function sessionEntryToContextMessages(
switch (entry.type) {
case "message":
return isContextMessage(entry.message) ? [entry.message] : [];
- case "compaction":
- return [
- ...(entry.details && typeof entry.details === "object" && "systemMessageJson" in entry.details
- ? [readSystemMessage(entry.details.systemMessageJson)] : []),
- createCompactionSummaryMessage(
- entry.summary,
- entry.tokensBefore,
- entry.timestamp,
- ),
- ...(identity?.requiresCompletionsReasoningReplay === false
- ? []
- : retainedReasoningToMessages(
- retainedReasoningFromDetails(entry.details),
- entry.timestamp,
- identity,
- )),
- ...entry.retainedTail.filter((message) => isContextMessage(message) &&
- !(message.role === "system" && entry.details && typeof entry.details === "object" && "systemMessageJson" in entry.details)),
- ];
+ case "compaction": {
+ const details = entry.details;
+ const system = details && typeof details === "object" && "systemMessageJson" in details
+ ? [readSystemMessage(details.systemMessageJson)] : [];
+ const reasoning = identity?.requiresCompletionsReasoningReplay === false
+ ? []
+ : retainedReasoningToMessages(
+ retainedReasoningFromDetails(details), entry.timestamp, identity,
+ );
+ const tail = entry.retainedTail.filter((message) => isContextMessage(message) &&
+ !(message.role === "system" && system.length > 0));
+ const resume = details && typeof details === "object" &&
+ "retainedTailMode" in details && details.retainedTailMode === "active_turn" &&
+ entry.summary.trim().length > 0 && reasoning.length === 0 &&
+ tail.length === 1 && tail[0]?.role === "user";
+ const summary = createCompactionSummaryMessage(
+ entry.summary, entry.tokensBefore, entry.timestamp, Boolean(resume),
+ );
+ return resume
+ ? [...system, ...tail, summary]
+ : [...system, summary, ...reasoning, ...tail];
+ }
case "branch_summary":
return entry.summary
? [