Skip to content

Commit 3ec4089

Browse files
authored
fix(gateway): give prepared chat.send media one abandonment-discard owner (#124100)
#123983 fixed two of six pre-persistence exits that orphan staged inbound media (~/.openclaw/media/inbound has no transcript reference until the user turn persists, and the inbound sweep is off by default). Four sibling exits still leaked: the post-reply-context abort and routing-change checks, the pre-ACK injection settle (onAborted/onActiveLeafChanged), and any setup throw routed to handleChatSendSetupError. Instead of adding four more inline discards, the custody moves to the admission cleanup owner: every abandonment exit already funnels through cleanupAdmittedRun, which now fires an armed discard gated on the user-turn recorder's persisted fact (the restart-safe path persists durably before its exits; steer injections carry the same recorder). The ACK disarms it because dispatch's error lifecycle persists the referencing transcript on every post-ACK path. The two inline discards #123983 added are deleted. Regression test drives the setup-error exit with an offloaded attachment and fails pre-fix; the original #123983 abort test still passes through the new owner.
1 parent f1ced37 commit 3ec4089

3 files changed

Lines changed: 89 additions & 2 deletions

File tree

‎src/gateway/server-methods/chat-send-admission.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -460,11 +460,19 @@ export async function admitChatSend(params: {
460460
};
461461
};
462462
let releaseGatewayRootContinuation: (() => void) | undefined;
463+
// Prepared inbound media has no transcript reference until the user turn
464+
// persists; every abandonment exit funnels through cleanupAdmittedRun, so
465+
// the armed discard here is the single custody owner for that window. The
466+
// handler disarms it once the media becomes referenced (durable admission
467+
// or ACK handing ownership to dispatch, which persists on all paths).
468+
let discardAbandonedPreparedMedia: (() => void) | undefined;
463469
const cleanupAdmittedRun: typeof activeRunAbort.cleanup = (options) => {
464470
activeRunAbort.cleanup(options);
465471
releaseInitialGatewayWorkAdmission();
466472
releaseGatewayRootContinuation?.();
467473
releaseGatewayRootContinuation = undefined;
474+
discardAbandonedPreparedMedia?.();
475+
discardAbandonedPreparedMedia = undefined;
468476
};
469477
const rejectActiveLeafChanged = async () => {
470478
if (
@@ -525,6 +533,9 @@ export async function admitChatSend(params: {
525533
rejectSessionRoutingChanged,
526534
retainGatewayWorkAdmission,
527535
restartSafeAdmission,
536+
setDiscardAbandonedPreparedMedia: (discard: (() => void) | undefined) => {
537+
discardAbandonedPreparedMedia = discard;
538+
},
528539
setReleaseGatewayRootContinuation: (release: (() => void) | undefined) => {
529540
releaseGatewayRootContinuation = release;
530541
},

‎src/gateway/server-methods/chat-send-handler.ts‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,15 +73,24 @@ async function handleChatSendWithOptions(
7373
if (!preparedAttachments.ok) {
7474
return;
7575
}
76+
// Prepared inbound media has no transcript reference until the user turn
77+
// persists; every pre-ACK abandonment exit funnels through
78+
// cleanupAdmittedRun, which fires this armed discard. The hasPersisted gate
79+
// protects the restart-safe path, which persists durably before its abort
80+
// and routing exits; dispatch owns persistence after the ACK disarms this.
81+
let preparedMediaRecorder: { hasPersisted: () => boolean } | undefined;
82+
admitted.value.setDiscardAbandonedPreparedMedia(() => {
83+
if (!preparedMediaRecorder?.hasPersisted()) {
84+
void discardPreparedChatSendAttachments(preparedAttachments.value.offloadedRefs);
85+
}
86+
});
7687
if (activeRunAbort.controller.signal.aborted) {
77-
void discardPreparedChatSendAttachments(preparedAttachments.value.offloadedRefs);
7888
finishAbortedChatSend();
7989
return;
8090
}
8191
// Attachment preparation can suspend. Recheck immediately before the
8292
// synchronous ACK path so aborts and hot routing reloads cannot cross it.
8393
if (sessionRoutingChanged(context.getRuntimeConfig())) {
84-
void discardPreparedChatSendAttachments(preparedAttachments.value.offloadedRefs);
8594
admitted.value.rejectSessionRoutingChanged();
8695
return;
8796
}
@@ -129,6 +138,7 @@ async function handleChatSendWithOptions(
129138
recorder: userTurnRecorder,
130139
replyContextFieldsPromise,
131140
} = userTurn;
141+
preparedMediaRecorder = userTurnRecorder;
132142
if (restartSafeAdmission) {
133143
const persistedUserTurn = await persistGatewayUserTurnTranscript();
134144
// A matching idempotency row and lifecycle claim commit atomically, so
@@ -252,6 +262,10 @@ async function handleChatSendWithOptions(
252262
},
253263
{ config: cfg },
254264
);
265+
// After the ACK, dispatch owns the turn: its error lifecycle persists the
266+
// user transcript (which references the media) on every path, so a
267+
// post-ACK cleanupAdmittedRun must not race that persist with a discard.
268+
admitted.value.setDiscardAbandonedPreparedMedia(undefined);
255269
respond(true, ackPayload, undefined, { runId: clientRunId });
256270
const chatSendAckedAtMs = chatSendTiming?.ackedAtMs ?? performance.now();
257271
startChatDispatch({

‎src/gateway/server.chat.gateway-server-chat-b.test.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2112,6 +2112,68 @@ describe("gateway server chat", () => {
21122112
}
21132113
});
21142114

2115+
test("chat.send discards prepared inbound media when setup throws before the ACK", async () => {
2116+
openDirectChatSession();
2117+
try {
2118+
await writeStoredMainSession({
2119+
modelProvider: "test-provider",
2120+
model: "vision-model",
2121+
});
2122+
const context = createDirectChatContext({
2123+
// Throwing from addChatRun exercises handleChatSendSetupError — one of
2124+
// the pre-persistence exits that previously leaked staged media.
2125+
addChatRun: vi.fn(() => {
2126+
throw new Error("setup exploded before ack");
2127+
}),
2128+
getRuntimeConfig: () => ({}),
2129+
});
2130+
const inboundDir = path.join(getMediaDir(), "inbound");
2131+
const inboundBaseline = new Set(await fs.readdir(inboundDir).catch(() => []));
2132+
const responses: Array<{ ok: boolean; payload?: unknown; error?: unknown }> = [];
2133+
await callDirectChat("chat.send", {
2134+
id: "setup-error-media",
2135+
params: makeChatSendParams({
2136+
message: "setup error with media",
2137+
idempotencyKey: "idem-setup-error-media",
2138+
attachments: [
2139+
{
2140+
// Non-image attachments always offload into the inbound media
2141+
// store during preparation; the failed send must discard them.
2142+
type: "file",
2143+
mimeType: "text/plain",
2144+
fileName: "notes.txt",
2145+
content: Buffer.from("offloaded inbound media").toString("base64"),
2146+
},
2147+
],
2148+
}),
2149+
client: {
2150+
connId: "conn-owner",
2151+
connect: { device: { id: "dev-owner" }, scopes: ["operator.write"] },
2152+
} as never,
2153+
respond: ((ok, payload, error) => {
2154+
responses.push({ ok, payload, error });
2155+
}) as RespondFn,
2156+
context,
2157+
});
2158+
expect(responses).toEqual([
2159+
{
2160+
ok: false,
2161+
payload: expect.objectContaining({ status: "error" }),
2162+
error: expect.anything(),
2163+
},
2164+
]);
2165+
// Prepared inbound media has no transcript reference on this exit; the
2166+
// admission cleanup owner must discard it or the file is orphaned
2167+
// forever (the inbound sweep is off unless attachments.ttlHours is set).
2168+
await waitForFast(async () => {
2169+
const remaining = await fs.readdir(inboundDir).catch(() => []);
2170+
expect(remaining.filter((name) => !inboundBaseline.has(name))).toEqual([]);
2171+
}, FAST_WAIT_OPTS);
2172+
} finally {
2173+
resetDirectChatSession();
2174+
}
2175+
});
2176+
21152177
test("chat.abort cancels chat.send during attachment preparation before ACK", async () => {
21162178
openDirectChatSession();
21172179
const firstCatalogSnapshot =

0 commit comments

Comments
 (0)