Skip to content

Commit 610ca42

Browse files
authored
fix(cli): publish buffered media atomically (#117934)
1 parent c8ee501 commit 610ca42

4 files changed

Lines changed: 113 additions & 25 deletions

File tree

‎docs/cli/infer.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ A good infer-based skill maps common user intents to the right subcommand, inclu
106106
- For `image describe`, `--file` accepts local paths and HTTP(S) URLs; remote URLs go through the normal media-fetch SSRF policy.
107107
- Stateless execution commands (`model run`, `image *`, `audio *`, `video *`, `web *`, `embedding *`) default to local. Gateway-managed state commands (`tts status`) default to gateway.
108108
- The local path never requires the gateway to be running.
109+
- Generated image and video `--output` files are staged beside the destination and replace it only after the complete buffer is written; a failed write leaves an existing destination unchanged.
109110
- Local `model run` is a lean one-shot provider completion: it resolves the configured agent model and auth but does not start a chat-agent turn, load tools, or open bundled MCP servers.
110111
- `model run --file` attaches image files (auto-detected MIME type) to the prompt; repeat `--file` for multiple images. Non-image files are rejected — use `infer audio transcribe` or `infer video describe` instead.
111112
- `model run --gateway` exercises Gateway routing, saved auth, provider selection, and the embedded runtime, but stays a raw model probe: no prior session transcript, bootstrap/AGENTS context, tools, or bundled MCP servers.

‎src/cli/capability-cli.test.ts‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2028,6 +2028,76 @@ describe("capability cli", () => {
20282028
}
20292029
});
20302030

2031+
it.each([
2032+
{ kind: "image", extension: ".png", original: "existing-image", byte: 0x49 },
2033+
{ kind: "video", extension: ".mp4", original: "existing-video", byte: 0x56 },
2034+
])(
2035+
"preserves an existing buffered $kind --output when publication fails",
2036+
async ({ kind, extension, original, byte }) => {
2037+
const buffer = Buffer.alloc(2_048, byte);
2038+
if (kind === "image") {
2039+
mocks.generateImage.mockResolvedValue({
2040+
provider: "openai",
2041+
model: "gpt-image-2",
2042+
attempts: [],
2043+
images: [{ buffer, mimeType: "image/png", fileName: "generated.png" }],
2044+
});
2045+
} else {
2046+
mocks.generateVideo.mockResolvedValue({
2047+
provider: "openai",
2048+
model: "sora-2",
2049+
attempts: [],
2050+
videos: [{ buffer, mimeType: "video/mp4", fileName: "generated.mp4" }],
2051+
});
2052+
}
2053+
2054+
const tempDir = tempDirs.make(`openclaw-buffered-${kind}-fail-`);
2055+
const outputBase = path.join(tempDir, "result");
2056+
const outputPath = `${outputBase}${extension}`;
2057+
await fs.writeFile(outputPath, original);
2058+
await fs.chmod(outputPath, 0o640);
2059+
2060+
const writeFile = fs.writeFile.bind(fs);
2061+
const writeFileSpy = vi.spyOn(fs, "writeFile").mockImplementation(async (...args) => {
2062+
const [filePath, data, options] = args;
2063+
if (
2064+
typeof filePath === "string" &&
2065+
Buffer.isBuffer(data) &&
2066+
data.byteLength === buffer.byteLength &&
2067+
path.dirname(filePath) === tempDir
2068+
) {
2069+
await writeFile(filePath, data.subarray(0, 17), options);
2070+
throw new Error("injected buffered media write failure");
2071+
}
2072+
await writeFile(...args);
2073+
});
2074+
2075+
try {
2076+
await expect(
2077+
runCapability(
2078+
kind,
2079+
"generate",
2080+
"--prompt",
2081+
"friendly lobster",
2082+
"--output",
2083+
outputBase,
2084+
"--json",
2085+
),
2086+
).rejects.toThrow("exit 1");
2087+
2088+
expectRuntimeErrorContains("injected buffered media write failure");
2089+
expect(mocks.runtime.writeJson).not.toHaveBeenCalled();
2090+
expect(await fs.readFile(outputPath, "utf8")).toBe(original);
2091+
if (process.platform !== "win32") {
2092+
expect((await fs.stat(outputPath)).mode & 0o777).toBe(0o640);
2093+
}
2094+
expect(await fs.readdir(tempDir)).toEqual([`result${extension}`]);
2095+
} finally {
2096+
writeFileSpy.mockRestore();
2097+
}
2098+
},
2099+
);
2100+
20312101
it("blocks private-network url-only generated video downloads by default", async () => {
20322102
mocks.loadConfig.mockReturnValue({});
20332103
primeGeneratedVideoUrl("http://127.0.0.2:40123/private-video.mp4?sig=secret-presigned-token");

‎src/cli/capability-cli/media-output.ts‎

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,41 @@
11
import fs from "node:fs/promises";
22
import path from "node:path";
33
import { detectMime, extensionForMime, normalizeMimeType } from "@openclaw/media-core/mime";
4+
import { writeSiblingTempFile } from "../../infra/sibling-temp-file.js";
45
import { saveMediaBuffer } from "../../media/store.js";
56

7+
const GENERATED_MEDIA_OUTPUT_TEMP_PREFIX = ".openclaw-media-output";
8+
9+
async function resolveExistingOutputMode(filePath: string): Promise<number | undefined> {
10+
try {
11+
return (await fs.stat(filePath)).mode & 0o7777;
12+
} catch (error) {
13+
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
14+
return undefined;
15+
}
16+
throw error;
17+
}
18+
}
19+
20+
export async function publishOutputFileAtomically<T>(params: {
21+
filePath: string;
22+
writeTemp: (tempPath: string) => Promise<T>;
23+
}): Promise<T> {
24+
const dir = path.dirname(params.filePath);
25+
await fs.mkdir(dir, { recursive: true });
26+
const mode = await resolveExistingOutputMode(params.filePath);
27+
// Stage beside the destination so producer failures never destroy prior user bytes.
28+
const { result } = await writeSiblingTempFile({
29+
dir,
30+
chmodDir: false,
31+
tempPrefix: GENERATED_MEDIA_OUTPUT_TEMP_PREFIX,
32+
...(mode === undefined ? {} : { mode }),
33+
writeTemp: params.writeTemp,
34+
resolveFinalPath: () => params.filePath,
35+
});
36+
return result;
37+
}
38+
639
export async function writeOutputAsset(params: {
740
buffer: Buffer;
841
mimeType?: string;
@@ -42,8 +75,12 @@ export async function writeOutputAsset(params: {
4275
params.outputCount <= 1
4376
? path.join(parsed.dir, `${parsed.name}${ext}`)
4477
: path.join(parsed.dir, `${parsed.name}-${String(params.outputIndex + 1)}${ext}`);
45-
await fs.mkdir(path.dirname(filePath), { recursive: true });
46-
await fs.writeFile(filePath, params.buffer);
78+
await publishOutputFileAtomically({
79+
filePath,
80+
writeTemp: async (tempPath) => {
81+
await fs.writeFile(tempPath, params.buffer, { flag: "wx" });
82+
},
83+
});
4784
return {
4885
path: filePath,
4986
mimeType: detectedNormalized ?? params.mimeType,

‎src/cli/capability-cli/video.ts‎

Lines changed: 3 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ import { getRuntimeConfig } from "../../config/config.js";
1414
import { resolveAgentModelPrimaryValue } from "../../config/model-input.js";
1515
import type { OpenClawConfig } from "../../config/types.openclaw.js";
1616
import { readResponseWithLimit } from "../../infra/http-body.js";
17-
import { writeSiblingTempFile } from "../../infra/sibling-temp-file.js";
1817
import { buildMediaUnderstandingRegistry } from "../../media-understanding/provider-registry.js";
1918
import { describeVideoFile } from "../../media-understanding/runtime.js";
2019
import { resolveGeneratedMediaMaxBytes } from "../../media/configured-max-bytes.js";
@@ -31,7 +30,7 @@ import {
3130
import type { VideoGenerationResolution } from "../../video-generation/types.js";
3231
import { runCommandWithRuntime } from "../cli-utils.js";
3332
import { getModelsCommandSecretTargetIds } from "../command-secret-targets.js";
34-
import { writeOutputAsset } from "./media-output.js";
33+
import { publishOutputFileAtomically, writeOutputAsset } from "./media-output.js";
3534
import type { CapabilityEnvelope } from "./metadata.js";
3635
import {
3736
emitJsonOrText,
@@ -45,18 +44,6 @@ import {
4544
} from "./shared.js";
4645

4746
const GENERATED_VIDEO_DOWNLOAD_TIMEOUT_MS = 120_000;
48-
const GENERATED_VIDEO_OUTPUT_TEMP_PREFIX = ".openclaw-video-output";
49-
50-
async function resolveExistingVideoOutputMode(filePath: string): Promise<number | undefined> {
51-
try {
52-
return (await fs.stat(filePath)).mode & 0o7777;
53-
} catch (error) {
54-
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
55-
return undefined;
56-
}
57-
throw error;
58-
}
59-
}
6047

6148
function normalizeVideoResolution(raw: string | undefined): VideoGenerationResolution | undefined {
6249
const normalized = raw?.trim().toUpperCase();
@@ -176,14 +163,8 @@ async function runVideoGenerate(params: {
176163
result.videos.length <= 1
177164
? path.join(parsed.dir, `${parsed.name}${ext}`)
178165
: path.join(parsed.dir, `${parsed.name}-${String(index + 1)}${ext}`);
179-
const dir = path.dirname(filePath);
180-
await fs.mkdir(dir, { recursive: true });
181-
const mode = await resolveExistingVideoOutputMode(filePath);
182-
const { result: size } = await writeSiblingTempFile({
183-
dir,
184-
chmodDir: false,
185-
tempPrefix: GENERATED_VIDEO_OUTPUT_TEMP_PREFIX,
186-
...(mode === undefined ? {} : { mode }),
166+
const size = await publishOutputFileAtomically({
167+
filePath,
187168
writeTemp: async (tempPath) => {
188169
await pipeline(
189170
Readable.fromWeb(
@@ -197,7 +178,6 @@ async function runVideoGenerate(params: {
197178
}
198179
return writtenSize;
199180
},
200-
resolveFinalPath: () => filePath,
201181
});
202182
return { path: filePath, mimeType: video.mimeType, size };
203183
}

0 commit comments

Comments
 (0)