Skip to content

Commit e85004a

Browse files
committed
fix(agents): keep delivering reply when post-turn compaction fails
A CLI-backed turn persists its assistant reply to the live transcript, then runs post-turn compaction. A compaction throw (e.g. 'CLI transcript compaction failed: Summarization failed: Connection error.') escaped to the outer catch, which re-threw before delivery — discarding an already-generated reply and surfacing the turn as unavailable. Guard the post-turn compaction call: when a deliverable reply exists, warn and continue to delivery; otherwise keep the failure fatal so a no-reply turn is not reported as an empty success. Fixes #94688
1 parent f7c3775 commit e85004a

2 files changed

Lines changed: 174 additions & 24 deletions

File tree

‎src/agents/agent-command.compaction-rotation.test.ts‎

Lines changed: 138 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,12 @@ const state = vi.hoisted(() => ({
2323
normalizeProviderModelIdWithRuntimeMock: vi.fn(
2424
(_params: ProviderModelNormalizationParams) => undefined,
2525
),
26+
runCliTurnCompactionLifecycleMock: vi.fn(
27+
async (params: { sessionEntry?: SessionEntry }) => params.sessionEntry,
28+
),
29+
emitAgentEventMock: vi.fn(),
2630
deliveryFreshEntries: [] as Array<SessionEntry | undefined>,
31+
deliveryCalls: 0,
2732
}));
2833

2934
vi.mock("../config/io.js", () => ({
@@ -144,14 +149,28 @@ vi.mock("./command/attempt-execution.runtime.js", async () => {
144149
});
145150

146151
vi.mock("./command/cli-compaction.js", () => ({
147-
runCliTurnCompactionLifecycle: async (params: { sessionEntry?: SessionEntry }) =>
148-
params.sessionEntry,
152+
runCliTurnCompactionLifecycle: (params: { sessionEntry?: SessionEntry }) =>
153+
state.runCliTurnCompactionLifecycleMock(params),
149154
}));
150155

156+
vi.mock("../infra/agent-events.js", async () => {
157+
const actual = await vi.importActual<typeof import("../infra/agent-events.js")>(
158+
"../infra/agent-events.js",
159+
);
160+
return {
161+
...actual,
162+
emitAgentEvent: (...args: Parameters<typeof actual.emitAgentEvent>) => {
163+
state.emitAgentEventMock(...args);
164+
return actual.emitAgentEvent(...args);
165+
},
166+
};
167+
});
168+
151169
vi.mock("./command/delivery.runtime.js", () => ({
152170
deliverAgentCommandResult: async (params: {
153171
resolveFreshSessionEntryForDelivery?: () => Promise<SessionEntry | undefined>;
154172
}) => {
173+
state.deliveryCalls += 1;
155174
state.deliveryFreshEntries.push(await params.resolveFreshSessionEntryForDelivery?.());
156175
return { deliverySucceeded: true };
157176
},
@@ -167,7 +186,11 @@ beforeEach(async () => {
167186
vi.clearAllMocks();
168187
state.loadManifestModelCatalogMock.mockReturnValue([]);
169188
state.normalizeProviderModelIdWithRuntimeMock.mockImplementation(() => undefined);
189+
state.runCliTurnCompactionLifecycleMock.mockImplementation(
190+
async (params: { sessionEntry?: SessionEntry }) => params.sessionEntry,
191+
);
170192
state.deliveryFreshEntries = [];
193+
state.deliveryCalls = 0;
171194
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-rotation-e2e-"));
172195
state.workspaceDir = path.join(tmpDir, "workspace");
173196
state.agentDir = path.join(tmpDir, "agent");
@@ -353,6 +376,119 @@ describe("agentCommand compaction transcript rotation", () => {
353376
]);
354377
});
355378

379+
it("delivers the already-generated reply when post-turn compaction fails", async () => {
380+
state.runCliTurnCompactionLifecycleMock.mockRejectedValueOnce(
381+
new Error(
382+
"CLI transcript compaction failed for openai/gpt-5.5: Summarization failed: Connection error.",
383+
),
384+
);
385+
state.runAgentAttemptMock.mockResolvedValueOnce(
386+
makeResult({
387+
sessionId: "yuyu-home",
388+
text: "reply generated before compaction failed",
389+
}),
390+
);
391+
392+
const result = await agentCommand({
393+
message: "room message",
394+
sessionId: "yuyu-home",
395+
cwd: state.workspaceDir,
396+
deliver: true,
397+
});
398+
399+
expect(state.runCliTurnCompactionLifecycleMock).toHaveBeenCalledTimes(1);
400+
expect(state.deliveryCalls).toBe(1);
401+
expect(result).toMatchObject({ deliverySucceeded: true });
402+
403+
// The turn must settle as a normal lifecycle "end", never a post-turn
404+
// "error": a swallowed compaction failure cannot reclassify a delivered turn.
405+
const lifecyclePhases = state.emitAgentEventMock.mock.calls
406+
.map(([event]) => event as { stream?: string; data?: { phase?: string } })
407+
.filter((event) => event?.stream === "lifecycle")
408+
.map((event) => event.data?.phase);
409+
expect(lifecyclePhases).toContain("end");
410+
expect(lifecyclePhases).not.toContain("error");
411+
});
412+
413+
it("delivers a media-only reply (no assistant text) when post-turn compaction fails", async () => {
414+
state.runCliTurnCompactionLifecycleMock.mockRejectedValueOnce(
415+
new Error(
416+
"CLI transcript compaction failed for openai/gpt-5.5: Summarization failed: Connection error.",
417+
),
418+
);
419+
state.runAgentAttemptMock.mockResolvedValueOnce({
420+
payloads: [{ mediaUrls: ["https://example.com/generated.png"] }],
421+
meta: {
422+
durationMs: 1,
423+
stopReason: "end_turn",
424+
executionTrace: {
425+
runner: "cli" as const,
426+
fallbackUsed: false,
427+
winnerProvider: "openai",
428+
winnerModel: "gpt-5.5",
429+
},
430+
agentMeta: {
431+
sessionId: "media-only-session",
432+
provider: "openai",
433+
model: "gpt-5.5",
434+
},
435+
},
436+
});
437+
438+
const result = await agentCommand({
439+
message: "generate an image",
440+
sessionId: "media-only-session",
441+
cwd: state.workspaceDir,
442+
deliver: true,
443+
});
444+
445+
// A media reply has no assistant text but is still deliverable, so the
446+
// compaction failure must not discard it.
447+
expect(state.runCliTurnCompactionLifecycleMock).toHaveBeenCalledTimes(1);
448+
expect(state.deliveryCalls).toBe(1);
449+
expect(result).toMatchObject({ deliverySucceeded: true });
450+
});
451+
452+
it("keeps a no-reply turn's compaction failure fatal instead of an empty success", async () => {
453+
const noReplyResult: EmbeddedAgentRunResult = {
454+
payloads: [],
455+
meta: {
456+
durationMs: 1,
457+
stopReason: "end_turn",
458+
executionTrace: {
459+
runner: "cli" as const,
460+
fallbackUsed: false,
461+
winnerProvider: "openai",
462+
winnerModel: "gpt-5.5",
463+
},
464+
agentMeta: {
465+
sessionId: "no-reply-session",
466+
provider: "openai",
467+
model: "gpt-5.5",
468+
},
469+
},
470+
};
471+
state.runCliTurnCompactionLifecycleMock.mockRejectedValueOnce(
472+
new Error(
473+
"CLI transcript compaction failed for openai/gpt-5.5: Summarization failed: Connection error.",
474+
),
475+
);
476+
state.runAgentAttemptMock.mockResolvedValueOnce(noReplyResult);
477+
478+
await expect(
479+
agentCommand({
480+
message: "prompt that produced no assistant reply",
481+
sessionId: "no-reply-session",
482+
cwd: state.workspaceDir,
483+
deliver: true,
484+
}),
485+
).rejects.toThrow("Summarization failed: Connection error.");
486+
487+
// Compaction was reached, the failure stayed fatal, and nothing was delivered.
488+
expect(state.runCliTurnCompactionLifecycleMock).toHaveBeenCalledTimes(1);
489+
expect(state.deliveryCalls).toBe(0);
490+
});
491+
356492
it("resumes the next turn from the rotated successor", async () => {
357493
const storePath = requireStorePath();
358494
const sessionsDir = await fs.realpath(path.dirname(storePath));

‎src/agents/agent-command.ts‎

Lines changed: 36 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import {
3232
resolveAgentOutboundTarget,
3333
} from "../infra/outbound/agent-delivery.js";
3434
import { resolveMessageChannelSelection } from "../infra/outbound/channel-selection.js";
35+
import { normalizeOutboundPayloads } from "../infra/outbound/payloads.js";
3536
import { buildOutboundSessionContext } from "../infra/outbound/session-context.js";
3637
import { parseStrictNonNegativeInteger } from "../infra/parse-finite-number.js";
3738
import { createSubsystemLogger } from "../logging/subsystem.js";
@@ -2212,28 +2213,41 @@ async function agentCommandInternal(
22122213
);
22132214
}
22142215
if (persistedCliTurnTranscript && !suppressVisibleSessionEffects) {
2215-
sessionEntry = await (
2216-
await loadCliCompactionRuntime()
2217-
).runCliTurnCompactionLifecycle({
2218-
cfg,
2219-
sessionId: effectiveSessionId,
2220-
sessionKey: sessionKey ?? effectiveSessionId,
2221-
sessionEntry,
2222-
sessionStore,
2223-
storePath,
2224-
sessionAgentId,
2225-
workspaceDir,
2226-
cwd: effectiveCwd,
2227-
agentDir,
2228-
provider: result.meta.agentMeta?.provider ?? provider,
2229-
model: result.meta.agentMeta?.model ?? model,
2230-
skillsSnapshot,
2231-
messageChannel,
2232-
agentAccountId: runContext.accountId,
2233-
senderIsOwner: opts.senderIsOwner,
2234-
thinkLevel: resolvedThinkLevel,
2235-
extraSystemPrompt: opts.extraSystemPrompt,
2236-
});
2216+
try {
2217+
sessionEntry = await (
2218+
await loadCliCompactionRuntime()
2219+
).runCliTurnCompactionLifecycle({
2220+
cfg,
2221+
sessionId: effectiveSessionId,
2222+
sessionKey: sessionKey ?? effectiveSessionId,
2223+
sessionEntry,
2224+
sessionStore,
2225+
storePath,
2226+
sessionAgentId,
2227+
workspaceDir,
2228+
cwd: effectiveCwd,
2229+
agentDir,
2230+
provider: result.meta.agentMeta?.provider ?? provider,
2231+
model: result.meta.agentMeta?.model ?? model,
2232+
skillsSnapshot,
2233+
messageChannel,
2234+
agentAccountId: runContext.accountId,
2235+
senderIsOwner: opts.senderIsOwner,
2236+
thinkLevel: resolvedThinkLevel,
2237+
extraSystemPrompt: opts.extraSystemPrompt,
2238+
});
2239+
} catch (error) {
2240+
// Post-turn compaction only trims context for future turns; a failure must not discard
2241+
// a reply already generated and persisted above. Gate on the outbound content
2242+
// projection: with nothing deliverable, stay fatal so an empty/silent turn is not lost.
2243+
const hasDeliverableReply = normalizeOutboundPayloads(result.payloads ?? []).length > 0;
2244+
if (!hasDeliverableReply) {
2245+
throw error;
2246+
}
2247+
log.warn(
2248+
`Post-turn CLI compaction failed for ${sessionKey ?? sessionId}; delivering reply without compaction: ${error instanceof Error ? error.message : String(error)}`,
2249+
);
2250+
}
22372251
}
22382252
}
22392253

0 commit comments

Comments
 (0)