Skip to content

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

fix(mcp): bound the session/get compaction history before truncating

joyawangde1e26b3b15d
diff --git a/apps/desktop/electron/main/mcp-control.ts b/apps/desktop/electron/main/mcp-control.ts
index 4f270d049..4c69e3c7d 100644
--- a/apps/desktop/electron/main/mcp-control.ts
+++ b/apps/desktop/electron/main/mcp-control.ts
@@ -570,7 +570,28 @@ const COMPACTION_SCALAR_KEYS = [
] as const;
/**
- * Bounds the `session/get` answer for the control plane (mocode #495).
+ * Keeps only the compact identity of one `ContextCompactionRecord`.
+ *
+ * `summary`, `retainedTail`, and `details.modifiedFiles` grow without bound and
+ * are not part of the tools contract, so they are dropped here.
+ */
+function projectCompactionRecord(value: unknown): unknown {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return value;
+ const source = value as Record<string, unknown>;
+ const bounded: Record<string, unknown> = {};
+ for (const key of COMPACTION_SCALAR_KEYS) {
+ if (source[key] !== undefined) bounded[key] = source[key];
+ }
+ const details = source.details;
+ if (details && typeof details === "object" && !Array.isArray(details)) {
+ const generation = (details as Record<string, unknown>).generation;
+ if (generation !== undefined) bounded.details = { generation };
+ }
+ return bounded;
+}
+
+/**
+ * Bounds the `session/get` answer for the control plane (mocode #495, #506).
*
* A durable session's `ContextCompactionRecord` (`summary` / `retainedTail` /
* `details.modifiedFiles`) grows without bound: on a long session it alone can
@@ -584,27 +605,39 @@ const COMPACTION_SCALAR_KEYS = [
* the retained tail, or the artifact list. Keep that whitelist and drop the
* rest, so the transcript survives bounding. Non-`session/get` shapes and
* sessions without a compaction record are returned untouched.
+ *
+ * `session.compaction` is only the NEWEST record; `session.compactions` is the
+ * unbounded history and every entry carries its own `summary` / `retainedTail` /
+ * `details.modifiedFiles`. Projecting the newest record alone was not enough:
+ * on a session compacted several times the history array alone still exceeded
+ * the limit, so the answer stayed a truncation envelope and shrinking the
+ * transcript page could not help (the overflow was independent of
+ * `messageLimit` / `contentLimit`). Project every entry in the history too.
*/
export function projectSessionGetResult(value: unknown): unknown {
if (!value || typeof value !== "object" || Array.isArray(value)) return value;
const root = value as Record<string, unknown>;
const session = root.session;
if (!session || typeof session !== "object" || Array.isArray(session)) return value;
- const compaction = (session as Record<string, unknown>).compaction;
- if (!compaction || typeof compaction !== "object" || Array.isArray(compaction)) return value;
+ const source = session as Record<string, unknown>;
- const source = compaction as Record<string, unknown>;
- const bounded: Record<string, unknown> = {};
- for (const key of COMPACTION_SCALAR_KEYS) {
- if (source[key] !== undefined) bounded[key] = source[key];
+ let projected: Record<string, unknown> | undefined;
+
+ const compaction = source.compaction;
+ if (compaction && typeof compaction === "object" && !Array.isArray(compaction)) {
+ projected = { ...source, compaction: projectCompactionRecord(compaction) };
}
- const details = source.details;
- if (details && typeof details === "object" && !Array.isArray(details)) {
- const generation = (details as Record<string, unknown>).generation;
- if (generation !== undefined) bounded.details = { generation };
+
+ const compactions = source.compactions;
+ if (Array.isArray(compactions)) {
+ projected = {
+ ...(projected ?? source),
+ compactions: compactions.map(projectCompactionRecord),
+ };
}
- return { ...root, session: { ...(session as Record<string, unknown>), compaction: bounded } };
+ if (!projected) return value;
+ return { ...root, session: projected };
}
function errorInfo(error: unknown): { code: string; message: string; details?: unknown } {
diff --git a/apps/desktop/test/mcp-control.test.mjs b/apps/desktop/test/mcp-control.test.mjs
index acb5e1813..921bbac2d 100644
--- a/apps/desktop/test/mcp-control.test.mjs
+++ b/apps/desktop/test/mcp-control.test.mjs
@@ -624,6 +624,87 @@ test("session/get compaction metadata is projected before bounding (mocode #495)
assert.equal(session.compaction.details.modifiedFiles, undefined);
});
+test("session/get compaction history is projected before bounding (mocode #506)", () => {
+ // The history array alone blows the limit even though the newest record is
+ // already projected and the transcript page is tiny: the phone could not open
+ // the session at ANY messageLimit/contentLimit, because the overflow was
+ // independent of the transcript page.
+ const huge = "y".repeat(200_000);
+ const historyEntry = (generation) => ({
+ id: `cp${generation}`,
+ throughMessageId: `m${generation}`,
+ tokensBefore: generation * 1000,
+ createdAt: `2026-09-2${generation}T00:00:00.000Z`,
+ summary: huge,
+ retainedTail: [{ content: huge }],
+ details: { generation, modifiedFiles: ["a", "b", "c"] },
+ providerId: "p1",
+ modelId: "deepseek/deepseek-v4.1-flash",
+ });
+ const messages = [{ id: "m1", role: "user", content: "hello" }];
+ const raw = {
+ session: {
+ id: "s1",
+ title: "Long session",
+ messageStart: 0,
+ hasMoreBefore: false,
+ compaction: {
+ id: "cp7",
+ createdAt: "2026-10-05T02:51:23.415Z",
+ details: { generation: 7 },
+ },
+ compactions: [historyEntry(1), historyEntry(2), historyEntry(3), historyEntry(4)],
+ messages,
+ },
+ };
+
+ const unprojected = boundMcpResult(raw);
+ assert.equal(unprojected.truncated, true, "the history array alone must exceed the limit");
+
+ const bounded = boundMcpResult(raw, projectSessionGetResult);
+ assert.notEqual(bounded.truncated, true, "projected answer must fit the limit");
+
+ const session = bounded.session;
+ assert.deepEqual(session.messages, messages, "messages must survive");
+ assert.equal(session.compaction.details.generation, 7, "newest record keeps its identity");
+ assert.equal(session.compactions.length, 4, "history length is preserved");
+ for (const entry of session.compactions) {
+ // The compact identity is kept ...
+ assert.equal(typeof entry.createdAt, "string");
+ assert.equal(typeof entry.details.generation, "number");
+ // ... and every entry's unbounded fields are dropped.
+ assert.equal(entry.summary, undefined);
+ assert.equal(entry.retainedTail, undefined);
+ assert.equal(entry.details.modifiedFiles, undefined);
+ }
+});
+
+test("session/get projection bounds a session with history but no newest record (mocode #506)", () => {
+ const huge = "z".repeat(700_000);
+ const raw = {
+ session: {
+ id: "s1",
+ compactions: [
+ {
+ id: "cp1",
+ createdAt: "2026-09-29T22:54:23.437Z",
+ summary: huge,
+ retainedTail: [huge],
+ details: { generation: 1, modifiedFiles: ["a"] },
+ },
+ ],
+ messages: [{ id: "m1", role: "user", content: "hello" }],
+ },
+ };
+
+ assert.equal(boundMcpResult(raw).truncated, true);
+
+ const bounded = boundMcpResult(raw, projectSessionGetResult);
+ assert.notEqual(bounded.truncated, true, "history-only sessions must still be projected");
+ assert.equal(bounded.session.compactions[0].summary, undefined);
+ assert.equal(bounded.session.compactions[0].details.generation, 1);
+});
+
test("session/get projection leaves a small session untouched (mocode #495)", () => {
const raw = {
session: {
diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.md
index 7a391ed54..9f550e223 100644
--- a/docs/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/spec/03-runtime/01-ipc-protocol.md
@@ -2295,13 +2295,17 @@ error model. Both the text payload and `structuredContent` are size-bounded to
replaced by `{truncated: true, reason: "MCP_RESULT_LIMIT", preview: "<the first
512 KiB of the JSON>"}`, so an external caller can never receive a silently
shortened payload. If an oversized answer comes from `session/get`
-(`pi_session_get`) and has a `compaction` record, Main projects that record to
-the compact identity (`createdAt` and `details.generation`) and checks the size
-again before returning the truncation envelope. This lets a long session's
-transcript survive when its unbounded `ContextCompactionRecord` (`summary` /
-`retainedTail` / `details.modifiedFiles`) alone caused the overflow. Results
-already under the limit retain their full compaction details, and the desktop's
-own session detail is unchanged.
+(`pi_session_get`) and carries a `compaction` record or a `compactions` history,
+Main projects each record to the compact identity (`createdAt` and
+`details.generation`) and checks the size again before returning the truncation
+envelope. This lets a long session's transcript survive when its unbounded
+`ContextCompactionRecord` (`summary` / `retainedTail` / `details.modifiedFiles`)
+alone caused the overflow — including the case where the newest `compaction` is
+already compact but the unbounded `compactions` history alone still exceeds the
+limit, which no `messageLimit` / `contentLimit` reduction can fix because the
+overflow is independent of the transcript page. Results already under the limit
+retain their full compaction details, and the desktop's own session detail is
+unchanged.
The six `session/collaboration/*` operations are first-party-plugin-only: they
require an authenticated plugin tool invocation context, so they appear in
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 62678b1d9..6e0531e6c 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -13633,23 +13633,31 @@ are withdrawn with ADR 0165.
- **Preconditions**: Start PI-Desktop with `PI_DESKTOP_MCP_CONTROL=1`. A durable
session exists whose `session.compaction` record (`summary` / `retainedTail` /
`details.modifiedFiles`) alone serializes to more than the 512 KiB MCP result
- limit.
+ limit. A second durable session exists whose `session.compactions` history
+ alone does — the newest `compaction` is already compact, but several history
+ entries each carry their own `summary` / `retainedTail` /
+ `details.modifiedFiles` (mocode #506).
- **Steps**: 1) Read `mcp-control.json`, use its URL and bearer token, and
complete the MCP handshake. 2) Call `pi_session_get` for that session with any
`messageLimit` / `contentLimit` / `messageBefore`. 3) Inspect
- `structuredContent`. 4) Repeat for a small session.
+ `structuredContent`. 4) Repeat for the history-heavy session with the smallest
+ page (`messageLimit: 1`, `contentLimit: 1`). 5) Repeat for a small session.
- **Expected**: The answer is not the `{truncated: true, reason:
"MCP_RESULT_LIMIT", preview}` envelope; `session.messages` carries the
requested transcript page; `session.compaction` keeps `createdAt` and
`details.generation` while `summary`, `retainedTail`, and
- `details.modifiedFiles` are absent. The small session's answer is unchanged.
+ `details.modifiedFiles` are absent. Every `session.compactions` entry keeps its
+ scalar identity and drops those same unbounded fields, so the history-heavy
+ session returns a real page even at `messageLimit: 1` / `contentLimit: 1`. The
+ small session's answer is unchanged.
- **Specs linked**: `03-runtime/01-ipc-protocol.md` §13d
- **Acceptance**: C (sessions), Quality
- **Milestone**: M6+
- **Status**: The local MCP server contract test in
`apps/desktop/test/mcp-control.test.mjs` exercises authenticated JSON-RPC
- `tools/call` for both oversized and under-limit `pi_session_get` results. The
- separate full Electron-to-Host journey remains release qualification.
+ `tools/call` for oversized (current record, compaction history, and
+ history-only) and under-limit `pi_session_get` results. The separate full
+ Electron-to-Host journey remains release qualification.
#### E2E-234: Workspace security denylist and ignore layers