Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(agent-runtime): deduplicate persisted system events
ZxlDragonDoctor0aeea089c1f3
diff --git a/packages/agent-runtime/src/system-transcript-journal.test.ts b/packages/agent-runtime/src/system-transcript-journal.test.tsindex 59c3e815c..443a035e5 100644--- a/packages/agent-runtime/src/system-transcript-journal.test.ts+++ b/packages/agent-runtime/src/system-transcript-journal.test.ts@@ -45,6 +45,51 @@ describe("model system journal", () => {expect(entries.map((item) => item.message.role)).toEqual(["system", "user"]);});+ it("does not persist a cloned system event twice, but keeps the same payload at a new timestamp", async () => {+ const journal = new SystemTranscriptJournal();+ const entries: MessageEntry[] = [];+ const rows: UiMessage[] = [];+ const append = async (row: UiMessage) => { rows.push(row); };++ await journal.persist([initial], entries, append);+ await journal.persist(structuredClone([initial]), entries, append);+ await journal.persist([{ ...initial, timestamp: initial.timestamp + 1 }], entries, append);++ expect(rows).toHaveLength(2);+ expect(rows.map((row) => readSystemMessage(row.modelSystem?.messageJson))).toEqual([+ initial,+ { ...initial, timestamp: initial.timestamp + 1 },+ ]);+ expect(entries).toHaveLength(2);+ });++ it("collapses exact duplicate system rows during replay without dropping distinct events", () => {+ const duplicate = { ...userRow, id: "system-duplicate", role: "system" as const, modelSystem: {+ version: 1 as const, messageJson: JSON.stringify(initial), beforeMessageId: userRow.id,+ } };+ const distinct = { ...duplicate, id: "system-distinct", modelSystem: {+ ...duplicate.modelSystem,+ messageJson: JSON.stringify({ ...initial, timestamp: initial.timestamp + 1 }),+ } };++ const replay = orderSystemRows([duplicate, { ...duplicate, id: "system-copy" }, distinct, userRow]);+ expect(replay.filter((row) => row.modelSystem)).toHaveLength(2);+ expect(replay.map((row) => row.id)).toContain("system-duplicate");+ expect(replay.map((row) => row.id)).toContain("system-distinct");+ });++ it("recognizes a reconstructed system event after restoring or remembering it", () => {+ const restored = new SystemTranscriptJournal();+ restored.restore({ ...userRow, id: "saved-system", role: "system", modelSystem: {+ version: 1, messageJson: JSON.stringify(initial),+ } });+ expect(restored.isPersisted(structuredClone(initial))).toBe(true);++ const remembered = new SystemTranscriptJournal();+ remembered.remember(initial, "checkpoint-system");+ expect(remembered.isPersisted(structuredClone(initial))).toBe(true);+ });+it("replaces skill sections without rewriting the old prefix", () => {const original = [initial, user];const changed = syncSystemSections(original, { runtime: "Instructions", skills: "Second skill" });diff --git a/packages/agent-runtime/src/system-transcript-journal.ts b/packages/agent-runtime/src/system-transcript-journal.tsindex e3f7492cd..d7948778a 100644--- a/packages/agent-runtime/src/system-transcript-journal.ts+++ b/packages/agent-runtime/src/system-transcript-journal.ts@@ -29,14 +29,26 @@ export function readSystemMessage(value: unknown): SystemMessage {return value as SystemMessage;}+function serializedSystemMessage(message: SystemMessage): string {+ return JSON.stringify({+ ...message,+ content: contentText(message.content),+ ...(message.toolsAdded ? { toolsAdded: message.toolsAdded.map(toToolDeclaration) } : {}),+ });+}+/** Reorder only internal rows, whose following user row may have arrived first. */export function orderSystemRows(history: readonly UiMessage[]): UiMessage[] {const rows = history.filter((row) => !row.modelSystem);+ const seen = new Set<string>();for (const row of history) {if (!row.modelSystem) continue;if (row.role !== "system" || row.modelSystem.version !== 1) {throw new Error("Invalid model system record");}+ const key = serializedSystemMessage(readSystemMessage(row.modelSystem.messageJson));+ if (seen.has(key)) continue;+ seen.add(key);const before = row.modelSystem.beforeMessageId;let index = before ? rows.findIndex((candidate) => candidate.id === before) : -1;if (index < 0 && row.modelSystem.afterMessageId) {@@ -54,17 +66,22 @@ export function orderSystemRows(history: readonly UiMessage[]): UiMessage[] {/** Persist provider-neutral declarations before dispatch; never persist a folded request. */export class SystemTranscriptJournal {private readonly ids = new WeakMap<AgentMessage, string>();+ private readonly serializedIds = new Set<string>();private readonly pending = new WeakMap<AgentMessage, string>();private readonly checkpoints = new Set<string>();restore(row: UiMessage): SystemMessage {const message = readSystemMessage(row.modelSystem?.messageJson);this.ids.set(message, row.id);+ this.serializedIds.add(serializedSystemMessage(message));return message;}isPersisted(message: AgentMessage): boolean {- return this.ids.has(message) || this.checkpoints.has(JSON.stringify(message));+ if (message.role !== "system") return false;+ if (this.ids.has(message)) return true;+ const key = serializedSystemMessage(message);+ return this.serializedIds.has(key) || this.checkpoints.has(key);}async persist(@@ -81,13 +98,15 @@ export class SystemTranscriptJournal {const previousEntry = preceding && entries.find((entry) => entry.message === preceding);const id = this.pending.get(message) ?? randomUUID();this.pending.set(message, id);- const serialized: SystemMessage = {- ...message, content: contentText(message.content),- ...(message.toolsAdded ? { toolsAdded: message.toolsAdded.map(toToolDeclaration) } : {}),- };+ const serializedKey = serializedSystemMessage(message);const row: UiMessage = {id, role: "system", content: "", createdAt: new Date(message.timestamp).toISOString(),- modelSystem: { version: 1, messageJson: JSON.stringify(serialized), ...(nextEntry ? { beforeMessageId: nextEntry.id } : {}), ...(previousEntry ? { afterMessageId: previousEntry.id } : {}) },+ modelSystem: {+ version: 1,+ messageJson: serializedKey,+ ...(nextEntry ? { beforeMessageId: nextEntry.id } : {}),+ ...(previousEntry ? { afterMessageId: previousEntry.id } : {}),+ },};try {await append(row);@@ -97,6 +116,7 @@ export class SystemTranscriptJournal {throw new LocalRequestError("request-preparation", { cause });}this.ids.set(message, id);+ this.serializedIds.add(serializedKey);this.pending.delete(message);const entry: MessageEntry = {type: "message", id, seq: entries.length, parentId: null,@@ -109,10 +129,11 @@ export class SystemTranscriptJournal {}rememberCheckpoint(message: unknown): void {- this.checkpoints.add(JSON.stringify(readSystemMessage(message)));+ this.checkpoints.add(serializedSystemMessage(readSystemMessage(message)));}remember(message: AgentMessage, id: string): void {this.ids.set(message, id);+ if (message.role === "system") this.serializedIds.add(serializedSystemMessage(message));}}