Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(server,web): memory update cards survive a paginated conversation (#1138)

lmlihengda2ef18a438b
diff --git a/changelog/unreleased/2026-10-14-memory-updates-pagination.md b/changelog/unreleased/2026-10-14-memory-updates-pagination.md
new file mode 100644
index 00000000..fa9370d4
--- /dev/null
+++ b/changelog/unreleased/2026-10-14-memory-updates-pagination.md
@@ -0,0 +1,20 @@
+# Memory update cards survive a paginated conversation
+
+- **Date:** 2026-10-14
+- **Type:** fix
+- **Scope:** `server`, `web`
+
+[中文版](2026-10-14-memory-updates-pagination.zh.md)
+
+Ported from upstream PenguinHarness (#1138, commit `d51c4577`).
+
+Opening a long conversation could hide its memory update cards even though the file edits behind them
+had succeeded. A history window can start after the `session_meta` record — the one that carries the
+Agent State directory — so the stream model had no `<agent_state>/memory/` root to classify memory
+paths against.
+
+The history page envelope now carries the directory recorded by the context the window starts in,
+and the stream controller seeds it before replaying the window. Cards come back when the
+conversation is opened, when older messages are loaded and after a reconnect; repeated edits to one
+topic still draw a single row, and edits to the memory index stay excluded. No OmniMessage field
+was added, and neither stored traces nor memory files are rewritten.
diff --git a/changelog/unreleased/2026-10-14-memory-updates-pagination.zh.md b/changelog/unreleased/2026-10-14-memory-updates-pagination.zh.md
new file mode 100644
index 00000000..128c30e5
--- /dev/null
+++ b/changelog/unreleased/2026-10-14-memory-updates-pagination.zh.md
@@ -0,0 +1,17 @@
+# 会话分页读取时,记忆更新卡片不再丢失
+
+- **Date:** 2026-10-14
+- **Type:** fix
+- **Scope:** `server`, `web`
+
+[English](2026-10-14-memory-updates-pagination.md)
+
+移植自上游 PenguinHarness(#1138,提交 `d51c4577`)。
+
+打开一条很长的会话时,记忆更新卡片可能整块不见,尽管它对应的文件其实已经改成功了。原因是:历史窗口可能
+从 `session_meta` 那条记录**之后**开始,而 Agent State 目录正是那条记录带着的 —— 于是流模型手里没有
+`<agent_state>/memory/` 这个根,认不出哪些文件写入属于记忆。
+
+现在历史分页的信封里带上「窗口起始那个上下文记录下来的」Agent State 目录,流控制器在回放这一页之前先把它
+填进去。打开会话、往上加载更早的消息、断开后重连,三种情形下卡片都回来了;同一个话题被反复编辑仍只画一行,
+对记忆索引的编辑照旧不算。没有给 OmniMessage 增加字段,也没有改写已存的 Trace 或记忆文件。
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index b625cc52..c0bc2ff2 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -2235,6 +2235,11 @@ export interface MessagesPageInfo {
* window is told from a plain rotation. Absent when the Session has no Trace yet.
*/
contextModel?: ModelRefDto;
+ /**
+ * Agent State directory recorded by the starting context's `session_meta`. Seeds memory
+ * change detection when that record falls before the window. Absent without a Trace.
+ */
+ agentState?: string;
}
/** Message history: the full messages and events from concatenating all of this Session's Trace files in order (excludes partial_*). */
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index fcedf6a5..bcff3ba3 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -1016,6 +1016,7 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
contextTokens: result.prior.contextTokens,
},
...(result.contextModel !== undefined ? { contextModel: result.contextModel } : {}),
+ ...(result.agentState !== undefined ? { agentState: result.agentState } : {}),
};
// Images by reference, after the held inputs were merged: the dedup compares raw
// envelopes, and a held input carries its image inline exactly as its Trace copy does.
diff --git a/packages/server/src/services/trace-service.ts b/packages/server/src/services/trace-service.ts
index 65325aca..404b477a 100644
--- a/packages/server/src/services/trace-service.ts
+++ b/packages/server/src/services/trace-service.ts
@@ -195,6 +195,8 @@ export interface MessagesPageResult {
* one does not hold that record. Absent for an empty transcript.
*/
contextModel?: { provider: string; modelId: string };
+ /** Agent State directory from the same context's metadata, for memory-change detection. */
+ agentState?: string;
}
export interface ForkTraceResult {
@@ -711,6 +713,7 @@ export class TraceService implements Traces {
provider: startMeta.payload.provider,
modelId: startMeta.payload.model_id,
},
+ agentState: startMeta.payload.agent_state,
}
: {}),
};
diff --git a/packages/server/test/messages-live.test.ts b/packages/server/test/messages-live.test.ts
index 8fe235d0..17e48329 100644
--- a/packages/server/test/messages-live.test.ts
+++ b/packages/server/test/messages-live.test.ts
@@ -9,6 +9,8 @@
* - Windowed reads carry `live` on tail pages with the same content, never on `before` pages.
* - A read without paging parameters is byte-identical to the transcript alone, and malformed
* paging parameters are refused.
+ * - Given memory metadata before the requested window, tail and older pages carry its directory
+ * without inserting extra records; an empty transcript leaves the directory absent.
*/
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import {
@@ -18,6 +20,7 @@ import {
partialThinking,
partialToolCallOutput,
requestBegin,
+ sessionMeta,
toolCall,
toolCallOutput,
userText,
@@ -28,7 +31,7 @@ import type { MessagesResponse } from "../src/api/types.js";
import type { SessionRow } from "../src/db/repos/sessions.js";
import type { RuntimeSession } from "../src/runtime/session-manager.js";
import { fakeSession, sessionRow, uniqueSessionId } from "./fixtures/session.js";
-import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";
+import { apiClient, createTestApp, provisionUser, waitFor, writeTraceFile } from "./helpers.js";
import type { TestApp } from "./helpers.js";
/**
@@ -91,6 +94,44 @@ describe("messages live tail", () => {
const body = await getMessages();
expect(body.messages).toEqual([]);
expect(body.live).toBeUndefined();
+ const tail = await getMessages("?tailLimit=1");
+ expect(tail.messages).toEqual([]);
+ expect(tail.page?.agentState).toBeUndefined();
+ });
+
+ it("tail and older pages preserve the recorded memory directory without adding metadata to their messages", async () => {
+ const agentState = "/recorded/agents/memory-agent/agent_state";
+ await writeTraceFile(t.root, row.projectId, row.agentId, "2026-10-14", SID, 1, [
+ sessionMeta({
+ session_id: SID,
+ provider: "custom",
+ model_id: "memory-model",
+ model_context_window: 1000,
+ system_prompt: "",
+ agent_state: agentState,
+ workspace: row.workspace,
+ source: "user",
+ }),
+ userText("first"),
+ assistantText("first answer"),
+ userText("second"),
+ assistantText("second answer"),
+ userText("third"),
+ assistantText("third answer"),
+ ]);
+
+ const tail = await getMessages("?tailLimit=1");
+ expect(tail.page?.agentState).toBe(agentState);
+ expect(tail.messages.some((message) => message.type === "session_meta")).toBe(false);
+ const older = await getMessages(`?before=${tail.page!.before!}&limit=1`);
+ expect(older.page?.agentState).toBe(agentState);
+ expect(older.messages.some((message) => message.type === "session_meta")).toBe(false);
+ const first = await getMessages(`?before=${older.page!.before!}&limit=1`);
+ expect(first.page?.before).toBeUndefined();
+ expect(first.page?.agentState).toBe(agentState);
+ expect([...first.messages, ...older.messages, ...tail.messages]).toEqual(
+ (await getMessages()).messages,
+ );
});
it("while running: `live` carries the cursor and one synthetic start per open fragment (origin preserved); it disappears once the run ends", async () => {
diff --git a/packages/web/src/lib/omni/stream-controller.ts b/packages/web/src/lib/omni/stream-controller.ts
index d3635d34..a32bc83b 100644
--- a/packages/web/src/lib/omni/stream-controller.ts
+++ b/packages/web/src/lib/omni/stream-controller.ts
@@ -428,14 +428,15 @@ export function createStreamController(deps: StreamControllerDeps): StreamContro
/**
* Seeds a model with what came before the window it is about to take: the stats accrued
* ahead of it, so header chips and per-turn cumulative rows equal a full load (see
- * seedPriorStats), and the model its first context runs on, whose `session_meta` a window
- * that starts partway into that context does not hold.
+ * seedPriorStats), the model its first context runs on, and the Agent State directory for
+ * memory-change detection. Their `session_meta` may fall before the window.
*/
const seedWindow = (target: StreamModel, page: MessagesPageInfo): void => {
seedPriorStats(target.stats, page.prior);
if (page.contextModel !== undefined) {
target.contextModel = { sessionId: deps.sessionId, ...page.contextModel };
}
+ if (page.agentState !== undefined) target.agentState = page.agentState;
};
const load = async (
diff --git a/packages/web/src/lib/omni/stream-model.ts b/packages/web/src/lib/omni/stream-model.ts
index e53491f7..f5194b3a 100644
--- a/packages/web/src/lib/omni/stream-model.ts
+++ b/packages/web/src/lib/omni/stream-model.ts
@@ -500,7 +500,7 @@ export interface StreamModel {
nested: boolean;
/** Child-session identity from its session_meta (nested models only; null until it arrives). */
meta: NestedSessionMeta | null;
- /** Absolute `agent_state` path from session_meta (null until it arrives); the Memory root `<agent_state>/memory/` for the Task summary's memory-change rows. */
+ /** Absolute `agent_state` path from session_meta or the history page (null until known); the Memory root `<agent_state>/memory/` for the Task summary's memory-change rows. */
agentState: string | null;
/**
* The model the running context was opened on, and the Session its `session_meta` names (null
@@ -774,8 +774,8 @@ export function pushMessage(
}
// session_meta: never rendered as an item itself, but read at BOTH levels. Both keep the
// agent_state path — the main session's Task summary classifies file-tool writes against
- // `<agent_state>/memory/` for its memory-change rows, so a model built from a window that
- // never carries a session_meta derives none. A NESTED child session additionally has no DTO
+ // `<agent_state>/memory/` for its memory-change rows. History pages seed it when the meta
+ // falls before their window. A NESTED child session additionally has no DTO
// loaded here, so it captures the identity the subagents panel needs (which agent runs this
// child, on which model); the main session takes the rest of its identity/config from the
// Session DTO. A rewritten session_meta (file rotation) overwrites with the same values. On
diff --git a/packages/web/test/stream-controller.test.ts b/packages/web/test/stream-controller.test.ts
index fe758cbc..59e3599d 100644
--- a/packages/web/test/stream-controller.test.ts
+++ b/packages/web/test/stream-controller.test.ts
@@ -10,6 +10,12 @@
* asks for 20 more; a page the server cut short at its byte budget still offers the history
* before it; a user image the page carries by reference and the stream's inline copy of it
* draw one picture.
+ *
+ * Memory updates when session_meta falls before the window:
+ * - Given a completed tail, loading it shows one update per topic, excluding the index.
+ * - Given a running tail, edits received live show the same updates when the Task finishes.
+ * - Given an older page, loading it adds that page's updates without mixing them into the tail.
+ * - Given a reconnect, rebuilding the tail preserves its updates without duplicating them.
*/
import { describe, expect, it } from "vitest";
import {
@@ -23,6 +29,7 @@ import {
sessionMeta,
tokenUsage,
toolCall,
+ toolCallOutput,
userText,
withOrigin,
} from "@lmliheng/penguin-core/omnimessage";
@@ -40,6 +47,7 @@ import type { MessagesPageQuery, StreamController } from "../src/lib/omni/stream
import { approvalKey, findToolCard } from "../src/lib/omni/stream-model";
import type {
AssistantTextItem,
+ ChatItem,
TaskStatsItem,
ToolCallItem,
UserImageItem,
@@ -788,6 +796,91 @@ describe("windowed history: tail-first load + scroll-up backfill", () => {
});
});
+describe("memory updates in paginated history", () => {
+ const agentState = "/recorded/agents/memory-agent/agent_state";
+ const page = pageInfo({ before: "1:8", earlierTurns: 1, agentState });
+ const changes = (items: readonly ChatItem[]) =>
+ items.flatMap((item) => (item.kind === "task_stats" ? (item.memoryChanges ?? []) : []));
+
+ function memoryTurn(file: string, day = "05"): OmniMessage[] {
+ const stamp = (message: OmniMessage, second: number) =>
+ at(message, `2026-07-${day}T00:00:${String(second).padStart(2, "0")}.000Z`);
+ return [
+ stamp(userText("remember this"), 0),
+ ...[file, file, "MEMORY.md"].flatMap((name, i) => [
+ stamp(
+ toolCall({
+ name: "edit_file",
+ arguments: JSON.stringify({ file_path: `${agentState}/memory/user/${name}` }),
+ toolCallId: `${file}-${i}`,
+ }),
+ 1 + i * 2,
+ ),
+ stamp(toolCallOutput({ output: "updated", toolCallId: `${file}-${i}` }), 2 + i * 2),
+ ]),
+ stamp(assistantText("remembered"), 7),
+ ];
+ }
+
+ it.each(["idle", "running"] as const)(
+ "a %s tail without session_meta shows one update for repeated topic edits",
+ async (state) => {
+ const h = createHarness();
+ const pending = h.controller.load();
+ h.controller.handleServer({ type: "task_state", state });
+ const messages = memoryTurn("local-dev-instance.md");
+ h.resolveLoad(state === "idle" ? messages : messages.slice(0, 1), undefined, null, page);
+ await pending;
+ if (state === "running") {
+ for (const message of messages.slice(1)) h.controller.handleOmni(message);
+ h.controller.handleServer({ type: "task_state", state: "idle" });
+ }
+ expect(changes(h.controller.model.items)).toMatchObject([
+ { scope: "user", file: "local-dev-instance.md", op: "edit" },
+ ]);
+ },
+ );
+
+ it("an older page restores its own memory updates without mixing them into the tail", async () => {
+ const h = createHarness();
+ const pending = h.controller.load();
+ h.controller.handleServer({ type: "task_state", state: "idle" });
+ h.resolveLoad(memoryTurn("recent.md"), undefined, null, page);
+ await pending;
+
+ const older = h.controller.loadOlder();
+ h.resolveLoad(
+ memoryTurn("older.md", "04"),
+ undefined,
+ null,
+ pageInfo({ before: "1:2", agentState }),
+ );
+ await older;
+ expect(changes(h.controller.prefixItems)).toMatchObject([
+ { scope: "user", file: "older.md", op: "edit" },
+ ]);
+ expect(changes(h.controller.model.items)).toMatchObject([
+ { scope: "user", file: "recent.md", op: "edit" },
+ ]);
+ });
+
+ it("reconnecting preserves the tail's memory updates without duplicating them", async () => {
+ const h = createHarness();
+ const pending = h.controller.load();
+ h.controller.handleServer({ type: "task_state", state: "idle" });
+ const messages = memoryTurn("local-dev-instance.md");
+ h.resolveLoad(messages, undefined, null, page);
+ await pending;
+
+ h.controller.handleServer({ type: "resync_required" });
+ h.resolveLoad(messages, undefined, null, page);
+ await flush();
+ expect(changes(h.controller.model.items)).toMatchObject([
+ { scope: "user", file: "local-dev-instance.md", op: "edit" },
+ ]);
+ });
+});
+
describe("resync decision tree (windowed history)", () => {
const tailPage = pageInfo({ before: "2:10", earlierTurns: 1 });