Skip to content

Commit ba9eaf2

Browse files
authored
fix(media): retain inbound media with recursive cleanup TTL (#38292)
* Config: add media retention TTL setting * Media: recurse persisted media cleanup * Gateway: add persisted media cleanup timer * Media: harden retention cleanup sweep * Media: make recursive retention cleanup opt-in * Media: retry writes after empty-dir cleanup race
1 parent 563a125 commit ba9eaf2

11 files changed

Lines changed: 444 additions & 38 deletions

‎src/config/schema.help.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -423,9 +423,11 @@ export const FIELD_HELP: Record<string, string> = {
423423
"nodeHost.browserProxy.allowProfiles":
424424
"Optional allowlist of browser profile names exposed through node proxy routing. Leave empty to expose all configured profiles, or use a tight list to enforce least-privilege profile access.",
425425
media:
426-
"Top-level media behavior shared across providers and tools that handle inbound files. Keep defaults unless you need stable filenames for external processing pipelines.",
426+
"Top-level media behavior shared across providers and tools that handle inbound files. Keep defaults unless you need stable filenames for external processing pipelines or longer-lived inbound media retention.",
427427
"media.preserveFilenames":
428428
"When enabled, uploaded media keeps its original filename instead of a generated temp-safe name. Turn this on when downstream automations depend on stable names, and leave off to reduce accidental filename leakage.",
429+
"media.ttlHours":
430+
"Optional retention window in hours for persisted inbound media cleanup across the full media tree. Leave unset to preserve legacy behavior, or set values like 24 (1 day) or 168 (7 days) when you want automatic cleanup.",
429431
audio:
430432
"Global audio ingestion settings used before higher-level tools process speech or media content. Configure this when you need deterministic transcription behavior for voice notes and clips.",
431433
"audio.transcription":

‎src/config/schema.labels.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,7 @@ export const FIELD_LABELS: Record<string, string> = {
278278
"nodeHost.browserProxy.allowProfiles": "Node Browser Proxy Allowed Profiles",
279279
media: "Media",
280280
"media.preserveFilenames": "Preserve Media Filenames",
281+
"media.ttlHours": "Media Retention TTL (hours)",
281282
audio: "Audio",
282283
"audio.transcription": "Audio Transcription",
283284
"audio.transcription.command": "Audio Transcription Command",

‎src/config/types.openclaw.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,12 @@ export type OpenClawConfig = {
101101
bindings?: AgentBinding[];
102102
broadcast?: BroadcastConfig;
103103
audio?: AudioConfig;
104+
media?: {
105+
/** Preserve original uploaded filenames when storing inbound media. */
106+
preserveFilenames?: boolean;
107+
/** Optional retention window for persisted inbound media cleanup. */
108+
ttlHours?: number;
109+
};
104110
messages?: MessagesConfig;
105111
commands?: CommandsConfig;
106112
approvals?: ApprovalsConfig;

‎src/config/zod-schema.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -423,6 +423,12 @@ export const OpenClawSchema = z
423423
media: z
424424
.object({
425425
preserveFilenames: z.boolean().optional(),
426+
ttlHours: z
427+
.number()
428+
.int()
429+
.min(1)
430+
.max(24 * 7)
431+
.optional(),
426432
})
427433
.strict()
428434
.optional(),

‎src/gateway/server-close.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ export function createGatewayCloseHandler(params: {
2121
tickInterval: ReturnType<typeof setInterval>;
2222
healthInterval: ReturnType<typeof setInterval>;
2323
dedupeCleanup: ReturnType<typeof setInterval>;
24+
mediaCleanup: ReturnType<typeof setInterval> | null;
2425
agentUnsub: (() => void) | null;
2526
heartbeatUnsub: (() => void) | null;
2627
chatRunState: { clear: () => void };
@@ -87,6 +88,9 @@ export function createGatewayCloseHandler(params: {
8788
clearInterval(params.tickInterval);
8889
clearInterval(params.healthInterval);
8990
clearInterval(params.dedupeCleanup);
91+
if (params.mediaCleanup) {
92+
clearInterval(params.mediaCleanup);
93+
}
9094
if (params.agentUnsub) {
9195
try {
9296
params.agentUnsub();
Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
import { afterEach, describe, expect, it, vi } from "vitest";
2+
import type { HealthSummary } from "../commands/health.js";
3+
4+
const cleanOldMediaMock = vi.fn(async () => {});
5+
6+
vi.mock("../media/store.js", async (importOriginal) => {
7+
const actual = await importOriginal<typeof import("../media/store.js")>();
8+
return {
9+
...actual,
10+
cleanOldMedia: cleanOldMediaMock,
11+
};
12+
});
13+
14+
describe("startGatewayMaintenanceTimers", () => {
15+
afterEach(() => {
16+
vi.useRealTimers();
17+
vi.clearAllMocks();
18+
});
19+
20+
it("does not schedule recursive media cleanup unless ttl is configured", async () => {
21+
vi.useFakeTimers();
22+
const { startGatewayMaintenanceTimers } = await import("./server-maintenance.js");
23+
24+
const timers = startGatewayMaintenanceTimers({
25+
broadcast: () => {},
26+
nodeSendToAllSubscribed: () => {},
27+
getPresenceVersion: () => 1,
28+
getHealthVersion: () => 1,
29+
refreshGatewayHealthSnapshot: async () => ({ ok: true }) as HealthSummary,
30+
logHealth: { error: () => {} },
31+
dedupe: new Map(),
32+
chatAbortControllers: new Map(),
33+
chatRunState: { abortedRuns: new Map() },
34+
chatRunBuffers: new Map(),
35+
chatDeltaSentAt: new Map(),
36+
removeChatRun: () => undefined,
37+
agentRunSeq: new Map(),
38+
nodeSendToSession: () => {},
39+
});
40+
41+
expect(cleanOldMediaMock).not.toHaveBeenCalled();
42+
expect(timers.mediaCleanup).toBeNull();
43+
44+
clearInterval(timers.tickInterval);
45+
clearInterval(timers.healthInterval);
46+
clearInterval(timers.dedupeCleanup);
47+
});
48+
49+
it("runs startup media cleanup and repeats it hourly", async () => {
50+
vi.useFakeTimers();
51+
const { startGatewayMaintenanceTimers } = await import("./server-maintenance.js");
52+
53+
const timers = startGatewayMaintenanceTimers({
54+
broadcast: () => {},
55+
nodeSendToAllSubscribed: () => {},
56+
getPresenceVersion: () => 1,
57+
getHealthVersion: () => 1,
58+
refreshGatewayHealthSnapshot: async () => ({ ok: true }) as HealthSummary,
59+
logHealth: { error: () => {} },
60+
dedupe: new Map(),
61+
chatAbortControllers: new Map(),
62+
chatRunState: { abortedRuns: new Map() },
63+
chatRunBuffers: new Map(),
64+
chatDeltaSentAt: new Map(),
65+
removeChatRun: () => undefined,
66+
agentRunSeq: new Map(),
67+
nodeSendToSession: () => {},
68+
mediaCleanupTtlMs: 24 * 60 * 60_000,
69+
});
70+
71+
expect(cleanOldMediaMock).toHaveBeenCalledWith(24 * 60 * 60_000, {
72+
recursive: true,
73+
pruneEmptyDirs: true,
74+
});
75+
76+
cleanOldMediaMock.mockClear();
77+
await vi.advanceTimersByTimeAsync(60 * 60_000);
78+
expect(cleanOldMediaMock).toHaveBeenCalledWith(24 * 60 * 60_000, {
79+
recursive: true,
80+
pruneEmptyDirs: true,
81+
});
82+
83+
clearInterval(timers.tickInterval);
84+
clearInterval(timers.healthInterval);
85+
clearInterval(timers.dedupeCleanup);
86+
if (timers.mediaCleanup) {
87+
clearInterval(timers.mediaCleanup);
88+
}
89+
});
90+
91+
it("skips overlapping media cleanup runs", async () => {
92+
vi.useFakeTimers();
93+
let resolveCleanup = () => {};
94+
let cleanupReady = false;
95+
cleanOldMediaMock.mockImplementation(
96+
() =>
97+
new Promise<void>((resolve) => {
98+
resolveCleanup = resolve;
99+
cleanupReady = true;
100+
}),
101+
);
102+
const { startGatewayMaintenanceTimers } = await import("./server-maintenance.js");
103+
104+
const timers = startGatewayMaintenanceTimers({
105+
broadcast: () => {},
106+
nodeSendToAllSubscribed: () => {},
107+
getPresenceVersion: () => 1,
108+
getHealthVersion: () => 1,
109+
refreshGatewayHealthSnapshot: async () => ({ ok: true }) as HealthSummary,
110+
logHealth: { error: () => {} },
111+
dedupe: new Map(),
112+
chatAbortControllers: new Map(),
113+
chatRunState: { abortedRuns: new Map() },
114+
chatRunBuffers: new Map(),
115+
chatDeltaSentAt: new Map(),
116+
removeChatRun: () => undefined,
117+
agentRunSeq: new Map(),
118+
nodeSendToSession: () => {},
119+
mediaCleanupTtlMs: 24 * 60 * 60_000,
120+
});
121+
122+
expect(cleanOldMediaMock).toHaveBeenCalledTimes(1);
123+
124+
await vi.advanceTimersByTimeAsync(60 * 60_000);
125+
expect(cleanOldMediaMock).toHaveBeenCalledTimes(1);
126+
127+
if (cleanupReady) {
128+
resolveCleanup();
129+
}
130+
await Promise.resolve();
131+
132+
await vi.advanceTimersByTimeAsync(60 * 60_000);
133+
expect(cleanOldMediaMock).toHaveBeenCalledTimes(2);
134+
135+
clearInterval(timers.tickInterval);
136+
clearInterval(timers.healthInterval);
137+
clearInterval(timers.dedupeCleanup);
138+
if (timers.mediaCleanup) {
139+
clearInterval(timers.mediaCleanup);
140+
}
141+
});
142+
});

‎src/gateway/server-maintenance.ts‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { HealthSummary } from "../commands/health.js";
2+
import { cleanOldMedia } from "../media/store.js";
23
import { abortChatRunById, type ChatAbortControllerEntry } from "./chat-abort.js";
34
import type { ChatRunEntry } from "./server-chat.js";
45
import {
@@ -37,10 +38,12 @@ export function startGatewayMaintenanceTimers(params: {
3738
) => ChatRunEntry | undefined;
3839
agentRunSeq: Map<string, number>;
3940
nodeSendToSession: (sessionKey: string, event: string, payload: unknown) => void;
41+
mediaCleanupTtlMs?: number;
4042
}): {
4143
tickInterval: ReturnType<typeof setInterval>;
4244
healthInterval: ReturnType<typeof setInterval>;
4345
dedupeCleanup: ReturnType<typeof setInterval>;
46+
mediaCleanup: ReturnType<typeof setInterval> | null;
4447
} {
4548
setBroadcastHealthUpdate((snap: HealthSummary) => {
4649
params.broadcast("health", snap, {
@@ -129,5 +132,33 @@ export function startGatewayMaintenanceTimers(params: {
129132
}
130133
}, 60_000);
131134

132-
return { tickInterval, healthInterval, dedupeCleanup };
135+
if (typeof params.mediaCleanupTtlMs !== "number") {
136+
return { tickInterval, healthInterval, dedupeCleanup, mediaCleanup: null };
137+
}
138+
139+
let mediaCleanupInFlight: Promise<void> | null = null;
140+
const runMediaCleanup = () => {
141+
if (mediaCleanupInFlight) {
142+
return mediaCleanupInFlight;
143+
}
144+
mediaCleanupInFlight = cleanOldMedia(params.mediaCleanupTtlMs, {
145+
recursive: true,
146+
pruneEmptyDirs: true,
147+
})
148+
.catch((err) => {
149+
params.logHealth.error(`media cleanup failed: ${formatError(err)}`);
150+
})
151+
.finally(() => {
152+
mediaCleanupInFlight = null;
153+
});
154+
return mediaCleanupInFlight;
155+
};
156+
157+
const mediaCleanup = setInterval(() => {
158+
void runMediaCleanup();
159+
}, 60 * 60_000);
160+
161+
void runMediaCleanup();
162+
163+
return { tickInterval, healthInterval, dedupeCleanup, mediaCleanup };
133164
}

‎src/gateway/server.impl.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,17 @@ export { __resetModelCatalogCacheForTest } from "./server-model-catalog.js";
119119

120120
ensureOpenClawCliOnPath();
121121

122+
const MAX_MEDIA_TTL_HOURS = 24 * 7;
123+
124+
function resolveMediaCleanupTtlMs(ttlHoursRaw: number): number {
125+
const ttlHours = Math.min(Math.max(ttlHoursRaw, 1), MAX_MEDIA_TTL_HOURS);
126+
const ttlMs = ttlHours * 60 * 60_000;
127+
if (!Number.isFinite(ttlMs) || !Number.isSafeInteger(ttlMs)) {
128+
throw new Error(`Invalid media.ttlHours: ${String(ttlHoursRaw)}`);
129+
}
130+
return ttlMs;
131+
}
132+
122133
const log = createSubsystemLogger("gateway");
123134
const logCanvas = log.child("canvas");
124135
const logDiscovery = log.child("discovery");
@@ -680,8 +691,9 @@ export async function startGatewayServer(
680691
let tickInterval = noopInterval();
681692
let healthInterval = noopInterval();
682693
let dedupeCleanup = noopInterval();
694+
let mediaCleanup: ReturnType<typeof setInterval> | null = null;
683695
if (!minimalTestGateway) {
684-
({ tickInterval, healthInterval, dedupeCleanup } = startGatewayMaintenanceTimers({
696+
({ tickInterval, healthInterval, dedupeCleanup, mediaCleanup } = startGatewayMaintenanceTimers({
685697
broadcast,
686698
nodeSendToAllSubscribed,
687699
getPresenceVersion,
@@ -696,6 +708,9 @@ export async function startGatewayServer(
696708
removeChatRun,
697709
agentRunSeq,
698710
nodeSendToSession,
711+
...(typeof cfgAtStart.media?.ttlHours === "number"
712+
? { mediaCleanupTtlMs: resolveMediaCleanupTtlMs(cfgAtStart.media.ttlHours) }
713+
: {}),
699714
}));
700715
}
701716

@@ -1002,6 +1017,7 @@ export async function startGatewayServer(
10021017
tickInterval,
10031018
healthInterval,
10041019
dedupeCleanup,
1020+
mediaCleanup,
10051021
agentUnsub,
10061022
heartbeatUnsub,
10071023
chatRunState,

‎src/media/server.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ export function attachMediaRoutes(
9696

9797
// periodic cleanup
9898
setInterval(() => {
99-
void cleanOldMedia(ttlMs);
99+
void cleanOldMedia(ttlMs, { recursive: false });
100100
}, ttlMs).unref();
101101
}
102102

0 commit comments

Comments
 (0)