Skip to content

Commit 150b285

Browse files
committed
fix(gateway): keep uncommitted generated media while its session run is live
Generated assistant media is stored with a null messageId and a transient retention class until the assistant turn commits its transcript message and attaches the record. The managed outgoing media GC reaped transient records purely by age, so any turn still in flight past the 15 minute TTL had its media records and files deleted before finalization; the later attach is silently ineffective and the committed message keeps a permanently dead media URL. Cleanup now accepts a hasActiveSessionRun probe and skips the transient age reap while the owning session still has a registered chat run. Both GC entry points, the chat.history sweep and the maintenance sweep, supply the probe from the gateway's registered chat run map, which spans admission through finalization. Sessions without a live run keep the existing TTL behavior.
1 parent 6d2ba0d commit 150b285

6 files changed

Lines changed: 146 additions & 5 deletions

File tree

‎src/gateway/managed-image-attachments.test.ts‎

Lines changed: 53 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
2525
import { withEnvAsync } from "../test-utils/env.js";
2626
import {
27+
attachManagedImageRecordToMessage,
2728
insertManagedImageRecord,
2829
MANAGED_OUTGOING_ORIGINALS_SUBDIR,
2930
readManagedImageRecord,
@@ -231,6 +232,8 @@ async function createFixture(
231232
filename?: string;
232233
contentType?: string;
233234
body?: Buffer;
235+
messageId?: string | null;
236+
createdAt?: string;
234237
},
235238
) {
236239
const attachmentId = options?.attachmentId ?? "11111111-1111-4111-8111-111111111111";
@@ -245,8 +248,8 @@ async function createFixture(
245248
attachmentId,
246249
sessionKey,
247250
...(options?.agentId ? { agentId: options.agentId } : {}),
248-
messageId: "msg-1",
249-
createdAt: new Date().toISOString(),
251+
messageId: options?.messageId === undefined ? "msg-1" : options.messageId,
252+
createdAt: options?.createdAt ?? new Date().toISOString(),
250253
alt: "Cat",
251254
original: {
252255
mediaRoot: path.join(stateDir, "media"),
@@ -1927,6 +1930,54 @@ describe("cleanupManagedOutgoingImageRecords", () => {
19271930
await expectPathMissing(fixture.originalPath);
19281931
});
19291932

1933+
it("retains an aged transient record while its session still has an active run", async () => {
1934+
const fixture = await createFixture(stateDir, {
1935+
messageId: null,
1936+
createdAt: new Date(Date.now() - 16 * 60 * 1000).toISOString(),
1937+
});
1938+
1939+
const checkedSessionKeys: string[] = [];
1940+
const result = await cleanupManagedOutgoingImageRecords({
1941+
stateDir,
1942+
hasActiveSessionRun: (sessionKey) => {
1943+
checkedSessionKeys.push(sessionKey);
1944+
return sessionKey === fixture.sessionKey;
1945+
},
1946+
});
1947+
1948+
expect(result).toEqual({ deletedRecordCount: 0, deletedFileCount: 0, retainedCount: 1 });
1949+
expect(checkedSessionKeys).toEqual([fixture.sessionKey]);
1950+
await expect(fs.access(fixture.originalPath)).resolves.toBeUndefined();
1951+
expect(
1952+
attachManagedImageRecordToMessage({
1953+
attachmentId: fixture.attachmentId,
1954+
sessionKey: fixture.sessionKey,
1955+
messageId: "msg-late",
1956+
updatedAt: new Date().toISOString(),
1957+
stateDir,
1958+
}),
1959+
).toBe(true);
1960+
const attached = readManagedImageRecord(fixture.attachmentId, stateDir);
1961+
expect(attached?.messageId).toBe("msg-late");
1962+
expect(attached?.retentionClass).toBe("history");
1963+
});
1964+
1965+
it("reaps an aged transient record once its session has no active run", async () => {
1966+
const fixture = await createFixture(stateDir, {
1967+
messageId: null,
1968+
createdAt: new Date(Date.now() - 16 * 60 * 1000).toISOString(),
1969+
});
1970+
1971+
const result = await cleanupManagedOutgoingImageRecords({
1972+
stateDir,
1973+
hasActiveSessionRun: () => false,
1974+
});
1975+
1976+
expect(result).toEqual({ deletedRecordCount: 1, deletedFileCount: 1, retainedCount: 0 });
1977+
expect(readManagedImageRecord(fixture.attachmentId, stateDir)).toBeNull();
1978+
await expectPathMissing(fixture.originalPath);
1979+
});
1980+
19301981
it("retries a durably claimed file deletion after a filesystem failure", async () => {
19311982
const fixture = await createFixture(stateDir);
19321983
loadSessionEntryMock.mockReturnValue({

‎src/gateway/managed-image-attachments.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -618,6 +618,7 @@ export async function cleanupManagedOutgoingMediaRecords(params?: {
618618
sessionKey?: string;
619619
agentId?: string;
620620
forceDeleteSessionRecords?: boolean;
621+
hasActiveSessionRun?: (sessionKey: string, agentId: string | undefined) => boolean;
621622
}): Promise<CleanupManagedOutgoingMediaRecordsResult> {
622623
const stateDir = params?.stateDir ?? resolveStateDir();
623624
const nowMs = params?.nowMs ?? Date.now();
@@ -674,7 +675,11 @@ export async function cleanupManagedOutgoingMediaRecords(params?: {
674675
shouldDelete = transcriptMatch === "missing";
675676
} else if (!entry.cleanupPending) {
676677
const createdAtMs = Date.parse(record.createdAt);
677-
shouldDelete = Number.isFinite(createdAtMs) && nowMs - createdAtMs >= transientMaxAgeMs;
678+
shouldDelete =
679+
Number.isFinite(createdAtMs) &&
680+
nowMs - createdAtMs >= transientMaxAgeMs &&
681+
params?.hasActiveSessionRun?.(record.sessionKey, record.agentId?.trim() || undefined) !==
682+
true;
678683
}
679684

680685
if (shouldDelete) {

‎src/gateway/server-maintenance.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ import {
3939
waitForMediaCleanupDrains,
4040
waitForMediaCleanupDrainsToSettle,
4141
} from "./server-media-cleanup-lifecycle.js";
42+
import { hasRegisteredChatRunForSessionKey } from "./server-methods/session-active-runs.js";
4243
import { PENDING_CHAT_SEND_DEDUPE_PREFIX, type DedupeEntry } from "./server-shared.js";
4344
import { formatError } from "./server-utils.js";
4445
import { setBroadcastHealthUpdate } from "./server/health-state.js";
@@ -331,7 +332,14 @@ export function startGatewayMaintenanceTimers(params: {
331332
params.runManagedOutgoingMediaGc ??
332333
(async () => {
333334
const { cleanupManagedOutgoingMediaRecords } = await import("./managed-image-attachments.js");
334-
return await cleanupManagedOutgoingMediaRecords();
335+
return await cleanupManagedOutgoingMediaRecords({
336+
hasActiveSessionRun: (sessionKey, agentId) =>
337+
hasRegisteredChatRunForSessionKey({
338+
context: { chatAbortControllers: params.chatAbortControllers },
339+
sessionKey,
340+
agentId,
341+
}),
342+
});
335343
});
336344
const managedOutgoingCleanupLoader = createLazyPromiseLoader(async () => {
337345
try {

‎src/gateway/server-methods/chat-assistant-content.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
createManagedOutgoingMediaBlocks,
1414
} from "../managed-image-attachments.js";
1515
import { formatForLog } from "../ws-log.js";
16+
import { hasRegisteredChatRunForSessionKey } from "./session-active-runs.js";
1617
import type { GatewayRequestContext } from "./types.js";
1718

1819
const MANAGED_OUTGOING_MEDIA_PATH_PREFIX = "/api/chat/media/outgoing/";
@@ -426,7 +427,7 @@ export function hasManagedOutgoingAssistantContent(
426427
export function scheduleChatHistoryManagedMediaCleanup(params: {
427428
sessionKey: string;
428429
agentId?: string;
429-
context: Pick<GatewayRequestContext, "logGateway">;
430+
context: Pick<GatewayRequestContext, "chatAbortControllers" | "logGateway">;
430431
}) {
431432
const cleanupKey =
432433
params.sessionKey === "global" && params.agentId
@@ -438,6 +439,8 @@ export function scheduleChatHistoryManagedMediaCleanup(params: {
438439
const pending = cleanupManagedOutgoingMediaRecords({
439440
sessionKey: params.sessionKey,
440441
...(params.sessionKey === "global" && params.agentId ? { agentId: params.agentId } : {}),
442+
hasActiveSessionRun: (sessionKey, agentId) =>
443+
hasRegisteredChatRunForSessionKey({ context: params.context, sessionKey, agentId }),
441444
})
442445
.then(() => undefined)
443446
.catch((error: unknown) => {

‎src/gateway/server-methods/session-active-runs.test.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
} from "../../infra/agent-run-registry.js";
1616
import {
1717
collectTrackedActiveSessionRuns,
18+
hasRegisteredChatRunForSessionKey,
1819
hasTrackedActiveSessionRun,
1920
hasVisibleActiveSessionRun,
2021
resolveVisibleActiveSessionRunState,
@@ -292,3 +293,51 @@ it("does not project an aborted embedded handle retained for cleanup as active",
292293
clearActiveEmbeddedRun(sessionId, handle, sessionKey);
293294
}
294295
});
296+
297+
it("counts settled but still registered chat runs for a session key", () => {
298+
const context = {
299+
chatAbortControllers: new Map([
300+
[
301+
"run-finalizing",
302+
{
303+
sessionKey: "agent:main:main",
304+
sessionId: "session-main",
305+
projectSessionActive: false,
306+
controlUiVisible: false,
307+
},
308+
],
309+
["run-global-work", { sessionKey: "global", agentId: "work" }],
310+
]),
311+
} as never;
312+
313+
expect(
314+
hasRegisteredChatRunForSessionKey({
315+
context,
316+
sessionKey: "agent:main:main",
317+
agentId: undefined,
318+
}),
319+
).toBe(true);
320+
expect(
321+
hasRegisteredChatRunForSessionKey({
322+
context,
323+
sessionKey: "agent:other:other",
324+
agentId: undefined,
325+
}),
326+
).toBe(false);
327+
expect(
328+
hasRegisteredChatRunForSessionKey({ context, sessionKey: "global", agentId: "work" }),
329+
).toBe(true);
330+
expect(
331+
hasRegisteredChatRunForSessionKey({ context, sessionKey: "global", agentId: "other" }),
332+
).toBe(false);
333+
expect(
334+
hasRegisteredChatRunForSessionKey({ context, sessionKey: "global", agentId: undefined }),
335+
).toBe(true);
336+
expect(
337+
hasRegisteredChatRunForSessionKey({
338+
context: {},
339+
sessionKey: "agent:main:main",
340+
agentId: undefined,
341+
}),
342+
).toBe(false);
343+
});

‎src/gateway/server-methods/session-active-runs.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,31 @@ function isTrackedActiveSessionRunForKey(
6161
: false;
6262
}
6363

64+
export function hasRegisteredChatRunForSessionKey(params: {
65+
context: Partial<Pick<GatewayRequestContext, "chatAbortControllers">>;
66+
sessionKey: string;
67+
agentId: string | undefined;
68+
}): boolean {
69+
if (!(params.context.chatAbortControllers instanceof Map)) {
70+
return false;
71+
}
72+
const requestedAgentId = params.agentId ? normalizeAgentId(params.agentId) : undefined;
73+
for (const active of params.context.chatAbortControllers.values()) {
74+
if (active.sessionKey?.trim() !== params.sessionKey) {
75+
continue;
76+
}
77+
if (params.sessionKey !== "global") {
78+
return true;
79+
}
80+
const activeAgentId =
81+
typeof active.agentId === "string" ? normalizeAgentId(active.agentId) : undefined;
82+
if (!requestedAgentId || !activeAgentId || requestedAgentId === activeAgentId) {
83+
return true;
84+
}
85+
}
86+
return false;
87+
}
88+
6489
/** Returns true when either requested or canonical session key has a visible active run. */
6590
export function hasTrackedActiveSessionRun(params: {
6691
context: Partial<Pick<GatewayRequestContext, "chatAbortControllers">>;

0 commit comments

Comments
 (0)