Skip to content

Commit 5739f42

Browse files
authored
fix(nodes): preserve screen output on write failure (#117973)
* fix(nodes): publish screen output atomically Closes #117970 * fix(nodes): keep output schema unchanged
1 parent dea6fb3 commit 5739f42

7 files changed

Lines changed: 71 additions & 8 deletions

File tree

‎docs/cli/nodes.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ openclaw nodes screen record --node <id> --duration 10s --fps 10 --out ./clip.mp
7676
- `push` sends an APNs test push to an iOS node. Options: `--title <text>` (default `OpenClaw`), `--body <text>`, `--environment <sandbox|production>` to override the detected APNs environment. Accepted delivery exits `0`; a typed APNs rejection preserves the complete text or JSON diagnostic and exits non-zero.
7777
- `location get` fetches the node's current location. Options: `--max-age <ms>` (reuse a cached fix), `--accuracy <coarse|balanced|precise>`, `--location-timeout <ms>` (default `10000`), `--invoke-timeout <ms>` (default `20000`).
7878
- `screen record` captures a short clip and prints the saved path (or writes JSON with `--json`). Options: `--screen <index>` (default `0`), `--duration <ms|10s>` (default `10000`), `--fps <fps>` (default `10`), `--no-audio`, `--out <path>`, `--invoke-timeout <ms>` (default `120000`).
79+
- Explicit screen output paths are staged beside the destination and replace it only after a complete write; a failed write leaves an existing file unchanged.
7980

8081
Camera and Canvas commands have their own docs: [Camera nodes](/nodes/camera), [Canvas](/platforms/mac/canvas). Canvas is implemented by the bundled experimental Canvas plugin; core keeps `openclaw nodes canvas` as a compatibility mount point.
8182

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,8 @@ import { getImageMetadata } from "../../media/media-services.js";
2828
import { defaultRuntime } from "../../runtime.js";
2929
import { runCommandWithRuntime } from "../cli-utils.js";
3030
import { getModelsCommandSecretTargetIds } from "../command-secret-targets.js";
31+
import { readInputFiles, writeOutputAsset } from "../media-output.js";
3132
import { collectOption } from "../program/helpers.js";
32-
import { readInputFiles, writeOutputAsset } from "./media-output.js";
3333
import { isMissingMediaUnderstandingProvider } from "./media-understanding-result.js";
3434
import type { CapabilityEnvelope } from "./metadata.js";
3535
import {

‎src/cli/capability-cli/tts-runtime.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ import {
2525
textToSpeech,
2626
} from "../../tts/tts.js";
2727
import { getTtsCommandSecretTargetIds } from "../command-secret-targets.js";
28-
import { publishOutputFileAtomically } from "./media-output.js";
28+
import { publishOutputFileAtomically } from "../media-output.js";
2929
import type { CapabilityEnvelope, CapabilityTransport } from "./metadata.js";
3030
import {
3131
pinRuntimeConfigSnapshot,

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ import {
3030
import type { VideoGenerationResolution } from "../../video-generation/types.js";
3131
import { runCommandWithRuntime } from "../cli-utils.js";
3232
import { getModelsCommandSecretTargetIds } from "../command-secret-targets.js";
33-
import { publishOutputFileAtomically, writeOutputAsset } from "./media-output.js";
33+
import { publishOutputFileAtomically, writeOutputAsset } from "../media-output.js";
3434
import type { CapabilityEnvelope } from "./metadata.js";
3535
import {
3636
emitJsonOrText,
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
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";
5-
import { saveMediaBuffer } from "../../media/store.js";
4+
import { writeSiblingTempFile } from "../infra/sibling-temp-file.js";
5+
import { saveMediaBuffer } from "../media/store.js";
66

77
const GENERATED_MEDIA_OUTPUT_TEMP_PREFIX = ".openclaw-media-output";
88

‎src/cli/nodes-camera.test.ts‎

Lines changed: 57 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ import {
88
} from "../test-utils/camera-url-test-helpers.js";
99
import { withTempDir } from "../test-utils/temp-dir.js";
1010

11+
type PublishOutputFileAtomically = typeof import("./media-output.js").publishOutputFileAtomically;
12+
1113
const fetchGuardMocks = vi.hoisted(() => ({
1214
fetchWithSsrFGuard: vi.fn(
1315
async (params: { url: string; timeoutMs?: number; requireHttps?: boolean }) => {
@@ -20,10 +22,25 @@ const fetchGuardMocks = vi.hoisted(() => ({
2022
),
2123
}));
2224

25+
const mediaOutputMocks = vi.hoisted(() => ({
26+
publishOutputFileAtomically: vi.fn<PublishOutputFileAtomically>(),
27+
}));
28+
2329
vi.mock("../infra/net/fetch-guard.js", () => ({
2430
fetchWithSsrFGuard: fetchGuardMocks.fetchWithSsrFGuard,
2531
}));
2632

33+
vi.mock("./media-output.js", async () => {
34+
const actual = await vi.importActual<typeof import("./media-output.js")>("./media-output.js");
35+
mediaOutputMocks.publishOutputFileAtomically.mockImplementation(
36+
actual.publishOutputFileAtomically,
37+
);
38+
return {
39+
...actual,
40+
publishOutputFileAtomically: mediaOutputMocks.publishOutputFileAtomically,
41+
};
42+
});
43+
2744
let cameraTempPath: typeof import("./nodes-camera.js").cameraTempPath;
2845
let parseCameraClipPayload: typeof import("./nodes-camera.js").parseCameraClipPayload;
2946
let parseCameraSnapPayload: typeof import("./nodes-camera.js").parseCameraSnapPayload;
@@ -39,6 +56,7 @@ let screenSnapshotFormatForPath: typeof import("./nodes-screen.js").screenSnapsh
3956
let screenSnapshotTempPath: typeof import("./nodes-screen.js").screenSnapshotTempPath;
4057
let writeScreenRecordToFile: typeof import("./nodes-screen.js").writeScreenRecordToFile;
4158
let writeScreenSnapshotToFile: typeof import("./nodes-screen.js").writeScreenSnapshotToFile;
59+
let publishOutputFileAtomically: PublishOutputFileAtomically;
4260

4361
async function withCameraTempDir<T>(run: (dir: string) => Promise<T>): Promise<T> {
4462
return await withTempDir("openclaw-test-", run);
@@ -94,6 +112,7 @@ describe("nodes camera helpers", () => {
94112
writeScreenRecordToFile,
95113
writeScreenSnapshotToFile,
96114
} = await import("./nodes-screen.js"));
115+
({ publishOutputFileAtomically } = await vi.importActual("./media-output.js"));
97116
});
98117

99118
beforeEach(() => {
@@ -258,11 +277,47 @@ describe("nodes camera helpers", () => {
258277
).rejects.toThrow(/node remoteip/i);
259278
});
260279

261-
it("normalizes valid base64 before writing", async () => {
280+
it("normalizes valid base64 and preserves the destination mode", async () => {
262281
await withCameraTempDir(async (dir) => {
263282
const out = path.join(dir, "x.bin");
283+
await fs.writeFile(out, "existing-screen");
284+
await fs.chmod(out, 0o640);
285+
264286
await writeBase64ToFile(out, " aGk\n");
265-
await expect(readFileUtf8AndCleanup(out)).resolves.toBe("hi");
287+
288+
await expect(fs.readFile(out, "utf8")).resolves.toBe("hi");
289+
if (process.platform !== "win32") {
290+
expect((await fs.stat(out)).mode & 0o777).toBe(0o640);
291+
}
292+
expect(await fs.readdir(dir)).toEqual(["x.bin"]);
293+
});
294+
});
295+
296+
it("preserves an existing output when the decoded media write fails", async () => {
297+
await withCameraTempDir(async (dir) => {
298+
const out = path.join(dir, "x.bin");
299+
await fs.writeFile(out, "existing-screen");
300+
await fs.chmod(out, 0o640);
301+
mediaOutputMocks.publishOutputFileAtomically.mockImplementationOnce(async (params) => {
302+
return await publishOutputFileAtomically({
303+
...params,
304+
writeTemp: async (tempPath) => {
305+
await params.writeTemp(tempPath);
306+
await fs.truncate(tempPath, 1);
307+
throw new Error("injected node media write failure");
308+
},
309+
});
310+
});
311+
312+
await expect(writeScreenRecordToFile(out, "aGk=")).rejects.toThrow(
313+
"injected node media write failure",
314+
);
315+
316+
await expect(fs.readFile(out, "utf8")).resolves.toBe("existing-screen");
317+
if (process.platform !== "win32") {
318+
expect((await fs.stat(out)).mode & 0o777).toBe(0o640);
319+
}
320+
expect(await fs.readdir(dir)).toEqual(["x.bin"]);
266321
});
267322
});
268323

‎src/cli/nodes-camera.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { toErrorObject } from "../infra/errors.js";
77
import { fetchWithSsrFGuard } from "../infra/net/fetch-guard.js";
88
import { normalizeHostname } from "../infra/net/hostname.js";
99
import { resolveCliName } from "./cli-name.js";
10+
import { publishOutputFileAtomically } from "./media-output.js";
1011
import {
1112
asBoolean,
1213
asNumber,
@@ -254,7 +255,13 @@ export async function writeBase64ToFile(
254255
if (buf.length > maxBytes) {
255256
throw new Error(`writeBase64ToFile: decoded ${buf.length} bytes, exceeds max ${maxBytes}`);
256257
}
257-
await fs.writeFile(filePath, buf);
258+
await fs.stat(path.dirname(filePath));
259+
await publishOutputFileAtomically({
260+
filePath,
261+
writeTemp: async (tempPath) => {
262+
await fs.writeFile(tempPath, buf, { flag: "wx" });
263+
},
264+
});
258265
return { path: filePath, bytes: buf.length };
259266
}
260267

0 commit comments

Comments
 (0)