Skip to content

Commit d35c79e

Browse files
dashhuangaltaywtf
andauthored
fix(agents): suppress duplicate user persistence on fallback retries (#63696)
* fix(agents): suppress duplicate user persistence on fallback retries * refactor(agents): align persisted-user callback types * docs: note fallback transcript dedupe * refactor(agents): remove fallback persistence casts --------- Co-authored-by: Altay <[email protected]>
1 parent 4488382 commit d35c79e

10 files changed

Lines changed: 101 additions & 0 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,7 @@ Docs: https://docs.openclaw.ai
167167

168168
- Plugins/providers: preserve scoped cold-load fallback for enabled external manifest-contract capability providers missing from the startup registry, so providers such as Fish Audio can resolve on request without requiring `activation.onStartup` for correctness. (#76536) Thanks @Conan-Scott.
169169
- Gateway/update: carry `continuationMessage` from `update.run` into successful restart sentinels so session-scoped self-updates can resume one follow-up turn after the Gateway restarts. Refs #71178. (#74362) Thanks @100menotu001, @HeilbronAILabs, and @artnking.
170+
- Agents/fallback: suppress duplicate current-turn user-message transcript writes after embedded fallback retries while still sending the retry prompt to the model. (#63696) Thanks @dashhuang.
170171

171172
## 2026.5.2
172173

‎src/agents/agent-command.live-model-switch.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -765,6 +765,36 @@ describe("agentCommand – LiveSessionModelSwitchError retry", () => {
765765
expect(state.trajectoryFlushMock).toHaveBeenCalled();
766766
});
767767

768+
it("suppresses duplicate user persistence only after the current turn has flushed", async () => {
769+
type AttemptCall = {
770+
onUserMessagePersisted?: () => void;
771+
suppressPromptPersistenceOnRetry?: boolean;
772+
};
773+
const attemptCalls: AttemptCall[] = [];
774+
state.runWithModelFallbackMock.mockImplementation(async (params: FallbackRunnerParams) => {
775+
const first = await params.run(params.provider, params.model);
776+
const result = await params.run(params.provider, params.model);
777+
return {
778+
result,
779+
provider: params.provider,
780+
model: params.model,
781+
attempts: [first],
782+
};
783+
});
784+
state.runAgentAttemptMock.mockImplementation(async (attemptParams: AttemptCall) => {
785+
attemptCalls.push(attemptParams);
786+
attemptParams.onUserMessagePersisted?.();
787+
return makeSuccessResult("openai", "gpt-5.4");
788+
});
789+
790+
await runBasicAgentCommand();
791+
792+
expect(attemptCalls).toHaveLength(2);
793+
expect(attemptCalls[0]?.suppressPromptPersistenceOnRetry).not.toBe(true);
794+
expect(typeof attemptCalls[0]?.onUserMessagePersisted).toBe("function");
795+
expect(attemptCalls[1]?.suppressPromptPersistenceOnRetry).toBe(true);
796+
});
797+
768798
it("propagates non-switch errors without retrying and emits lifecycle error", async () => {
769799
state.runWithModelFallbackMock.mockRejectedValueOnce(new Error("provider down"));
770800

‎src/agents/agent-command.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -966,6 +966,7 @@ async function agentCommandInternal(
966966
});
967967

968968
let fallbackAttemptIndex = 0;
969+
let currentTurnUserMessagePersisted = false;
969970
const fallbackResult = await runWithModelFallback<AgentAttemptResult>({
970971
cfg,
971972
provider,
@@ -1022,6 +1023,11 @@ async function agentCommandInternal(
10221023
allowTransientCooldownProbe: runOptions?.allowTransientCooldownProbe,
10231024
sessionHasHistory:
10241025
!isNewSession || (await attemptExecutionRuntime.sessionFileHasContent(sessionFile)),
1026+
suppressPromptPersistenceOnRetry:
1027+
isFallbackRetry && currentTurnUserMessagePersisted,
1028+
onUserMessagePersisted: () => {
1029+
currentTurnUserMessagePersisted = true;
1030+
},
10251031
onAgentEvent: (evt) => {
10261032
if (evt.stream.startsWith("codex_app_server.")) {
10271033
emitAgentEvent({

‎src/agents/command/attempt-execution.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import type { AgentMessage } from "@mariozechner/pi-agent-core";
12
import { normalizeReplyPayload } from "../../auto-reply/reply/normalize-reply.js";
23
import type { ThinkLevel, VerboseLevel } from "../../auto-reply/thinking.js";
34
import { appendSessionTranscriptMessage } from "../../config/sessions/transcript-append.js";
@@ -357,6 +358,8 @@ export function runAgentAttempt(params: {
357358
allowTransientCooldownProbe?: boolean;
358359
modelFallbacksOverride?: string[];
359360
sessionHasHistory?: boolean;
361+
suppressPromptPersistenceOnRetry?: boolean;
362+
onUserMessagePersisted?: (message: Extract<AgentMessage, { role: "user" }>) => void;
360363
}) {
361364
const isRawModelRun = params.opts.modelRun === true || params.opts.promptMode === "none";
362365
const claudeCliFallbackPrelude =
@@ -611,6 +614,8 @@ export function runAgentAttempt(params: {
611614
promptMode: params.opts.promptMode,
612615
disableTools: params.opts.modelRun === true,
613616
onAgentEvent: params.onAgentEvent,
617+
suppressNextUserMessagePersistence: params.suppressPromptPersistenceOnRetry === true,
618+
onUserMessagePersisted: params.onUserMessagePersisted,
614619
bootstrapPromptWarningSignaturesSeen,
615620
bootstrapPromptWarningSignature,
616621
});

‎src/agents/pi-embedded-runner/run.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1166,6 +1166,8 @@ export async function runEmbeddedPiAgent(
11661166
bootstrapPromptWarningSignaturesSeen,
11671167
bootstrapPromptWarningSignature:
11681168
bootstrapPromptWarningSignaturesSeen[bootstrapPromptWarningSignaturesSeen.length - 1],
1169+
suppressNextUserMessagePersistence: params.suppressNextUserMessagePersistence,
1170+
onUserMessagePersisted: params.onUserMessagePersisted,
11691171
});
11701172
const attempt = normalizeEmbeddedRunAttemptResult(rawAttempt);
11711173

‎src/agents/pi-embedded-runner/run/attempt.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1432,6 +1432,10 @@ export async function runEmbeddedAttempt(
14321432
? "aborted"
14331433
: undefined,
14341434
allowedToolNames,
1435+
suppressNextUserMessagePersistence: params.suppressNextUserMessagePersistence,
1436+
onUserMessagePersisted: (message) => {
1437+
params.onUserMessagePersisted?.(message);
1438+
},
14351439
});
14361440
trackSessionManagerAccess(params.sessionFile);
14371441

‎src/agents/pi-embedded-runner/run/params.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import type { AgentMessage } from "@mariozechner/pi-agent-core";
12
import type { ImageContent } from "@mariozechner/pi-ai";
23
import type { SourceReplyDeliveryMode } from "../../../auto-reply/get-reply-options.types.js";
34
import type { ReplyPayload } from "../../../auto-reply/reply-payload.js";
@@ -178,6 +179,8 @@ export type RunEmbeddedPiAgentParams = {
178179
* where transient service pressure is often model-scoped.
179180
*/
180181
allowTransientCooldownProbe?: boolean;
182+
suppressNextUserMessagePersistence?: boolean;
183+
onUserMessagePersisted?: (message: Extract<AgentMessage, { role: "user" }>) => void;
181184
/**
182185
* Dispose bundled MCP runtimes when the overall run ends instead of preserving
183186
* the session-scoped cache. Intended for one-shot local CLI runs that must

‎src/agents/session-tool-result-guard-wrapper.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,10 @@ export function guardSessionManager(
9797
allowSyntheticToolResults?: boolean;
9898
missingToolResultText?: string;
9999
allowedToolNames?: Iterable<string>;
100+
suppressNextUserMessagePersistence?: boolean;
101+
onUserMessagePersisted?: (
102+
message: Extract<AgentMessage, { role: "user" }>,
103+
) => void | Promise<void>;
100104
},
101105
): GuardedSessionManager {
102106
if (typeof (sessionManager as GuardedSessionManager).flushPendingToolResults === "function") {
@@ -170,6 +174,8 @@ export function guardSessionManager(
170174
agentId: opts.agentId,
171175
})
172176
: undefined,
177+
suppressNextUserMessagePersistence: opts?.suppressNextUserMessagePersistence,
178+
onUserMessagePersisted: opts?.onUserMessagePersisted,
173179
});
174180
(sessionManager as GuardedSessionManager).flushPendingToolResults = guard.flushPendingToolResults;
175181
(sessionManager as GuardedSessionManager).clearPendingToolResults = guard.clearPendingToolResults;

‎src/agents/session-tool-result-guard.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -498,6 +498,32 @@ describe("installSessionToolResultGuard", () => {
498498
});
499499
});
500500

501+
it("suppresses only the next persisted user message when requested", () => {
502+
const sm = SessionManager.inMemory();
503+
installSessionToolResultGuard(sm, {
504+
suppressNextUserMessagePersistence: true,
505+
});
506+
507+
sm.appendMessage(
508+
asAppendMessage({
509+
role: "user",
510+
content: "first",
511+
timestamp: Date.now(),
512+
}),
513+
);
514+
sm.appendMessage(
515+
asAppendMessage({
516+
role: "user",
517+
content: "second",
518+
timestamp: Date.now() + 1,
519+
}),
520+
);
521+
522+
const persisted = getPersistedMessages(sm);
523+
expect(persisted.map((message) => message.role)).toEqual(["user"]);
524+
expect(persisted[0]).toMatchObject({ content: "second" });
525+
});
526+
501527
// When an assistant message with toolCalls is aborted, no synthetic toolResult
502528
// should be created. Creating synthetic results for aborted/incomplete tool calls
503529
// causes API 400 errors: "unexpected tool_use_id found in tool_result blocks".

‎src/agents/session-tool-result-guard.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,12 @@ function resolveMaxToolResultChars(opts?: { maxToolResultChars?: number }): numb
4444
return Math.max(1, opts?.maxToolResultChars ?? DEFAULT_MAX_LIVE_TOOL_RESULT_CHARS);
4545
}
4646

47+
type UserAgentMessage = Extract<AgentMessage, { role: "user" }>;
48+
49+
function isUserAgentMessage(message: AgentMessage): message is UserAgentMessage {
50+
return message.role === "user";
51+
}
52+
4753
// `details` is runtime/UI metadata, not model-visible tool output. Keep the
4854
// session JSONL useful for debugging without letting metadata blobs dominate
4955
// disk, replay repair, transcript broadcasts, or future tooling that reads raw
@@ -302,6 +308,10 @@ export function installSessionToolResultGuard(
302308
event: PluginHookBeforeMessageWriteEvent,
303309
) => PluginHookBeforeMessageWriteResult | undefined;
304310
maxToolResultChars?: number;
311+
suppressNextUserMessagePersistence?: boolean;
312+
onUserMessagePersisted?: (
313+
message: Extract<AgentMessage, { role: "user" }>,
314+
) => void | Promise<void>;
305315
},
306316
): {
307317
flushPendingToolResults: () => void;
@@ -328,6 +338,7 @@ export function installSessionToolResultGuard(
328338
const missingToolResultText = opts?.missingToolResultText;
329339
const beforeWrite = opts?.beforeMessageWriteHook;
330340
const maxToolResultChars = resolveMaxToolResultChars(opts);
341+
let suppressNextUserMessagePersistence = opts?.suppressNextUserMessagePersistence === true;
331342

332343
/**
333344
* Run the before_message_write hook. Returns the (possibly modified) message,
@@ -450,6 +461,10 @@ export function installSessionToolResultGuard(
450461
if (!finalMessage) {
451462
return undefined;
452463
}
464+
if (isUserAgentMessage(finalMessage) && suppressNextUserMessagePersistence) {
465+
suppressNextUserMessagePersistence = false;
466+
return undefined;
467+
}
453468
const result = originalAppend(finalMessage as never);
454469

455470
const sessionFile = (
@@ -467,6 +482,9 @@ export function installSessionToolResultGuard(
467482
if (toolCalls.length > 0) {
468483
pendingState.trackToolCalls(toolCalls);
469484
}
485+
if (isUserAgentMessage(finalMessage)) {
486+
void opts?.onUserMessagePersisted?.(finalMessage);
487+
}
470488

471489
return result;
472490
};

0 commit comments

Comments
 (0)