From 3339cb8ddab30f10d6082d60c384300fdc8d1763 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Wed, 25 Nov 2026 03:54:44 +0000 Subject: [PATCH 01/17] fix(parsers): media paths resolve to absolute paths, and only http(s) skip the literal-name check (#8740) * fix(parsers): media paths resolve to absolute paths, and only http(s) skip the literal-name check * chore(skills): regenerate the skills manifest for the literal-name check * chore(parsers): raise the unpacked size budget to what the absolute resolver measures * chore(skills): regenerate the skills manifest after merging main * chore(skills): regenerate the skills manifest after merging main * chore(skills): regenerate the skills manifest after merging main --- .../src/media-use/lib/literal-media-input.mjs | 5 ++--- packages/parsers/src/assetResolution.test.ts | 17 +++++++++++++- packages/parsers/src/assetResolution.ts | 6 +++-- .../parsers/src/literalMediaInput.test.ts | 22 +++++++++++++++++++ packages/parsers/src/literalMediaInput.ts | 5 ++--- skills-manifest.json | 6 ++--- .../figma/scripts/lib/literal-media-input.mjs | 5 ++--- .../scripts/lib/literal-media-input.mjs | 5 ++--- .../scripts/literal-media-paths.test.mjs | 17 ++++++++++++-- .../scripts/lib/literal-media-input.mjs | 5 ++--- 10 files changed, 70 insertions(+), 23 deletions(-) create mode 100644 packages/parsers/src/literalMediaInput.test.ts diff --git a/packages/cli/src/media-use/lib/literal-media-input.mjs b/packages/cli/src/media-use/lib/literal-media-input.mjs index 85840a06af..a9293fb008 100644 --- a/packages/cli/src/media-use/lib/literal-media-input.mjs +++ b/packages/cli/src/media-use/lib/literal-media-input.mjs @@ -1,15 +1,14 @@ // The standalone twin of assertLiteralMediaInput in packages/parsers/src/literalMediaInput.ts, for inputs and outputs; a test keeps them equal. const PATTERN_IMAGE2_EXPANDS = /%\d*[d%*?[\]{}]/; const WILDCARD_MAKES_ANY_PERCENT_A_PATTERN = /[*?[{]/; -const URL_SCHEME = /^[a-z][a-z0-9+.-]+:/i; +const FORWARDED = /^https?:/i; /** ffmpeg's image2 reader or writer would use other files, folders included, than the one named. */ export function assertLiteralMediaPath(input) { - const local = !URL_SCHEME.test(input) || /^file:/i.test(input); const pattern = PATTERN_IMAGE2_EXPANDS.test(input) || (input.includes("%") && WILDCARD_MAKES_ANY_PERCENT_A_PATTERN.test(input)); - if (!local || !pattern) return; + if (FORWARDED.test(input) || !pattern) return; throw new Error( `[FFmpeg] refused media path "${input.split(/[\\/]/).pop()}": a "%" followed by "d", another "%" or a wildcard, ` + 'with or without digits between, or a "%" and a wildcard (*, ?, [ or {) anywhere in the path, would make ffmpeg ' + diff --git a/packages/parsers/src/assetResolution.test.ts b/packages/parsers/src/assetResolution.test.ts index c01a9e34b3..f1592bbc9f 100644 --- a/packages/parsers/src/assetResolution.test.ts +++ b/packages/parsers/src/assetResolution.test.ts @@ -2,7 +2,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { execFileSync } from "node:child_process"; import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { join, posix, win32 } from "node:path"; +import { isAbsolute, join, posix, resolve, win32 } from "node:path"; import { pathToFileURL } from "node:url"; import { collectSubCompositionSrcs, @@ -143,6 +143,21 @@ describe("collectSubCompositionSrcs", () => { // The browser clamps `..` at the origin root; path.join does not. One resolver must serve lint and render. describe("resolveProjectRelativeSrc — the one src resolver for lint and render", () => { + // fails without the fix: with "." as the base the join stayed relative, so a src such as concat:a.wav|b.wav led + // the path ffmpeg was handed, and ffmpeg read it as its concat protocol instead of a project file. + it("returns an absolute path whatever base the caller passed", () => { + for (const base of [".", "./", ""]) + for (const src of [ + "concat:a.wav|b.wav", + "subfile,,start,0,end,1,,:clip.mp4", + "assets/clip.mp4", + ]) { + const path = resolveProjectRelativeSrc(src, base, base && `${base}/compiled`); + expect(isAbsolute(path)).toBe(true); + expect(path.startsWith(resolve(base))).toBe(true); + } + }); + let tmp: string; beforeAll(() => { diff --git a/packages/parsers/src/assetResolution.ts b/packages/parsers/src/assetResolution.ts index 7051480ab7..b3be7118c1 100644 --- a/packages/parsers/src/assetResolution.ts +++ b/packages/parsers/src/assetResolution.ts @@ -230,9 +230,11 @@ function gitBashFile(src: string): string | undefined { /** Resolves a media `src` like a browser URL (`..` clamps at the project root); a miss returns the base-dir join. */ export function resolveProjectRelativeSrc( src: string, - baseDir: string, - compiledDir?: string, + relativeOrAbsoluteBase: string, + relativeOrAbsoluteCompiled?: string, ): string { + const baseDir = resolve(relativeOrAbsoluteBase); + const compiledDir = relativeOrAbsoluteCompiled && resolve(relativeOrAbsoluteCompiled); const cleanSrc = fileUrlAsPath(cleanAssetUrl(src)); // A leading slash is an origin-root URL served from the project root, unless the absolute path exists. diff --git a/packages/parsers/src/literalMediaInput.test.ts b/packages/parsers/src/literalMediaInput.test.ts new file mode 100644 index 0000000000..e69d3940d8 --- /dev/null +++ b/packages/parsers/src/literalMediaInput.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from "vitest"; +import { assertLiteralMediaInput, assertLiteralMediaOutput } from "./literalMediaInput.js"; + +describe("assertLiteralMediaInput", () => { + // fails without the fix: every scheme but file: skipped the check, as if another check had vetted it. + it("checks a scheme-led name as a local one; only http and https are left to the caller", () => { + for (const path of [ + "concat:/a/b%d.png", + "subfile,,start,0,end,0,,:/a/b%d.png", + "data:/a%d.png", + ]) { + expect(() => assertLiteralMediaInput(path)).toThrow(/pattern of other files/); + expect(() => assertLiteralMediaOutput(path)).toThrow(/pattern of other files/); + } + for (const path of [ + "https://cdn.example/a%2d.png", + "HTTP://cdn.example/a%2d.png", + "/a/clip.mp4", + ]) + expect(() => assertLiteralMediaInput(path)).not.toThrow(); + }); +}); diff --git a/packages/parsers/src/literalMediaInput.ts b/packages/parsers/src/literalMediaInput.ts index f9674f44d8..ff028d460c 100644 --- a/packages/parsers/src/literalMediaInput.ts +++ b/packages/parsers/src/literalMediaInput.ts @@ -1,13 +1,12 @@ const PATTERN_IMAGE2_EXPANDS = /%\d*[d%*?[\]{}]/; const WILDCARD_MAKES_ANY_PERCENT_A_PATTERN = /[*?[{]/; -const URL_SCHEME = /^[a-z][a-z0-9+.-]+:/i; +const FORWARDED = /^https?:/i; function refusePattern(path: string, use: "read" | "write"): void { - const local = !URL_SCHEME.test(path) || /^file:/i.test(path); const pattern = PATTERN_IMAGE2_EXPANDS.test(path) || (path.includes("%") && WILDCARD_MAKES_ANY_PERCENT_A_PATTERN.test(path)); - if (!local || !pattern) return; + if (FORWARDED.test(path) || !pattern) return; throw new Error( `[FFmpeg] refused media path "${path.split(/[\\/]/).pop()}": a "%" followed by "d", another "%" or a wildcard, ` + `with or without digits between, or a "%" and a wildcard (*, ?, [ or {) anywhere in the path, would make ffmpeg ` + diff --git a/skills-manifest.json b/skills-manifest.json index dc61115497..f24d995e74 100644 --- a/skills-manifest.json +++ b/skills-manifest.json @@ -2,11 +2,11 @@ "source": "heygen-com/hyperframes", "skills": { "figma": { - "hash": "b1facb484ca64802", + "hash": "aee1018803b57ea3", "files": 4 }, "hyperframes": { - "hash": "1ebf5a311a4d1ed7", + "hash": "7b9108a831fc740a", "files": 85 }, "hyperframes-cli": { @@ -18,7 +18,7 @@ "files": 13 }, "media-use": { - "hash": "ff2fa3c4eb8a7bc1", + "hash": "fff20d7c6efcc737", "files": 135 }, "remotion-to-hyperframes": { diff --git a/skills/figma/scripts/lib/literal-media-input.mjs b/skills/figma/scripts/lib/literal-media-input.mjs index 85840a06af..a9293fb008 100644 --- a/skills/figma/scripts/lib/literal-media-input.mjs +++ b/skills/figma/scripts/lib/literal-media-input.mjs @@ -1,15 +1,14 @@ // The standalone twin of assertLiteralMediaInput in packages/parsers/src/literalMediaInput.ts, for inputs and outputs; a test keeps them equal. const PATTERN_IMAGE2_EXPANDS = /%\d*[d%*?[\]{}]/; const WILDCARD_MAKES_ANY_PERCENT_A_PATTERN = /[*?[{]/; -const URL_SCHEME = /^[a-z][a-z0-9+.-]+:/i; +const FORWARDED = /^https?:/i; /** ffmpeg's image2 reader or writer would use other files, folders included, than the one named. */ export function assertLiteralMediaPath(input) { - const local = !URL_SCHEME.test(input) || /^file:/i.test(input); const pattern = PATTERN_IMAGE2_EXPANDS.test(input) || (input.includes("%") && WILDCARD_MAKES_ANY_PERCENT_A_PATTERN.test(input)); - if (!local || !pattern) return; + if (FORWARDED.test(input) || !pattern) return; throw new Error( `[FFmpeg] refused media path "${input.split(/[\\/]/).pop()}": a "%" followed by "d", another "%" or a wildcard, ` + 'with or without digits between, or a "%" and a wildcard (*, ?, [ or {) anywhere in the path, would make ffmpeg ' + diff --git a/skills/hyperframes/scripts/lib/literal-media-input.mjs b/skills/hyperframes/scripts/lib/literal-media-input.mjs index 85840a06af..a9293fb008 100644 --- a/skills/hyperframes/scripts/lib/literal-media-input.mjs +++ b/skills/hyperframes/scripts/lib/literal-media-input.mjs @@ -1,15 +1,14 @@ // The standalone twin of assertLiteralMediaInput in packages/parsers/src/literalMediaInput.ts, for inputs and outputs; a test keeps them equal. const PATTERN_IMAGE2_EXPANDS = /%\d*[d%*?[\]{}]/; const WILDCARD_MAKES_ANY_PERCENT_A_PATTERN = /[*?[{]/; -const URL_SCHEME = /^[a-z][a-z0-9+.-]+:/i; +const FORWARDED = /^https?:/i; /** ffmpeg's image2 reader or writer would use other files, folders included, than the one named. */ export function assertLiteralMediaPath(input) { - const local = !URL_SCHEME.test(input) || /^file:/i.test(input); const pattern = PATTERN_IMAGE2_EXPANDS.test(input) || (input.includes("%") && WILDCARD_MAKES_ANY_PERCENT_A_PATTERN.test(input)); - if (!local || !pattern) return; + if (FORWARDED.test(input) || !pattern) return; throw new Error( `[FFmpeg] refused media path "${input.split(/[\\/]/).pop()}": a "%" followed by "d", another "%" or a wildcard, ` + 'with or without digits between, or a "%" and a wildcard (*, ?, [ or {) anywhere in the path, would make ffmpeg ' + diff --git a/skills/hyperframes/scripts/literal-media-paths.test.mjs b/skills/hyperframes/scripts/literal-media-paths.test.mjs index 7f1708c99d..e6c127fd2c 100644 --- a/skills/hyperframes/scripts/literal-media-paths.test.mjs +++ b/skills/hyperframes/scripts/literal-media-paths.test.mjs @@ -35,7 +35,11 @@ test("the standalone check refuses exactly what the parsers check refuses", () = script("skills/hyperframes/scripts/lib/literal-media-input.mjs"), "utf8", ); - for (const name of ["PATTERN_IMAGE2_EXPANDS", "WILDCARD_MAKES_ANY_PERCENT_A_PATTERN"]) { + for (const name of [ + "PATTERN_IMAGE2_EXPANDS", + "WILDCARD_MAKES_ANY_PERCENT_A_PATTERN", + "FORWARDED", + ]) { const pattern = (text) => new RegExp(`const ${name} = (.+);`).exec(text)?.[1]; assert.ok(pattern(source), name); assert.equal(pattern(ours), pattern(source), name); @@ -46,10 +50,19 @@ test("the standalone check refuses exactly what the parsers check refuses", () = "file:/a/b%%.png", "/a/credentials.json%a{.xface", "/a/x{/y%a.png", + "concat:/a/b%d.png", + "subfile,,start,0,end,0,,:/a/b%d.png", + "data:/a%d.png", + "crypto:/a/b%d.png", ]) { assert.throws(() => assertLiteralMediaPath(path), PATTERN); } - for (const path of ["/a/100% done.mp4", "/a/x{y}.png", "https://cdn.example/a%2d.png"]) { + for (const path of [ + "/a/100% done.mp4", + "/a/x{y}.png", + "https://cdn.example/a%2d.png", + "http://cdn.example/a%2d.png", + ]) { assert.doesNotThrow(() => assertLiteralMediaPath(path)); } }); diff --git a/skills/media-use/scripts/lib/literal-media-input.mjs b/skills/media-use/scripts/lib/literal-media-input.mjs index 85840a06af..a9293fb008 100644 --- a/skills/media-use/scripts/lib/literal-media-input.mjs +++ b/skills/media-use/scripts/lib/literal-media-input.mjs @@ -1,15 +1,14 @@ // The standalone twin of assertLiteralMediaInput in packages/parsers/src/literalMediaInput.ts, for inputs and outputs; a test keeps them equal. const PATTERN_IMAGE2_EXPANDS = /%\d*[d%*?[\]{}]/; const WILDCARD_MAKES_ANY_PERCENT_A_PATTERN = /[*?[{]/; -const URL_SCHEME = /^[a-z][a-z0-9+.-]+:/i; +const FORWARDED = /^https?:/i; /** ffmpeg's image2 reader or writer would use other files, folders included, than the one named. */ export function assertLiteralMediaPath(input) { - const local = !URL_SCHEME.test(input) || /^file:/i.test(input); const pattern = PATTERN_IMAGE2_EXPANDS.test(input) || (input.includes("%") && WILDCARD_MAKES_ANY_PERCENT_A_PATTERN.test(input)); - if (!local || !pattern) return; + if (FORWARDED.test(input) || !pattern) return; throw new Error( `[FFmpeg] refused media path "${input.split(/[\\/]/).pop()}": a "%" followed by "d", another "%" or a wildcard, ` + 'with or without digits between, or a "%" and a wildcard (*, ?, [ or {) anywhere in the path, would make ffmpeg ' + From 182716eaa6fcff7dc49841f865ed8f758bf829ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Wed, 25 Nov 2026 04:25:54 +0000 Subject: [PATCH 02/17] fix(engine): read only the host's own cgroup layout for memory and CPU limits (#8803) --- .../engine/src/services/systemMemory.test.ts | 78 ++++++++++++++++++- packages/engine/src/services/systemMemory.ts | 32 ++++---- 2 files changed, 91 insertions(+), 19 deletions(-) diff --git a/packages/engine/src/services/systemMemory.test.ts b/packages/engine/src/services/systemMemory.test.ts index 2da2f103b5..5a565316fa 100644 --- a/packages/engine/src/services/systemMemory.test.ts +++ b/packages/engine/src/services/systemMemory.test.ts @@ -15,11 +15,15 @@ import { const BYTES_PER_MIB = 1024 * 1024; const CGROUP_V2_MEMORY_MAX_PATH = "/sys/fs/cgroup/memory.max"; const CGROUP_V1_MEMORY_LIMIT_PATH = "/sys/fs/cgroup/memory/memory.limit_in_bytes"; +const CGROUP_V2_CONTROLLERS_PATH = "/sys/fs/cgroup/cgroup.controllers"; +const CGROUP_V1_CPU_QUOTA_PATH = "/sys/fs/cgroup/cpu/cpu.cfs_quota_us"; +const CGROUP_V1_CPU_PERIOD_PATH = "/sys/fs/cgroup/cpu/cpu.cfs_period_us"; type SystemMemoryModule = typeof import("./systemMemory.js"); type MockSystemMemoryOptions = { availableParallelism?: number; + cgroupVersion?: 1 | 2; hostCpus?: number; files?: Record; hostTotalMb?: number; @@ -46,14 +50,20 @@ async function withSystemMemoryMocks( ): Promise { const { availableParallelism = 32, + cgroupVersion = 2, hostCpus = 32, - files = {}, + files: layoutFiles = {}, hostTotalMb = 32768, platform = "linux", readErrors = {}, onRead, throwOnFileRead = false, } = options; + // The same object, so a test can change a file between probes. + const files = + cgroupVersion === 2 + ? Object.assign(layoutFiles, { [CGROUP_V2_CONTROLLERS_PATH]: "cpu memory" }) + : layoutFiles; const restorePlatform = stubPlatform(platform); vi.resetModules(); @@ -198,6 +208,58 @@ describe("getCgroupCpuLimit", () => { expect(getCgroupCpuLimit()).toBeNull(), ); }); + + it("reads the quota over its period on a cgroup v1 host", async () => { + await withSystemMemoryMocks( + { + cgroupVersion: 1, + files: { [CGROUP_V1_CPU_QUOTA_PATH]: "200000", [CGROUP_V1_CPU_PERIOD_PATH]: "100000" }, + }, + ({ getCgroupCpuLimit }) => expect(getCgroupCpuLimit()).toBe(2), + ); + }); +}); + +describe("a cgroup v2 host with no limit at its root", () => { + // On v2, /sys/fs/cgroup/cpu and /sys/fs/cgroup/memory are child cgroups, not v1 controllers. + const unreadable = Object.assign(new Error("permission denied"), { code: "EACCES" }); + + it("never reads v1 paths, so finds no limit and warns about nothing", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const readCalls: string[] = []; + await withSystemMemoryMocks( + { + readErrors: { + [CGROUP_V1_CPU_QUOTA_PATH]: unreadable, + [CGROUP_V1_CPU_PERIOD_PATH]: unreadable, + [CGROUP_V1_MEMORY_LIMIT_PATH]: unreadable, + }, + onRead: (path) => readCalls.push(path), + }, + ({ getCgroupCpuLimit, getCgroupMemoryLimitMb }) => { + expect(getCgroupCpuLimit()).toBeNull(); + expect(getCgroupMemoryLimitMb()).toBeNull(); + expect(readCalls).not.toContain(CGROUP_V1_CPU_QUOTA_PATH); + expect(readCalls).not.toContain(CGROUP_V1_MEMORY_LIMIT_PATH); + expect(warn).not.toHaveBeenCalled(); + }, + ); + }); + + it("names the CPU file it could not read, not a memory limit", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + await withSystemMemoryMocks( + { readErrors: { "/sys/fs/cgroup/cpu.max": unreadable } }, + ({ getCgroupCpuLimit }) => { + expect(getCgroupCpuLimit()).toBeNull(); + expect(warn).toHaveBeenCalledTimes(1); + expect(warn.mock.calls[0]?.[0]).toContain( + "[SystemMemory] Unable to read /sys/fs/cgroup/cpu.max (EACCES", + ); + expect(warn.mock.calls[0]?.[0]).not.toContain("memory"); + }, + ); + }); }); describe("usableCpuCount under a CPU quota", () => { @@ -305,13 +367,18 @@ describe("getSystemTotalMb", () => { ({ _resetCgroupLimitCacheForTests, getSystemTotalMb }) => { expect(getSystemTotalMb()).toBe(4096); expect(getSystemTotalMb()).toBe(4096); - expect(readCalls).toEqual([CGROUP_V2_MEMORY_MAX_PATH]); + expect(readCalls).toEqual([CGROUP_V2_CONTROLLERS_PATH, CGROUP_V2_MEMORY_MAX_PATH]); files[CGROUP_V2_MEMORY_MAX_PATH] = `${2048 * BYTES_PER_MIB}`; _resetCgroupLimitCacheForTests(); expect(getSystemTotalMb()).toBe(2048); - expect(readCalls).toEqual([CGROUP_V2_MEMORY_MAX_PATH, CGROUP_V2_MEMORY_MAX_PATH]); + expect(readCalls).toEqual([ + CGROUP_V2_CONTROLLERS_PATH, + CGROUP_V2_MEMORY_MAX_PATH, + CGROUP_V2_CONTROLLERS_PATH, + CGROUP_V2_MEMORY_MAX_PATH, + ]); }, ); }); @@ -333,6 +400,7 @@ describe("getSystemTotalMb", () => { it("honors cgroup v1 numeric limits when cgroup v2 is absent", async () => { await withSystemMemoryMocks( { + cgroupVersion: 1, files: { [CGROUP_V1_MEMORY_LIMIT_PATH]: `${6144 * BYTES_PER_MIB}`, }, @@ -347,6 +415,7 @@ describe("getSystemTotalMb", () => { it("uses the host total when cgroup v1 reports a no-limit sentinel", async () => { await withSystemMemoryMocks( { + cgroupVersion: 1, files: { [CGROUP_V1_MEMORY_LIMIT_PATH]: "9223372036854771712", }, @@ -381,7 +450,7 @@ describe("getSystemTotalMb", () => { expect(isLowMemorySystem()).toBe(false); expect(warn).toHaveBeenCalledTimes(1); expect(warn.mock.calls[0]?.[0]).toContain( - "[SystemMemory] Unable to read cgroup memory limit", + `[SystemMemory] Unable to read ${CGROUP_V2_MEMORY_MAX_PATH} (`, ); expect(warn.mock.calls[0]?.[0]).toContain("EACCES"); }, @@ -440,6 +509,7 @@ describe("getSystemTotalMb", () => { async (content) => { await withSystemMemoryMocks( { + cgroupVersion: 1, files: { [CGROUP_V1_MEMORY_LIMIT_PATH]: content, }, diff --git a/packages/engine/src/services/systemMemory.ts b/packages/engine/src/services/systemMemory.ts index a4d22f6356..28986e38c2 100644 --- a/packages/engine/src/services/systemMemory.ts +++ b/packages/engine/src/services/systemMemory.ts @@ -22,6 +22,7 @@ const BYTES_PER_MIB_BIGINT = BigInt(BYTES_PER_MIB); // slice (e.g. /sys/fs/cgroup/user.slice/.../memory.max) that these root paths // don't see, and that's acceptable — bare hosts are covered by total-RAM // detection, and chasing nested slices adds fragility for no container gain. +const CGROUP_V2_CONTROLLERS_PATH = "/sys/fs/cgroup/cgroup.controllers"; const CGROUP_V2_MEMORY_MAX_PATH = "/sys/fs/cgroup/memory.max"; const CGROUP_V1_MEMORY_LIMIT_PATH = "/sys/fs/cgroup/memory/memory.limit_in_bytes"; // Kernel no-limit sentinel is page-rounded 2^63-1 (~9223372036854771712); >= 2^60 is implausible as a real limit. @@ -111,15 +112,13 @@ export function _resetCgroupLimitCacheForTests(): void { export function getCgroupCpuLimit(): number | null { if (_cachedCgroupCpus !== undefined) return _cachedCgroupCpus; if (process.platform !== "linux") return (_cachedCgroupCpus = null); - const v2 = readCgroupFile(CGROUP_V2_CPU_MAX_PATH); - _cachedCgroupCpus = - v2 !== null - ? parseCgroupCpus(v2, null, null) - : parseCgroupCpus( - null, - readCgroupFile(CGROUP_V1_CPU_QUOTA_PATH), - readCgroupFile(CGROUP_V1_CPU_PERIOD_PATH), - ); + _cachedCgroupCpus = isCgroupV2() + ? parseCgroupCpus(readCgroupFile(CGROUP_V2_CPU_MAX_PATH), null, null) + : parseCgroupCpus( + null, + readCgroupFile(CGROUP_V1_CPU_QUOTA_PATH), + readCgroupFile(CGROUP_V1_CPU_PERIOD_PATH), + ); return _cachedCgroupCpus; } @@ -135,10 +134,9 @@ export function getCgroupMemoryLimitMb(): number | null { return null; } - const v2Content = readCgroupFile(CGROUP_V2_MEMORY_MAX_PATH); - const v1Content = v2Content === null ? readCgroupFile(CGROUP_V1_MEMORY_LIMIT_PATH) : null; - - _cachedCgroupLimitMb = parseCgroupLimitMb(v2Content, v1Content); + _cachedCgroupLimitMb = isCgroupV2() + ? parseCgroupLimitMb(readCgroupFile(CGROUP_V2_MEMORY_MAX_PATH), null) + : parseCgroupLimitMb(null, readCgroupFile(CGROUP_V1_MEMORY_LIMIT_PATH)); if (_cachedCgroupLimitMb !== null) { // stderr, not stdout: this is a diagnostic notice, and commands like `check --json` // write their machine-readable payload to stdout. A banner on stdout corrupts that @@ -151,6 +149,10 @@ export function getCgroupMemoryLimitMb(): number | null { return _cachedCgroupLimitMb; } +function isCgroupV2(): boolean { + return readCgroupFile(CGROUP_V2_CONTROLLERS_PATH) !== null; +} + function readCgroupFile(path: string): string | null { try { return readFileSync(path, "utf8"); @@ -181,8 +183,8 @@ function warnCgroupReadFailure(path: string, error: unknown): void { if (_warnedCgroupReadFailure) return; _warnedCgroupReadFailure = true; console.warn( - `[SystemMemory] Unable to read cgroup memory limit at ${path} ` + - `(${formatCgroupReadError(error)}); falling back to host RAM.`, + `[SystemMemory] Unable to read ${path} ` + + `(${formatCgroupReadError(error)}); using the host's values instead.`, ); } From 92e19cfd4a4c5230993d73d2c04478abe9516fcf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Wed, 25 Nov 2026 04:27:20 +0000 Subject: [PATCH 03/17] fix(studio): the dev Studio serves project files only through its API (#8721) * fix(studio): the dev Studio serves no project or private file outside its API * fix(studio): the dev Studio shell sends the CLI Studio's framing headers * test(studio): the dev file-serving test does not wait on dependency discovery * test(studio): dev file-serving tests build /@fs/ URLs the way Vite does on Windows * test(studio): the dev file-serving test warms Studio's entry module before timing requests * test(studio): dev file-serving tests get a dev-server time budget --- packages/studio/vite.config.files.test.ts | 83 ++++++++++++++++++++++ packages/studio/vite.config.ts | 20 +++++- packages/studio/vite.private-files.test.ts | 83 ++++++++++++++++++++++ packages/studio/vite.private-files.ts | 65 +++++++++++++++++ 4 files changed, 250 insertions(+), 1 deletion(-) create mode 100644 packages/studio/vite.config.files.test.ts create mode 100644 packages/studio/vite.private-files.test.ts create mode 100644 packages/studio/vite.private-files.ts diff --git a/packages/studio/vite.config.files.test.ts b/packages/studio/vite.config.files.test.ts new file mode 100644 index 0000000000..8a1b51dc02 --- /dev/null +++ b/packages/studio/vite.config.files.test.ts @@ -0,0 +1,83 @@ +// @vitest-environment node +import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { createServer, type ViteDevServer } from "vite"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; + +const fsUrl = (path: string) => `/@fs/${path.replace(/\\/g, "/").replace(/^\/+/, "")}`; + +const SECRET = "registry-token-for-test"; +const project = realpathSync(mkdtempSync(join(tmpdir(), "hf-linked-project-"))); +const link = resolve(__dirname, "data", "projects", `linked-${process.pid}`); +const studioDotfile = resolve(__dirname, `.hf-dev-secret-${process.pid}`); +let server: ViteDevServer; +let origin = ""; + +beforeAll(async () => { + writeFileSync(join(project, ".npmrc"), SECRET); + writeFileSync(studioDotfile, SECRET); + mkdirSync(dirname(link), { recursive: true }); + symlinkSync(project, link); + server = await createServer({ + configFile: resolve(__dirname, "vite.config.ts"), + logLevel: "silent", + server: { host: "127.0.0.1", port: 0, strictPort: false, hmr: false }, + // Dependency discovery would hold the first module request on a cold server; file serving does not need it. + optimizeDeps: { noDiscovery: true, include: [] }, + }); + await server.listen(); + const address = server.httpServer?.address(); + if (!address || typeof address === "string") throw new Error("dev server has no port"); + origin = `http://127.0.0.1:${address.port}`; + await server.warmupRequest("/src/main.tsx"); +}, 60_000); + +afterAll(async () => { + rmSync(link, { force: true }); + rmSync(studioDotfile, { force: true }); + rmSync(project, { recursive: true, force: true }); + await server?.close(); +}, 30_000); + +// fails without the fix: the dev server's own file serving answered for linked projects and checkout files. +describe("the dev Studio's file serving", { timeout: 30_000 }, () => { + it("serves no byte of a linked project's or the checkout's private file", async () => { + const name = link.split(/[\\/]/).pop(); + const dotfile = studioDotfile.split(/[\\/]/).pop(); + for (const path of [ + `/data/projects/${name}/.npmrc`, + `/data/projects/${name}/.npmrc?raw`, + `/data/projects/${name}/.npmrc?import&raw`, + `/data/projects/${name}/.npmrc?url`, + `/data/projects/${name}/.npmrc?inline`, + fsUrl(`${project}/.npmrc?raw`), + `/${dotfile}`, + `/${dotfile}?raw`, + fsUrl(`${studioDotfile}?raw`), + ]) { + const response = await fetch(`${origin}${path}`); + expect(await response.text(), path).not.toContain(SECRET); + } + }); + + it("still serves Studio's own modules", async () => { + for (const path of ["/src/main.tsx", "/@vite/client"]) + expect((await fetch(`${origin}${path}`)).status, path).toBe(200); + }); + + it("answers with the CLI Studio's framing rule, so another site cannot frame it", async () => { + for (const path of ["/", "/src/main.tsx"]) { + const response = await fetch(`${origin}${path}`); + expect(response.headers.get("content-security-policy"), path).toBe("frame-ancestors 'self'"); + expect(response.headers.get("x-frame-options"), path).toBe("SAMEORIGIN"); + } + }); + + it("lets no other loopback origin read what it serves", async () => { + const response = await fetch(`${origin}/src/main.tsx`, { + headers: { Origin: "http://127.0.0.1:4444" }, + }); + expect(response.headers.get("access-control-allow-origin")).toBeNull(); + }); +}); diff --git a/packages/studio/vite.config.ts b/packages/studio/vite.config.ts index e781803d33..3a5f9e1d20 100644 --- a/packages/studio/vite.config.ts +++ b/packages/studio/vite.config.ts @@ -19,7 +19,13 @@ import { previewConfigPayload } from "./vite.preview-config"; import { loadStudioServerDevModule } from "./vite.studio-server-module"; import type { openProjectHistory } from "@hyperframes/studio-server"; import { previewChangeOwner } from "./vite.preview-watch"; -import { carriesOAuthReturn, refuseOAuthReturn } from "../studio-server/src/helpers/inertRefusal"; +import { + carriesOAuthReturn, + inertRefusal, + refuseOAuthReturn, +} from "../studio-server/src/helpers/inertRefusal"; +import { devServesUrl } from "./vite.private-files"; +import { SAME_ORIGIN_FRAMING_HEADERS } from "../engine/src/utils/loopbackOnly"; import { hostHeaderAllowed, PREVIEW_ALLOWED_HOSTS_ENV, @@ -229,6 +235,14 @@ export function devProjectApi(): Plugin { if (!carriesOAuthReturn(req.url ?? "/")) return next(); void bridgeHonoResponse(refuseOAuthReturn(), res); }); + // Plugin middlewares run before Vite's file serving; project files reach the page only through /api, as built. + const servedRoots = { studio: __dirname, checkout: resolve(__dirname, "../..") }; + server.middlewares.use((req, res, next) => { + const url = req.url ?? "/"; + if (url === "/__hyperframes_config" || url.startsWith("/api/")) return next(); + if (devServesUrl(url, servedRoots)) return next(); + void bridgeHonoResponse(inertRefusal(404, "Not found."), res); + }); server.middlewares.use((req, res, next) => { const url = req.url ?? ""; if (url !== "/__hyperframes_config" && !url.startsWith("/api/")) return next(); @@ -402,6 +416,10 @@ export default defineConfig({ }, server: { port: 5190, + // The built Studio answers no other origin; Vite's default would let any loopback page read what it serves. + cors: false, + // The same framing rule as the CLI Studio's shell, so another site cannot frame this one. + headers: { ...SAME_ORIGIN_FRAMING_HEADERS }, // Vite's defaults (localhost, IP literals) still apply on top of this list. allowedHosts: previewAllowedHostsFromEnv(), watch: { diff --git a/packages/studio/vite.private-files.test.ts b/packages/studio/vite.private-files.test.ts new file mode 100644 index 0000000000..1dbdf11d87 --- /dev/null +++ b/packages/studio/vite.private-files.test.ts @@ -0,0 +1,83 @@ +import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { afterAll, describe, expect, it } from "vitest"; +import { devServesUrl } from "./vite.private-files"; + +const fsUrl = (path: string) => `/@fs/${path.replace(/\\/g, "/").replace(/^\/+/, "")}`; + +const base = realpathSync(mkdtempSync(join(tmpdir(), "hf-dev-files-"))); +const checkout = join(base, "checkout"); +const studio = join(checkout, "packages", "studio"); +const elsewhere = join(base, "my-project"); +const roots = { studio, checkout }; + +function file(path: string): void { + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, "x"); +} + +for (const project of [join(studio, "data", "projects", "real"), elsewhere]) + for (const name of [".npmrc", "id_rsa", "sub/.hyperframes/chat.json", ".claude/settings.json"]) + file(join(project, name)); +symlinkSync(elsewhere, join(studio, "data", "projects", "linked")); +file(join(studio, "src", "main.tsx")); +file(join(checkout, ".npmrc")); +file(join(checkout, "node_modules", ".bun", "react@19", "node_modules", "react", "index.js")); + +afterAll(() => rmSync(base, { recursive: true, force: true })); + +// fails without the fix: the dev server answered every URL outside /api from its own file serving. +describe("the dev server serves no project or private file", () => { + const PRIVATE = [".npmrc", "id_rsa", "sub/.hyperframes/chat.json", ".claude/settings.json"]; + const QUERIES = ["", "?raw", "?url", "?inline", "?import", "?import&raw"]; + + it.each(["real", "linked"])("refuses every %s project file, private or not", (project) => { + for (const name of [...PRIVATE, "index.html"]) + for (const query of QUERIES) + expect(devServesUrl(`/data/projects/${project}/${name}${query}`, roots)).toBe(false); + }); + + it("refuses a linked project's files by their real path", () => { + for (const name of PRIVATE) + expect(devServesUrl(fsUrl(`${elsewhere}/${name}`), roots)).toBe(false); + }); + + it.each([ + "/data/sessions/s.json", + "/data/renders/r.mp4", + "/DATA/projects/real/.npmrc", + "/data/projects/real/%2Enpmrc", + "/src/../data/projects/real/.npmrc", + "/src/%2e%2e/data/projects/real/.npmrc", + fsUrl(`${checkout}/.npmrc`), + `/@id/${checkout}/.npmrc?raw`, + `${checkout}/.npmrc?raw`, + "/%E0%A4%A", + ])("refuses %s", (url) => { + expect(devServesUrl(url, roots)).toBe(false); + }); + + it.each([ + "/", + "/index.html", + "/src/main.tsx", + "/src/main.tsx?t=1", + "/@vite/client", + "/@react-refresh", + "/node_modules/.vite/deps/react.js?v=1", + fsUrl(`${checkout}/node_modules/.bun/react@19/node_modules/react/index.js`), + fsUrl(`${checkout}/packages/core/src/index.ts`), + ])("still serves Studio's own %s", (url) => { + expect(devServesUrl(url, roots)).toBe(true); + }); + + it("still serves a checkout's modules when the checkout sits in a hidden folder", () => { + const hidden = { + studio: join(base, ".cache", "co", "packages", "studio"), + checkout: join(base, ".cache", "co"), + }; + expect(devServesUrl(fsUrl(`${hidden.checkout}/packages/core/src/index.ts`), hidden)).toBe(true); + expect(devServesUrl(fsUrl(`${hidden.checkout}/.npmrc`), hidden)).toBe(false); + }); +}); diff --git a/packages/studio/vite.private-files.ts b/packages/studio/vite.private-files.ts new file mode 100644 index 0000000000..31546d0656 --- /dev/null +++ b/packages/studio/vite.private-files.ts @@ -0,0 +1,65 @@ +import { readdirSync, realpathSync } from "node:fs"; +import { isAbsolute, join, relative, resolve } from "node:path"; +import { + isCredentialOrToolStatePath, + isStudioPrivatePath, + isVcsOrSecretPath, + projectPathSegments, +} from "../parsers/src/privatePath"; + +export interface DevServedRoots { + /** The Vite root: Studio's own package, with linked projects under `data/projects`. */ + studio: string; + /** The source checkout Vite serves under `/@fs/`. */ + checkout: string; +} + +const inside = (rel: string) => rel !== "" && !rel.startsWith("..") && !isAbsolute(rel); + +function realOrSelf(path: string): string { + try { + return realpathSync.native(path); + } catch { + return path; + } +} + +function linkedProjects(studio: string): string[] { + const dir = join(studio, "data", "projects"); + try { + return readdirSync(dir).map((name) => realOrSelf(join(dir, name))); + } catch { + return []; + } +} + +// `/@fs/` names a file-system path; any other URL Vite may read from its root or, as an id, from the file system. +function filesNamedBy(url: string, studio: string): string[] | null { + let pathname: string; + try { + pathname = decodeURIComponent(new URL(url, "http://dev").pathname); + } catch { + return null; + } + if (pathname.startsWith("/@fs/")) return [resolve("/", pathname.slice("/@fs/".length))]; + const path = pathname.replace(/^\/@id(?=\/)/, ""); + return [resolve(studio, `.${path}`), resolve("/", path.replace(/^\/+/, ""))]; +} + +function refused(file: string, roots: DevServedRoots, projects: string[]): boolean { + if (projectPathSegments(relative(roots.studio, file))[0] === "data") return true; + if (projects.some((project) => project === file || inside(relative(project, file)))) return true; + const rel = relative(roots.checkout, file).split("\\").join("/"); + if (!projectPathSegments(rel).includes("node_modules")) return isStudioPrivatePath(rel); + return isVcsOrSecretPath(rel) || isCredentialOrToolStatePath(rel); +} + +/** Whether the dev server may answer `url` from a file: never a project's, `data/`'s, or a private one. */ +export function devServesUrl(url: string, roots: DevServedRoots): boolean { + const files = filesNamedBy(url, roots.studio); + if (!files) return false; + const projects = linkedProjects(roots.studio); + return !files.some( + (file) => refused(file, roots, projects) || refused(realOrSelf(file), roots, projects), + ); +} From 614ece8bb8d3c9a878112932eb8711aff5d61ecc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Wed, 25 Nov 2026 04:29:06 +0000 Subject: [PATCH 04/17] fix(studio): a sealed empty box drags on the press right after its select click (#8772) * test(studio): a sealed box with no text opens no text edit * fix(studio): a sealed box with no text drags on the press after its select click --- .../src/components/editor/domEditInlineText.ts | 1 + .../src/hooks/inlineTextEdit.sealed.test.ts | 17 ++++++++++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/packages/studio/src/components/editor/domEditInlineText.ts b/packages/studio/src/components/editor/domEditInlineText.ts index 14bbbc89fe..16089fd4b9 100644 --- a/packages/studio/src/components/editor/domEditInlineText.ts +++ b/packages/studio/src/components/editor/domEditInlineText.ts @@ -48,6 +48,7 @@ export function canEditTextInline(selection: DomEditSelection | null): boolean { export function canEditSealedTextInline(selection: DomEditSelection | null): boolean { if (!selection?.handle || selection.isCompositionHost) return false; if (selection.isInsideLockedComposition || selection.textMarkup === false) return false; + if (!selection.textContent?.trim()) return false; return !["BODY", "HTML"].includes(selection.tagName.toUpperCase()); } diff --git a/packages/studio/src/hooks/inlineTextEdit.sealed.test.ts b/packages/studio/src/hooks/inlineTextEdit.sealed.test.ts index 413c938ec3..0c2d857093 100644 --- a/packages/studio/src/hooks/inlineTextEdit.sealed.test.ts +++ b/packages/studio/src/hooks/inlineTextEdit.sealed.test.ts @@ -18,7 +18,10 @@ import { afterStudioManualEditGestures, isStudioManualEditGestureLiveIn, } from "../components/editor/manualEditGesture"; -import { canEditSealedTextInline } from "../components/editor/domEditInlineText"; +import { + canEditElementTextInline, + canEditSealedTextInline, +} from "../components/editor/domEditInlineText"; import { sealedPreviewFrame } from "../player/lib/sealedPreviewFrame.test-helpers"; import { describePreviewElements, previewTextEdit } from "../player/lib/previewElements"; import { keepKeyboardOutOfSealedFrame } from "../player/lib/sealedFrameKeyboard"; @@ -964,6 +967,18 @@ it("opens no sealed text edit on a layer the frame would refuse, so Enter stays expect(canEditSealedTextInline(await select(iframe, "p"))).toBe(true); }); +// fails without the fix: a sealed empty box opened a text edit, so the press that dragged it after its select click +// was taken as a double press and the drag moved nothing (edit bench seqab-none-px-r0-nested-z100). +it("opens no sealed text edit on a box with no text, as a regular preview opens none", async () => { + document.body.innerHTML = `

x

`; + const { iframe } = sealedFrame(); + for (const id of ["box", "blank"]) { + expect(canEditElementTextInline(document.getElementById(id))).toBe(false); + expect(canEditSealedTextInline(await select(iframe, id))).toBe(false); + } + expect(canEditSealedTextInline(await select(iframe, "p"))).toBe(true); +}); + it("holds the pending-edit drain until a save the frame started on blur lands", async () => { await vi.waitFor(() => expect(hasStudioPendingEdits()).toBe(false)); const { title, selection } = await sealedTitle(); From 66aba4c7a0b7475d964d22ae2491d22d7e89fb48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Wed, 25 Nov 2026 04:31:21 +0000 Subject: [PATCH 05/17] feat(producer): render a part of the film with HDR video or shader transitions (#8802) * feat(producer): render a part of the film with HDR video or shader transitions The layered route now takes the frame window too, so a range renders HDR compositions and webm/mov shader transitions in one pass instead of being refused. Both layered loops seek the film frame and look up transitions by it, and the transition count that picks the hybrid loop counts only the window's frames. A whole render frees each HDR video's frames once it passes the clip's end, and the compositor draws a video until then. A window replays that freeing for the frames before it, so its first frame no longer shows a video that ended earlier in the film. * refactor(producer): name the window start and transition lookup the layered loops share * test(producer): pin the frame where a range stops replaying ended HDR videos --- .../src/services/render/frameWindow.test.ts | 20 +++- .../src/services/render/frameWindow.ts | 8 +- .../stages/captureHdrFrameShared.test.ts | 5 + .../render/stages/captureHdrFrameShared.ts | 28 +++++- .../stages/captureHdrHybridLoop.test.ts | 36 +++++++- .../render/stages/captureHdrHybridLoop.ts | 18 ++-- .../stages/captureHdrSequentialLoop.test.ts | 91 +++++++++++++++++++ .../render/stages/captureHdrSequentialLoop.ts | 24 +++-- .../services/render/stages/captureHdrStage.ts | 7 +- .../services/renderOrchestrator.range.test.ts | 24 ++++- 10 files changed, 235 insertions(+), 26 deletions(-) create mode 100644 packages/producer/src/services/render/stages/captureHdrSequentialLoop.test.ts diff --git a/packages/producer/src/services/render/frameWindow.test.ts b/packages/producer/src/services/render/frameWindow.test.ts index 8633b929fc..46cbae530b 100644 --- a/packages/producer/src/services/render/frameWindow.test.ts +++ b/packages/producer/src/services/render/frameWindow.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { resolveFrameWindow } from "./frameWindow.js"; +import { assertRangeSupported, resolveFrameWindow } from "./frameWindow.js"; const fps30 = { num: 30, den: 1 }; const ntsc = { num: 30000, den: 1001 }; @@ -42,3 +42,21 @@ describe("resolveFrameWindow", () => { ); }); }); + +describe("assertRangeSupported", () => { + const window = { startFrame: 75, endFrame: 120 }; + + it("lets the disk and layered routes capture a window", () => { + expect(() => assertRangeSupported(window, "sdr_disk")).not.toThrow(); + expect(() => assertRangeSupported(window, "hdr_layered")).not.toThrow(); + }); + + it("refuses a window on the streaming routes, which render whole films", () => { + expect(() => assertRangeSupported(window, "sdr_streaming")).toThrow( + /renders the whole film only/, + ); + expect(() => assertRangeSupported(window, "sdr_segmented")).toThrow( + /renders the whole film only/, + ); + }); +}); diff --git a/packages/producer/src/services/render/frameWindow.ts b/packages/producer/src/services/render/frameWindow.ts index 82d9aa0d05..df9e38cd7c 100644 --- a/packages/producer/src/services/render/frameWindow.ts +++ b/packages/producer/src/services/render/frameWindow.ts @@ -30,12 +30,16 @@ export function resolveFrameWindow(range: RenderRange, fps: Fps, filmFrames: num return { startFrame, endFrame }; } -/** Only the disk route captures a frame window; HDR content and shader transitions render whole films for now. */ +export function windowStartFrame(frameWindow: FrameWindow | undefined): number { + return frameWindow?.startFrame ?? 0; +} + +/** The disk and layered routes capture a frame window; the streaming routes render whole films. */ export function assertRangeSupported( frameWindow: FrameWindow | undefined, route: CapturePlan["kind"], ): void { - if (!frameWindow || route === "sdr_disk") return; + if (!frameWindow || route === "sdr_disk" || route === "hdr_layered") return; throw new Error( `This composition renders on the "${route}" capture route, which renders the whole film only; ` + "render it without a start or end.", diff --git a/packages/producer/src/services/render/stages/captureHdrFrameShared.test.ts b/packages/producer/src/services/render/stages/captureHdrFrameShared.test.ts index 1ee0654811..6ae01baec1 100644 --- a/packages/producer/src/services/render/stages/captureHdrFrameShared.test.ts +++ b/packages/producer/src/services/render/stages/captureHdrFrameShared.test.ts @@ -171,6 +171,11 @@ describe("partitionTransitionFrames", () => { expect(set.has(3)).toBe(false); }); + it("keeps a window's film frames, from its first frame", () => { + const set = partitionTransitionFrames([{ startFrame: 95, endFrame: 105 }], 10, 100); + expect([...set].sort((a, b) => a - b)).toEqual([100, 101, 102, 103, 104, 105]); + }); + it("returns empty set for non-positive totalFrames", () => { expect(partitionTransitionFrames([{ startFrame: 0, endFrame: 5 }], 0).size).toBe(0); expect(partitionTransitionFrames([{ startFrame: 0, endFrame: 5 }], -1).size).toBe(0); diff --git a/packages/producer/src/services/render/stages/captureHdrFrameShared.ts b/packages/producer/src/services/render/stages/captureHdrFrameShared.ts index eeb2214b80..92f8882023 100644 --- a/packages/producer/src/services/render/stages/captureHdrFrameShared.ts +++ b/packages/producer/src/services/render/stages/captureHdrFrameShared.ts @@ -9,6 +9,7 @@ * centralized here. */ +import type { Fps } from "@hyperframes/core"; import { type BeforeCaptureHook, type CaptureSession, @@ -89,12 +90,13 @@ export function distributeLayeredHybridFrameRanges( export function partitionTransitionFrames( transitionRanges: ReadonlyArray>, totalFrames: number, + firstFrame = 0, ): Set { const frames = new Set(); if (totalFrames <= 0) return frames; for (const range of transitionRanges) { - const start = Math.max(0, range.startFrame); - const end = Math.min(totalFrames - 1, range.endFrame); + const start = Math.max(firstFrame, range.startFrame); + const end = Math.min(firstFrame + totalFrames - 1, range.endFrame); for (let i = start; i <= end; i++) frames.add(i); } return frames; @@ -416,3 +418,25 @@ export function cleanupEndedHdrVideos(args: { } } } + +export function transitionAtFrame( + transitionRanges: TransitionRange[], + frame: number, +): TransitionRange | undefined { + return transitionRanges.find((t) => frame >= t.startFrame && frame <= t.endFrame); +} + +export function cleanupHdrVideosEndedBefore( + firstFrame: number, + fps: Fps, + transitionRanges: TransitionRange[], + state: Omit[0], "time" | "activeTransition">, +): void { + for (let frame = 0; frame < firstFrame; frame++) { + cleanupEndedHdrVideos({ + ...state, + time: (frame * fps.den) / fps.num, + activeTransition: transitionAtFrame(transitionRanges, frame), + }); + } +} diff --git a/packages/producer/src/services/render/stages/captureHdrHybridLoop.test.ts b/packages/producer/src/services/render/stages/captureHdrHybridLoop.test.ts index ab0220df1d..aaf96775b5 100644 --- a/packages/producer/src/services/render/stages/captureHdrHybridLoop.test.ts +++ b/packages/producer/src/services/render/stages/captureHdrHybridLoop.test.ts @@ -1,6 +1,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { ShaderBlendRequest } from "../../shaderTransitionWorkerPool.js"; import { type HybridLoopInput, runHybridLayeredFrameLoop } from "./captureHdrHybridLoop.js"; +import { + captureTransitionFrameOnWorker, + seekInjectAndQueryStacking, +} from "./captureHdrFrameShared.js"; vi.mock("@hyperframes/engine", async (importOriginal) => ({ ...(await importOriginal()), @@ -47,11 +51,18 @@ vi.mock("../../shaderTransitionWorkerPool.js", () => ({ function loopInput(overrides: { writeFrame?: (frame: number) => boolean; assertNotAborted?: () => void; + firstFrame?: number; }): HybridLoopInput { + const first = overrides.firstFrame ?? 0; const log = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; let frame = 0; const input = { - job: { config: { fps: { num: 30, den: 1 } }, totalFrames: 16, framesRendered: 0 }, + job: { + config: { fps: { num: 30, den: 1 } }, + totalFrames: 16, + framesRendered: 0, + ...(first && { frameWindow: { startFrame: first, endFrame: first + 16 } }), + }, cfg: {}, log, framesDir: "/tmp/unused", @@ -78,8 +89,8 @@ function loopInput(overrides: { ease: "", fromScene: "a", toScene: "b", - startFrame: 2, - endFrame: 13, + startFrame: first + 2, + endFrame: first + 13, }, ], sceneElements: { a: ["a"], b: ["b"] }, @@ -117,6 +128,25 @@ describe("runHybridLayeredFrameLoop failures with 2 workers", () => { expect(escaped).toEqual([]); }); + it("seeks film frames and finds the film's transition inside a window", async () => { + vi.mocked(seekInjectAndQueryStacking).mockClear(); + vi.mocked(captureTransitionFrameOnWorker).mockClear(); + const input = loopInput({ firstFrame: 100 }); + await runHybridLayeredFrameLoop(input); + expect(input.job.framesRendered).toBe(16); + const transitions = vi + .mocked(captureTransitionFrameOnWorker) + .mock.calls.map(([args]) => args as { frameIdx: number; time: number }); + const normalTimes = vi.mocked(seekInjectAndQueryStacking).mock.calls.map((call) => call[1]); + const seekedFrames = [...normalTimes, ...transitions.map((t) => t.time)] + .map((time) => Math.round(Number(time) * 30)) + .sort((a, b) => a - b); + expect(seekedFrames).toEqual(Array.from({ length: 16 }, (_, k) => 100 + k)); + expect(transitions.map((t) => t.frameIdx).sort((a, b) => a - b)).toEqual( + Array.from({ length: 12 }, (_, k) => 102 + k), + ); + }); + let aborts = 0; it.each([ { diff --git a/packages/producer/src/services/render/stages/captureHdrHybridLoop.ts b/packages/producer/src/services/render/stages/captureHdrHybridLoop.ts index b6ff579739..b127c1dc3b 100644 --- a/packages/producer/src/services/render/stages/captureHdrHybridLoop.ts +++ b/packages/producer/src/services/render/stages/captureHdrHybridLoop.ts @@ -54,8 +54,10 @@ import { ensureFrameWritten, partitionTransitionFrames, seekInjectAndQueryStacking, + transitionAtFrame, } from "./captureHdrFrameShared.js"; import { reportFrameProgress } from "../shared.js"; +import { windowStartFrame } from "../frameWindow.js"; export interface HybridLoopInput { job: RenderJob; @@ -112,7 +114,8 @@ export async function runHybridLayeredFrameLoop(input: HybridLoopInput): Promise assertNotAborted, onProgress, } = input; - const transitionFramesSet = partitionTransitionFrames(transitionRanges, totalFrames); + const firstFrame = windowStartFrame(job.frameWindow); + const transitionFramesSet = partitionTransitionFrames(transitionRanges, totalFrames, firstFrame); const hasTransitions = transitionRanges.length > 0; const bufSize = width * height * 6; @@ -228,9 +231,10 @@ export async function runHybridLayeredFrameLoop(input: HybridLoopInput): Promise for (let i = range.start; i < range.end; i++) { throwIfFailed(); assertNotAborted(); - const time = (i * job.config.fps.den) / job.config.fps.num; - const activeTransition = transitionFramesSet.has(i) - ? transitionRanges.find((t) => i >= t.startFrame && i <= t.endFrame) + const frame = firstFrame + i; + const time = (frame * job.config.fps.den) / job.config.fps.num; + const activeTransition = transitionFramesSet.has(frame) + ? transitionAtFrame(transitionRanges, frame) : undefined; if (activeTransition && ring) { // Pick the next ring slot. If it's still in flight from an earlier @@ -247,7 +251,7 @@ export async function runHybridLayeredFrameLoop(input: HybridLoopInput): Promise // because the per-worker browser session is single-threaded. await captureTransitionFrameOnWorker({ session, - frameIdx: i, + frameIdx: frame, time, transition: activeTransition, buffers, @@ -265,7 +269,7 @@ export async function runHybridLayeredFrameLoop(input: HybridLoopInput): Promise const progress = activeTransition.endFrame === activeTransition.startFrame ? 1 - : (i - activeTransition.startFrame) / + : (frame - activeTransition.startFrame) / (activeTransition.endFrame - activeTransition.startFrame); // BLEND + ENCODE without awaiting. The promise drains back into // `ringInFlight[slot]`; the next iteration that picks `slot` @@ -327,7 +331,7 @@ export async function runHybridLayeredFrameLoop(input: HybridLoopInput): Promise // Rebind ctx to this worker's session for per-layer captures const wctx: HdrCompositeContext = { ...hdrCompositeCtx, domSession: session }; await timeHdrPhaseAsync(hdrPerf, "normalCompositeMs", () => - compositeHdrFrame(wctx, canvas, time, stackingInfo, undefined, i), + compositeHdrFrame(wctx, canvas, time, stackingInfo, undefined, frame), ); if (debugDumpEnabled && debugDumpDir && i % 30 === 0) { writeFileExclusiveSync( diff --git a/packages/producer/src/services/render/stages/captureHdrSequentialLoop.test.ts b/packages/producer/src/services/render/stages/captureHdrSequentialLoop.test.ts new file mode 100644 index 0000000000..22a51262ea --- /dev/null +++ b/packages/producer/src/services/render/stages/captureHdrSequentialLoop.test.ts @@ -0,0 +1,91 @@ +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, it, vi } from "vitest"; +import { compositeHdrFrame } from "../../hdrCompositor.js"; +import { captureSceneIntoBuffer, seekInjectAndQueryStacking } from "./captureHdrFrameShared.js"; +import { + type SequentialLoopInput, + runSequentialLayeredFrameLoop, +} from "./captureHdrSequentialLoop.js"; + +vi.mock("./captureHdrFrameShared.js", async (importOriginal) => ({ + ...(await importOriginal()), + captureSceneIntoBuffer: vi.fn(async () => {}), + seekInjectAndQueryStacking: vi.fn(async () => []), +})); +vi.mock("../../hdrCompositor.js", async (importOriginal) => ({ + ...(await importOriginal()), + compositeHdrFrame: vi.fn(async () => {}), +})); + +function windowInput(written: number[]): SequentialLoopInput { + return { + job: { + config: { fps: { num: 30, den: 1 } }, + totalFrames: 10, + framesRendered: 0, + frameWindow: { startFrame: 100, endFrame: 110 }, + }, + log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + width: 1, + height: 1, + totalFrames: 10, + nativeHdrIds: new Set(), + nativeHdrImageIds: new Set(), + hdrCompositeCtx: {}, + hdrPerf: undefined, + hdrEncoder: { writeFrame: async () => written.push(written.length) > 0 }, + domSession: { page: {} }, + transitionRanges: [ + { time: 0, duration: 0, shader: "crossfade", ease: "", fromScene: "a", toScene: "b" }, + ].map((t) => ({ ...t, startFrame: 104, endFrame: 106 })), + sceneElements: { a: ["a"], b: ["b"] }, + compositeTransfer: "srgb", + hdrTargetTransfer: undefined, + hdrVideoEndTimes: new Map(), + cleanedUpVideos: new Set(), + hdrVideoFrameSources: new Map(), + debugDumpEnabled: false, + debugDumpDir: null, + assertNotAborted: () => {}, + // The loop only touches the fields above. + } as unknown as SequentialLoopInput; +} + +it("seeks film frames and finds the film's transition inside a window", async () => { + const written: number[] = []; + await runSequentialLayeredFrameLoop(windowInput(written)); + + const seeked = vi + .mocked(seekInjectAndQueryStacking) + .mock.calls.map((call) => Math.round(Number(call[1]) * 30)); + expect(seeked).toEqual(Array.from({ length: 10 }, (_, k) => 100 + k)); + // Two scenes per transition frame, film frames 104-106. + const transitionFrames = vi + .mocked(captureSceneIntoBuffer) + .mock.calls.map(([args]) => args.frameIdx); + expect(transitionFrames).toEqual([104, 104, 105, 105, 106, 106]); + expect(written).toHaveLength(10); +}); + +it("starts a window without the HDR videos a whole render has already passed the end of", async () => { + const input = windowInput([]); + const close = vi.fn(); + input.hdrVideoEndTimes.set("ended", 1); + input.hdrVideoEndTimes.set("playing", 5); + // Ends between frames 99 and 100: a whole render still draws it at frame 100, then frees it. + input.hdrVideoEndTimes.set("endsAtFirstFrame", 3.31); + for (const id of ["ended", "playing", "endsAtFirstFrame"]) { + const dir = mkdtempSync(join(tmpdir(), `hf-hdr-${id}-`)); + input.hdrVideoFrameSources.set(id, { dir, windows: { close } } as never); + } + let shownAtFirstFrame: string[] = []; + vi.mocked(compositeHdrFrame).mockImplementationOnce(async () => { + shownAtFirstFrame = [...input.hdrVideoFrameSources.keys()]; + }); + + await runSequentialLayeredFrameLoop(input); + + expect(shownAtFirstFrame).toEqual(["playing", "endsAtFirstFrame"]); +}); diff --git a/packages/producer/src/services/render/stages/captureHdrSequentialLoop.ts b/packages/producer/src/services/render/stages/captureHdrSequentialLoop.ts index 6723b10207..8298526e1b 100644 --- a/packages/producer/src/services/render/stages/captureHdrSequentialLoop.ts +++ b/packages/producer/src/services/render/stages/captureHdrSequentialLoop.ts @@ -36,11 +36,14 @@ import { writeFileExclusiveSync } from "../shared.js"; import { captureSceneIntoBuffer, cleanupEndedHdrVideos, + cleanupHdrVideosEndedBefore, + transitionAtFrame, ensureFrameWritten, type LayeredTransitionBuffers, seekInjectAndQueryStacking, } from "./captureHdrFrameShared.js"; import { reportFrameProgress } from "../shared.js"; +import { windowStartFrame } from "../frameWindow.js"; export interface SequentialLoopInput { job: RenderJob; @@ -104,9 +107,18 @@ export async function runSequentialLayeredFrameLoop(input: SequentialLoopInput): : null; const normalCanvas = Buffer.alloc(bufSize); + const firstFrame = windowStartFrame(job.frameWindow); + cleanupHdrVideosEndedBefore(firstFrame, job.config.fps, transitionRanges, { + hdrVideoEndTimes, + cleanedUpVideos, + hdrVideoFrameSources, + sceneElements, + log, + }); for (let i = 0; i < totalFrames; i++) { assertNotAborted(); - const time = (i * job.config.fps.den) / job.config.fps.num; + const frame = firstFrame + i; + const time = (frame * job.config.fps.den) / job.config.fps.num; if (hdrPerf) hdrPerf.frames += 1; const stackingInfo = await seekInjectAndQueryStacking( @@ -119,12 +131,12 @@ export async function runSequentialLayeredFrameLoop(input: SequentialLoopInput): "frameInjectMs", "stackingQueryMs", ); - const activeTransition = transitionRanges.find((t) => i >= t.startFrame && i <= t.endFrame); + const activeTransition = transitionAtFrame(transitionRanges, frame); if (i % 30 === 0 && (log.isLevelEnabled?.("debug") ?? true)) { const hdrEl = stackingInfo.find((e) => e.isHdr); log.debug("[Render] HDR layer composite frame", { - frame: i, + frame, time: time.toFixed(2), hdrElement: hdrEl ? { z: hdrEl.zIndex, visible: hdrEl.visible, width: hdrEl.width } : null, stackingCount: stackingInfo.length, @@ -138,7 +150,7 @@ export async function runSequentialLayeredFrameLoop(input: SequentialLoopInput): const progress = activeTransition.endFrame === activeTransition.startFrame ? 1 - : (i - activeTransition.startFrame) / + : (frame - activeTransition.startFrame) / (activeTransition.endFrame - activeTransition.startFrame); const sceneAIds = new Set(sceneElements[activeTransition.fromScene] ?? []); const sceneBIds = new Set(sceneElements[activeTransition.toScene] ?? []); @@ -169,7 +181,7 @@ export async function runSequentialLayeredFrameLoop(input: SequentialLoopInput): hdrTargetTransfer, hdrPerf, log, - frameIdx: i, + frameIdx: frame, }); } @@ -196,7 +208,7 @@ export async function runSequentialLayeredFrameLoop(input: SequentialLoopInput): if (hdrPerf) hdrPerf.normalFrames += 1; timeHdrPhase(hdrPerf, "canvasClearMs", () => normalCanvas.fill(0)); await timeHdrPhaseAsync(hdrPerf, "normalCompositeMs", () => - compositeHdrFrame(hdrCompositeCtx, normalCanvas, time, stackingInfo, undefined, i), + compositeHdrFrame(hdrCompositeCtx, normalCanvas, time, stackingInfo, undefined, frame), ); if (debugDumpEnabled && debugDumpDir && i % 30 === 0) { writeFileExclusiveSync( diff --git a/packages/producer/src/services/render/stages/captureHdrStage.ts b/packages/producer/src/services/render/stages/captureHdrStage.ts index 1392f7e407..08ee6fc148 100644 --- a/packages/producer/src/services/render/stages/captureHdrStage.ts +++ b/packages/producer/src/services/render/stages/captureHdrStage.ts @@ -80,6 +80,7 @@ import { wrapCaptureStageError } from "../captureStageError.js"; import { encoderFailureError } from "../encoderInterruption.js"; import type { HdrLayeredCapturePlan } from "../capturePlan.js"; import type { DeliveryEncoderOptions } from "../deliveryEncoder.js"; +import { windowStartFrame } from "../frameWindow.js"; export interface CaptureHdrStageInput { job: RenderJob; @@ -369,7 +370,11 @@ export async function runCaptureHdrStage( // ── Dispatch to sequential or hybrid frame loop ──────────────────── const effectiveWorkerCount = Math.max(1, workerCount); - const transitionFrameCount = partitionTransitionFrames(transitionRanges, totalFrames).size; + const transitionFrameCount = partitionTransitionFrames( + transitionRanges, + totalFrames, + windowStartFrame(job.frameWindow), + ).size; const useHybrid = shouldUseHybridLayeredPath({ hasHdrContent, transitionFramesCount: transitionFrameCount, diff --git a/packages/producer/src/services/renderOrchestrator.range.test.ts b/packages/producer/src/services/renderOrchestrator.range.test.ts index 89bdc23b89..b393b5b0e5 100644 --- a/packages/producer/src/services/renderOrchestrator.range.test.ts +++ b/packages/producer/src/services/renderOrchestrator.range.test.ts @@ -12,6 +12,10 @@ const { state, CAPTURE_REACHED } = vi.hoisted(() => ({ shaderTransitions: false, disk: [] as { totalFrames: number; frameRange?: { startFrame: number; endFrame: number } }[], streaming: 0, + layered: [] as { + totalFrames: number; + frameWindow?: { startFrame: number; endFrame: number }; + }[], audio: [] as { totalFrames: number; frameWindow?: { startFrame: number; endFrame: number } }[], }, CAPTURE_REACHED: "capture reached", @@ -102,6 +106,16 @@ vi.mock("./render/stages/captureStage.js", async (importOriginal) => ({ throw new Error(CAPTURE_REACHED); }, })); +vi.mock("./render/stages/captureHdrStage.js", async (importOriginal) => ({ + ...(await importOriginal()), + runCaptureHdrStage: async (input: { + totalFrames: number; + job: { frameWindow?: { startFrame: number; endFrame: number } }; + }) => { + state.layered.push({ totalFrames: input.totalFrames, frameWindow: input.job.frameWindow }); + throw new Error(CAPTURE_REACHED); + }, +})); vi.mock("./render/stages/captureStreamingStage.js", async (importOriginal) => ({ ...(await importOriginal()), runCaptureStreamingStage: async () => { @@ -115,6 +129,7 @@ beforeEach(() => { state.shaderTransitions = false; state.disk = []; state.streaming = 0; + state.layered = []; state.audio = []; }); afterEach(() => { @@ -164,12 +179,13 @@ it("renders the whole film as before without a range", async () => { expect(state.disk[0]?.frameRange).toBeUndefined(); }); -it("refuses a range on the layered route instead of rendering the whole film", async () => { +it("captures the range's frames on the layered route", async () => { // webm and mov composite shader transitions on the layered route; mp4 composites them in the page. state.shaderTransitions = true; - await expect(render({ startSeconds: 2.5, endSeconds: 4 }, "webm")).rejects.toThrow( - /"hdr_layered" capture route, which renders the whole film only/, - ); + await render({ startSeconds: 2.5, endSeconds: 4 }, "webm"); + expect(state.layered).toEqual([ + { totalFrames: 45, frameWindow: { startFrame: 75, endFrame: 120 } }, + ]); expect(state.disk).toEqual([]); expect(state.streaming).toBe(0); }); From 4920a939bc645cb268b2d767af67a0c041f39d8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Wed, 25 Nov 2026 04:50:30 +0000 Subject: [PATCH 06/17] fix(skills): helper outputs replace a link at their name instead of writing through it (#8667) * fix(skills): helper outputs replace a link at their name instead of writing through it * fix(skills): audio data writes its temp file with a plain exclusive open * fix(skills): regenerate the skills manifest and read test outputs before inspecting them * chore(skills): regenerate the skills manifest after merging main * chore(skills): regenerate the skills manifest after merging main * chore(skills): regenerate the skills manifest after merging main --- .../cli/src/media-use/lib/link-safe-write.mjs | 86 +++++++++++++++++++ packages/cli/src/media-use/lib/manifest.mjs | 70 +-------------- scripts/generate-skill-module-copies.mjs | 7 ++ skills-manifest.json | 8 +- skills/hyperframes/scripts/bake-basemap.mjs | 70 ++++++++------- .../scripts/lib/link-safe-write.mjs | 86 +++++++++++++++++++ .../scripts/lib/link-safe-write.test.mjs | 76 ++++++++++++++++ skills/hyperframes/scripts/locate.mjs | 42 +++++---- skills/hyperframes/scripts/locate.test.mjs | 63 +++++++++++++- .../audio/scripts/extract-audio-data.py | 18 +++- .../audio/scripts/extract-audio-data.test.mjs | 60 +++++++++++++ .../media-use/scripts/lib/link-safe-write.mjs | 86 +++++++++++++++++++ skills/media-use/scripts/lib/manifest.mjs | 70 +-------------- 13 files changed, 556 insertions(+), 186 deletions(-) create mode 100644 packages/cli/src/media-use/lib/link-safe-write.mjs create mode 100644 skills/hyperframes/scripts/lib/link-safe-write.mjs create mode 100644 skills/hyperframes/scripts/lib/link-safe-write.test.mjs create mode 100644 skills/media-use/audio/scripts/extract-audio-data.test.mjs create mode 100644 skills/media-use/scripts/lib/link-safe-write.mjs diff --git a/packages/cli/src/media-use/lib/link-safe-write.mjs b/packages/cli/src/media-use/lib/link-safe-write.mjs new file mode 100644 index 0000000000..6a0b0cf1b6 --- /dev/null +++ b/packages/cli/src/media-use/lib/link-safe-write.mjs @@ -0,0 +1,86 @@ +import { randomBytes } from "node:crypto"; +import { lstatSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; + +// Writes into a folder someone else may have filled: a link already at a name is replaced or refused, never followed. + +/** Folder `rel` under `base`, made if missing; throws when any folder on the way is a link. */ +export function ownFolder(base, rel) { + let dir = base; + // Each folder is looked at before it is made, so nothing is ever made through a link. + for (const part of rel.split(/[\\/]/).filter(Boolean)) { + dir = join(dir, part); + if (lstatSync(dir, { throwIfNoEntry: false })?.isSymbolicLink()) { + throw new Error( + `${dir} is a link; media is written only into real folders, so nothing was written there`, + ); + } + mkdirSync(dir, { recursive: true }); + } + return dir; +} + +/** A new temp file beside `path` holding `content`, with a random name, created exclusively. */ +export function writeTempBeside(path, content) { + // Same shape as core atomicTempPath, which Studio's project history skips. + const temp = `${path}.hf${randomBytes(3).toString("hex")}.tmp`; + try { + writeFileSync(temp, content, { flag: "wx" }); + } catch (error) { + // EEXIST: the random name belongs to another writer, so it is left alone. A failed cleanup must not hide `error`. + if (error?.code !== "EEXIST") { + try { + rmSync(temp, { force: true }); + } catch {} + } + throw error; + } + return temp; +} + +/** Writes `content` to a temp file beside `path`, then renames it over: a link at `path` is replaced, not followed. */ +export function replaceFile(path, content) { + publish(writeTempBeside(path, content), path); +} + +/** As replaceFile, with `write(temp)` filling the temp file (an ffmpeg run, say); a throw leaves `path` as it was. */ +export function replaceFileWith(path, write) { + const temp = writeTempBeside(path, ""); + try { + write(temp); + } catch (error) { + rmSync(temp, { force: true }); + throw error; + } + publish(temp, path); +} + +function publish(temp, path) { + try { + renameRidingWindowsHolds(temp, path); + } catch (error) { + rmSync(temp, { force: true }); + throw error; + } +} + +// Windows refuses a rename for a moment while antivirus or a just-exited process still holds the file. +const WINDOWS_HOLD = new Set(["EPERM", "EACCES", "EBUSY"]); +const HOLD_BACKOFF_MS = [10, 20, 40, 80, 160, 320, 640]; + +function renameRidingWindowsHolds(from, to) { + for (let attempt = 0; ; attempt++) { + try { + return renameSync(from, to); + } catch (error) { + const held = process.platform === "win32" && WINDOWS_HOLD.has(error?.code); + if (!held || attempt >= HOLD_BACKOFF_MS.length) throw error; + sleepMs(HOLD_BACKOFF_MS[attempt]); + } + } +} + +/** Sync sleep (no busy-spin). */ +export function sleepMs(ms) { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); +} diff --git a/packages/cli/src/media-use/lib/manifest.mjs b/packages/cli/src/media-use/lib/manifest.mjs index dee46b397a..648ebcddaa 100644 --- a/packages/cli/src/media-use/lib/manifest.mjs +++ b/packages/cli/src/media-use/lib/manifest.mjs @@ -8,13 +8,15 @@ import { writeFileSync, writeSync, rmSync, - renameSync, lstatSync, realpathSync, constants, } from "node:fs"; import { randomBytes } from "node:crypto"; import { basename, join } from "node:path"; +import { ownFolder, replaceFile, sleepMs, writeTempBeside } from "./link-safe-write.mjs"; + +export { ownFolder, replaceFile, writeTempBeside }; const MANIFEST_FILE = "manifest.jsonl"; const INDEX_FILE = "index.md"; @@ -93,22 +95,6 @@ export function ownTypeDir(projectDir, type) { return ownFolder(ownMediaDir(projectDir), typeSubdir(type)); } -/** Folder `rel` under `base`, made if missing; throws when any folder on the way is a link. */ -export function ownFolder(base, rel) { - let dir = base; - // Each folder is looked at before it is made, so nothing is ever made through a link. - for (const part of rel.split(/[\\/]/).filter(Boolean)) { - dir = join(dir, part); - if (lstatSync(dir, { throwIfNoEntry: false })?.isSymbolicLink()) { - throw new Error( - `${dir} is a link; media is written only into real folders, so nothing was written there`, - ); - } - mkdirSync(dir, { recursive: true }); - } - return dir; -} - /** Throws when `path` is a link. */ export function refuseLink(path) { if (lstatSync(path, { throwIfNoEntry: false })?.isSymbolicLink()) { @@ -116,51 +102,6 @@ export function refuseLink(path) { } } -/** A new temp file beside `path` holding `content`, with a random name, created exclusively. */ -export function writeTempBeside(path, content) { - // Same shape as core atomicTempPath, which Studio's project history skips. - const temp = `${path}.hf${randomBytes(3).toString("hex")}.tmp`; - try { - writeFileSync(temp, content, { flag: "wx" }); - } catch (error) { - // EEXIST: the random name belongs to another writer, so it is left alone. A failed cleanup must not hide `error`. - if (error?.code !== "EEXIST") { - try { - rmSync(temp, { force: true }); - } catch {} - } - throw error; - } - return temp; -} - -/** Writes `content` to a temp file beside `path`, then renames it over: a link at `path` is replaced, not followed. */ -export function replaceFile(path, content) { - const temp = writeTempBeside(path, content); - try { - renameRidingWindowsHolds(temp, path); - } catch (error) { - rmSync(temp, { force: true }); - throw error; - } -} - -// Windows refuses a rename for a moment while antivirus or a just-exited process still holds the file. -const WINDOWS_HOLD = new Set(["EPERM", "EACCES", "EBUSY"]); -const HOLD_BACKOFF_MS = [10, 20, 40, 80, 160, 320, 640]; - -function renameRidingWindowsHolds(from, to) { - for (let attempt = 0; ; attempt++) { - try { - return renameSync(from, to); - } catch (error) { - const held = process.platform === "win32" && WINDOWS_HOLD.has(error?.code); - if (!held || attempt >= HOLD_BACKOFF_MS.length) throw error; - sleepMs(HOLD_BACKOFF_MS[attempt]); - } - } -} - export function appendRecord(projectDir, record) { ownTypeDir(projectDir, record.type); @@ -257,11 +198,6 @@ export function nextId(projectDir, type) { return `${prefix}_${String(max + 1).padStart(3, "0")}`; } -// Sync sleep (no busy-spin) for the allocation lock retry. -function sleepMs(ms) { - Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); -} - // Coarse per-project lock so concurrent resolves don't race on id allocation. // ponytail: one lock file with a 15s stale-steal (a crashed holder can't wedge // the project); fine for agent-scale concurrency — revisit if throughput needs diff --git a/scripts/generate-skill-module-copies.mjs b/scripts/generate-skill-module-copies.mjs index f33cbe4f85..d0dd321f81 100644 --- a/scripts/generate-skill-module-copies.mjs +++ b/scripts/generate-skill-module-copies.mjs @@ -32,6 +32,13 @@ export const skillModuleCopies = [ "packages/cli/src/media-use/lib/main-module.mjs", ], ], + [ + "skills/hyperframes/scripts/lib/link-safe-write.mjs", + [ + "skills/media-use/scripts/lib/link-safe-write.mjs", + "packages/cli/src/media-use/lib/link-safe-write.mjs", + ], + ], [ "skills/hyperframes/scripts/lib/literal-media-input.mjs", [ diff --git a/skills-manifest.json b/skills-manifest.json index f24d995e74..7415fff620 100644 --- a/skills-manifest.json +++ b/skills-manifest.json @@ -6,8 +6,8 @@ "files": 4 }, "hyperframes": { - "hash": "7b9108a831fc740a", - "files": 85 + "hash": "d0cfc4072c8f2797", + "files": 87 }, "hyperframes-cli": { "hash": "36ed7b39fe73ede2", @@ -18,8 +18,8 @@ "files": 13 }, "media-use": { - "hash": "fff20d7c6efcc737", - "files": 135 + "hash": "89f0d2fddb8bb9b1", + "files": 137 }, "remotion-to-hyperframes": { "hash": "3a1dd4a513701ef6", diff --git a/skills/hyperframes/scripts/bake-basemap.mjs b/skills/hyperframes/scripts/bake-basemap.mjs index 3fbc0c10a0..7597b5a5b3 100644 --- a/skills/hyperframes/scripts/bake-basemap.mjs +++ b/skills/hyperframes/scripts/bake-basemap.mjs @@ -22,9 +22,10 @@ // for the HF composition. One bake at a time: several headless Chromes on a small machine stall. import "./lib/windows-exe-search.mjs"; import { join } from "node:path"; -import { mkdirSync, writeFileSync, readdirSync, existsSync } from "node:fs"; +import { readdirSync, existsSync } from "node:fs"; import { homedir } from "node:os"; import { spawnSync } from "node:child_process"; +import { ownFolder, replaceFile, replaceFileWith } from "./lib/link-safe-write.mjs"; import { assertLiteralMediaPath } from "./lib/literal-media-input.mjs"; import { importEntry, searchedFolders, trustedPackageEntry } from "./lib/trusted-package.mjs"; @@ -152,7 +153,8 @@ const TILES = const OUT = process.env.OUT || process.cwd(); // artifacts → workspace (cwd), NOT the installed skill dir const framesDir = join(OUT, "frames-" + NAME); assertLiteralMediaPath(framesDir); -mkdirSync(framesDir, { recursive: true }); +// A link at an output name is replaced, never written through; a linked frames folder is refused. +ownFolder(OUT, "frames-" + NAME); // A seeded star field behind the globe, so every bake of the same move is identical. let seed = 7; @@ -281,11 +283,11 @@ try { timeouts.push(i); console.warn(`[${NAME}] idle TIMEOUT at frame ${i} — tiles may be incomplete`); } - await page.screenshot({ - path: join(framesDir, `f${String(i).padStart(4, "0")}.png`), + const shot = await page.screenshot({ clip: { x: 0, y: 0, width: 1920, height: 1080 }, optimizeForSpeed: true, }); + replaceFile(join(framesDir, `f${String(i).padStart(4, "0")}.png`), shot); if (p >= HOLD && !coords && COUNTRIES.length) coords = await page.evaluate(() => window.__project()); // capture at first hold frame if (i % 20 === 0 || i === N - 1) { @@ -298,35 +300,45 @@ try { // encode frames → all-intra MP4 (every frame seekable for HF); fall back to printing the command if ffmpeg is absent const mp4 = join(OUT, NAME + ".mp4"), pat = join(framesDir, "f%04d.png"); - const ff = spawnSync( - "ffmpeg", - [ - "-y", - "-framerate", - String(FPS), - "-i", - pat, - "-c:v", - "libx264", - "-pix_fmt", - "yuv420p", - "-g", - "1", - "-crf", - "16", - "-movflags", - "+faststart", - mp4, - ], - { stdio: "ignore" }, - ); - if (ff.status === 0) console.log(`[${NAME}] encoded → ${mp4}`); + let status = 0; + try { + replaceFileWith(mp4, (temp) => { + ({ status } = spawnSync( + "ffmpeg", + [ + "-y", + "-framerate", + String(FPS), + "-i", + pat, + "-c:v", + "libx264", + "-pix_fmt", + "yuv420p", + "-g", + "1", + "-crf", + "16", + "-movflags", + "+faststart", + "-f", + "mp4", + temp, + ], + { stdio: "ignore" }, + )); + if (status !== 0) throw new Error(`ffmpeg exited ${status}`); + }); + } catch (error) { + if (status === 0) throw error; // no temp file could be made: not an ffmpeg problem + } + if (status === 0) console.log(`[${NAME}] encoded → ${mp4}`); else console.warn( - `[${NAME}] ffmpeg unavailable (status ${ff.status}) — encode manually:\n ffmpeg -y -framerate ${FPS} -i ${pat} -c:v libx264 -pix_fmt yuv420p -g 1 -crf 16 -movflags +faststart ${mp4}`, + `[${NAME}] ffmpeg unavailable (status ${status}) — encode manually:\n ffmpeg -y -framerate ${FPS} -i ${pat} -c:v libx264 -pix_fmt yuv420p -g 1 -crf 16 -movflags +faststart ${mp4}`, ); if (coords) { - writeFileSync(join(OUT, NAME + "-coords.json"), JSON.stringify(coords)); + replaceFile(join(OUT, NAME + "-coords.json"), JSON.stringify(coords)); console.log( `[${NAME}] coords written: ${coords.countries.map((c) => c.name + "(" + c.d.length + "ch)").join(", ")}`, ); diff --git a/skills/hyperframes/scripts/lib/link-safe-write.mjs b/skills/hyperframes/scripts/lib/link-safe-write.mjs new file mode 100644 index 0000000000..6a0b0cf1b6 --- /dev/null +++ b/skills/hyperframes/scripts/lib/link-safe-write.mjs @@ -0,0 +1,86 @@ +import { randomBytes } from "node:crypto"; +import { lstatSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; + +// Writes into a folder someone else may have filled: a link already at a name is replaced or refused, never followed. + +/** Folder `rel` under `base`, made if missing; throws when any folder on the way is a link. */ +export function ownFolder(base, rel) { + let dir = base; + // Each folder is looked at before it is made, so nothing is ever made through a link. + for (const part of rel.split(/[\\/]/).filter(Boolean)) { + dir = join(dir, part); + if (lstatSync(dir, { throwIfNoEntry: false })?.isSymbolicLink()) { + throw new Error( + `${dir} is a link; media is written only into real folders, so nothing was written there`, + ); + } + mkdirSync(dir, { recursive: true }); + } + return dir; +} + +/** A new temp file beside `path` holding `content`, with a random name, created exclusively. */ +export function writeTempBeside(path, content) { + // Same shape as core atomicTempPath, which Studio's project history skips. + const temp = `${path}.hf${randomBytes(3).toString("hex")}.tmp`; + try { + writeFileSync(temp, content, { flag: "wx" }); + } catch (error) { + // EEXIST: the random name belongs to another writer, so it is left alone. A failed cleanup must not hide `error`. + if (error?.code !== "EEXIST") { + try { + rmSync(temp, { force: true }); + } catch {} + } + throw error; + } + return temp; +} + +/** Writes `content` to a temp file beside `path`, then renames it over: a link at `path` is replaced, not followed. */ +export function replaceFile(path, content) { + publish(writeTempBeside(path, content), path); +} + +/** As replaceFile, with `write(temp)` filling the temp file (an ffmpeg run, say); a throw leaves `path` as it was. */ +export function replaceFileWith(path, write) { + const temp = writeTempBeside(path, ""); + try { + write(temp); + } catch (error) { + rmSync(temp, { force: true }); + throw error; + } + publish(temp, path); +} + +function publish(temp, path) { + try { + renameRidingWindowsHolds(temp, path); + } catch (error) { + rmSync(temp, { force: true }); + throw error; + } +} + +// Windows refuses a rename for a moment while antivirus or a just-exited process still holds the file. +const WINDOWS_HOLD = new Set(["EPERM", "EACCES", "EBUSY"]); +const HOLD_BACKOFF_MS = [10, 20, 40, 80, 160, 320, 640]; + +function renameRidingWindowsHolds(from, to) { + for (let attempt = 0; ; attempt++) { + try { + return renameSync(from, to); + } catch (error) { + const held = process.platform === "win32" && WINDOWS_HOLD.has(error?.code); + if (!held || attempt >= HOLD_BACKOFF_MS.length) throw error; + sleepMs(HOLD_BACKOFF_MS[attempt]); + } + } +} + +/** Sync sleep (no busy-spin). */ +export function sleepMs(ms) { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); +} diff --git a/skills/hyperframes/scripts/lib/link-safe-write.test.mjs b/skills/hyperframes/scripts/lib/link-safe-write.test.mjs new file mode 100644 index 0000000000..a2785ec8b0 --- /dev/null +++ b/skills/hyperframes/scripts/lib/link-safe-write.test.mjs @@ -0,0 +1,76 @@ +import assert from "node:assert/strict"; +import { + linkSync, + lstatSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + symlinkSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { test } from "node:test"; +import { ownFolder, replaceFile, replaceFileWith } from "./link-safe-write.mjs"; + +function fixture(t) { + const root = mkdtempSync(join(tmpdir(), "link-safe-write-")); + t.after(() => rmSync(root, { recursive: true, force: true })); + const project = join(root, "project"); + mkdirSync(project); + const victim = join(root, "victim.txt"); + writeFileSync(victim, "victim"); + return { root, project, victim }; +} + +for (const [kind, plant] of [ + ["symbolic link", (target, at) => symlinkSync(target, at)], + ["hard link", (target, at) => linkSync(target, at)], +]) { + test(`replaceFile and replaceFileWith replace a ${kind} at the name, never its target`, (t) => { + const { project, victim } = fixture(t); + for (const [name, write] of [ + ["a.json", (path) => replaceFile(path, "new")], + ["b.png", (path) => replaceFileWith(path, (temp) => writeFileSync(temp, "new"))], + ]) { + const path = join(project, name); + plant(victim, path); + write(path); + assert.equal(readFileSync(victim, "utf8"), "victim"); + assert.equal(readFileSync(path, "utf8"), "new"); + const entry = lstatSync(path); + assert.equal(entry.isFile(), true); + assert.equal(entry.nlink, 1); + } + assert.deepEqual(readdirSync(project).sort(), ["a.json", "b.png"]); + }); +} + +test("replaceFileWith leaves the name as it was and no temp file when the write fails", (t) => { + const { project } = fixture(t); + const path = join(project, "out.mp4"); + writeFileSync(path, "old"); + assert.throws( + () => + replaceFileWith(path, (temp) => { + writeFileSync(temp, "half"); + throw new Error("encoder failed"); + }), + /encoder failed/, + ); + assert.equal(readFileSync(path, "utf8"), "old"); + assert.deepEqual(readdirSync(project), ["out.mp4"]); +}); + +test("ownFolder refuses a folder that is a link and makes nothing through it", (t) => { + const { root, project } = fixture(t); + const elsewhere = join(root, "elsewhere"); + mkdirSync(elsewhere); + symlinkSync(elsewhere, join(project, "frames-basemap"), "dir"); + assert.throws(() => ownFolder(project, "frames-basemap/sub"), /is a link/); + assert.deepEqual(readdirSync(elsewhere), []); + assert.equal(ownFolder(project, "frames-real"), join(project, "frames-real")); + assert.equal(lstatSync(join(project, "frames-real")).isDirectory(), true); +}); diff --git a/skills/hyperframes/scripts/locate.mjs b/skills/hyperframes/scripts/locate.mjs index 4132d9432e..23f23e52fb 100644 --- a/skills/hyperframes/scripts/locate.mjs +++ b/skills/hyperframes/scripts/locate.mjs @@ -23,6 +23,7 @@ import "./lib/windows-exe-search.mjs"; import { execFileSync } from "node:child_process"; import { existsSync, mkdirSync } from "node:fs"; +import { replaceFileWith } from "./lib/link-safe-write.mjs"; import { assertLiteralMediaPath } from "./lib/literal-media-input.mjs"; const N1 = 9, @@ -33,10 +34,17 @@ const GREEN = "0x3CDC5A", BLUE = "0x3C82FF", RED = "0xFF3232"; -const ff = (args) => - execFileSync("ffmpeg", ["-v", "error", "-y", ...args], { - stdio: ["ignore", "ignore", "inherit"], - }); +// A PNG written beside `dst` and renamed over it: a link already at `dst` is replaced, never written through. +const ff = (args, dst) => + replaceFileWith(dst, (temp) => + execFileSync( + "ffmpeg", + ["-v", "error", "-y", ...args, "-f", "image2", "-c:v", "png", "-update", "1", temp], + { + stdio: ["ignore", "ignore", "inherit"], + }, + ), + ); function probe(img) { const out = execFileSync("ffprobe", [ "-v", @@ -111,8 +119,8 @@ if (cmd === "overlay") { const n = Number(opt.n || N1); const { w, h } = probe(img); const fz = Math.max(16, Math.round(Math.min(w, h) / 22)); - ff(["-i", img, "-vf", gridFilters(w, h, n, "v", fz).join(","), `${dir}/gv.png`]); - ff(["-i", img, "-vf", gridFilters(w, h, n, "h", fz).join(","), `${dir}/gh.png`]); + ff(["-i", img, "-vf", gridFilters(w, h, n, "v", fz).join(",")], `${dir}/gv.png`); + ff(["-i", img, "-vf", gridFilters(w, h, n, "h", fz).join(",")], `${dir}/gh.png`); out({ w, h, @@ -135,17 +143,19 @@ if (cmd === "overlay") { const uw = Math.max(cw, 640), uh = Math.round((ch * uw) / cw); const fz = Math.max(15, Math.round(Math.min(uw, uh) / 16)); - ff([ - "-i", - img, - "-vf", + ff( [ - `crop=${cw}:${ch}:${cx}:${cy}`, - `scale=${uw}:${uh}`, - ...gridFilters(uw, uh, nf, "both", fz), - ].join(","), + "-i", + img, + "-vf", + [ + `crop=${cw}:${ch}:${cx}:${cy}`, + `scale=${uw}:${uh}`, + ...gridFilters(uw, uh, nf, "both", fz), + ].join(","), + ], `${dir}/gc.png`, - ]); + ); out({ region: reg.map(r4), crop_grid: `${dir}/gc.png`, @@ -179,7 +189,7 @@ if (cmd === "overlay") { const bw = Math.max(2, Math.round((box[2] - box[0]) * w)), bh = Math.max(2, Math.round((box[3] - box[1]) * h)); const dst = opt.out || "./check.png"; - ff(["-i", img, "-vf", `drawbox=x=${bx}:y=${by}:w=${bw}:h=${bh}:color=${RED}@1:t=6`, dst]); + ff(["-i", img, "-vf", `drawbox=x=${bx}:y=${by}:w=${bw}:h=${bh}:color=${RED}@1:t=6`], dst); out({ marked: dst, next: "READ it — red box on the target? If off, redo region/final with corrected strips.", diff --git a/skills/hyperframes/scripts/locate.test.mjs b/skills/hyperframes/scripts/locate.test.mjs index fa3058f7c5..78d409a4d1 100644 --- a/skills/hyperframes/scripts/locate.test.mjs +++ b/skills/hyperframes/scripts/locate.test.mjs @@ -1,7 +1,16 @@ import test from "node:test"; import assert from "node:assert/strict"; import { execFileSync, spawnSync } from "node:child_process"; -import { existsSync, lstatSync, mkdtempSync, rmSync } from "node:fs"; +import { + existsSync, + lstatSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + symlinkSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; @@ -49,3 +58,55 @@ test( } }, ); + +function grayImage(path) { + execFileSync("ffmpeg", [ + "-v", + "error", + "-f", + "lavfi", + "-i", + "color=c=gray:s=320x180", + "-frames:v", + "1", + path, + ]); +} + +// fails without the fix: ffmpeg -y opened each output by name, so a link planted there had its target overwritten. +function linkedOutputsStayLinksTargets(t, steps) { + const dir = mkdtempSync(join(tmpdir(), "locate-links-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + const project = join(dir, "project"); + mkdirSync(project); + const image = join(project, "in.png"); + grayImage(image); + for (const [args, names] of steps) { + for (const name of names) { + writeFileSync(join(dir, `victim-${name}`), "victim"); + symlinkSync(join(dir, `victim-${name}`), join(project, name)); + } + execFileSync(process.execPath, [LOCATE, args[0], image, ...args.slice(1)], { + cwd: project, + stdio: ["ignore", "ignore", "inherit"], + }); + for (const name of names) { + assert.equal(readFileSync(join(dir, `victim-${name}`), "utf8"), "victim", name); + assert.equal(lstatSync(join(project, name)).isFile(), true, name); + assert.equal(readFileSync(join(project, name)).subarray(1, 4).toString(), "PNG", name); + } + } +} + +test("mark replaces a link at check.png instead of writing through it", (t) => + linkedOutputsStayLinksTargets(t, [[["mark", "--box", "0.1,0.1,0.5,0.5"], ["check.png"]]])); + +test( + "overlay and region replace links at gv.png, gh.png and gc.png instead of writing through them", + { skip: !hasDrawtext() && "ffmpeg without the drawtext filter" }, + (t) => + linkedOutputsStayLinksTargets(t, [ + [["overlay"], ["gv.png", "gh.png"]], + [["region", "--vids", "4,5", "--hids", "4,5"], ["gc.png"]], + ]), +); diff --git a/skills/media-use/audio/scripts/extract-audio-data.py b/skills/media-use/audio/scripts/extract-audio-data.py index 839c211a7e..f0a6d1aa5f 100644 --- a/skills/media-use/audio/scripts/extract-audio-data.py +++ b/skills/media-use/audio/scripts/extract-audio-data.py @@ -17,6 +17,8 @@ Requirements: import argparse import json +import os +import secrets import subprocess import sys @@ -176,6 +178,19 @@ def extract(path: str, fps: int, n_bands: int) -> dict: } +def replace_file(path, text): + """Write `text` to a new temp file beside `path`, then rename it over: a link at `path` is replaced, not followed.""" + temp = f"{path}.hf{secrets.token_hex(3)}.tmp" # core's atomicTempPath shape, which Studio's project history skips + f = open(temp, "x", encoding="utf-8") # created exclusively: never a file someone else already put there + try: + with f: + f.write(text) + os.replace(temp, path) + except BaseException: + os.unlink(temp) + raise + + def main(): parser = argparse.ArgumentParser(description="Extract per-frame audio visualization data") parser.add_argument("input", help="Audio or video file") @@ -191,8 +206,7 @@ def main(): data = extract(args.input, args.fps, args.bands) - with open(args.output, "w", encoding="utf-8") as f: - json.dump(data, f) + replace_file(args.output, json.dumps(data)) print(f"Wrote {args.output} ({data['totalFrames']} frames, {data['bands']} bands)", file=sys.stderr) diff --git a/skills/media-use/audio/scripts/extract-audio-data.test.mjs b/skills/media-use/audio/scripts/extract-audio-data.test.mjs new file mode 100644 index 0000000000..2040f855f1 --- /dev/null +++ b/skills/media-use/audio/scripts/extract-audio-data.test.mjs @@ -0,0 +1,60 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { + linkSync, + lstatSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + symlinkSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { test } from "node:test"; + +const scripts = fileURLToPath(new URL(".", import.meta.url)); +const python = ["python3", "python"].find( + (name) => spawnSync(name, ["-c", "import sys; assert sys.version_info >= (3, 8)"]).status === 0, +); +// main() as the script runs it, with the analysis stubbed: numpy and ffmpeg are not what is under test. +const RUN = `import runpy, sys, types +sys.modules.setdefault("numpy", types.SimpleNamespace(ndarray=object)) +sys.path.insert(0, sys.argv[1]) +main = runpy.run_path(sys.argv[1] + "/extract-audio-data.py")["main"] +main.__globals__["extract"] = lambda path, fps, bands: {"totalFrames": 0, "bands": bands, "frames": []} +sys.argv = ["extract-audio-data.py", "in.mp3", "-o", sys.argv[2]] +main()`; + +for (const [kind, plant] of [ + ["symbolic link", (target, at) => symlinkSync(target, at)], + ["hard link", (target, at) => linkSync(target, at)], +]) { + // fails without the fix: main() wrote with open(path, "w"), which truncates the target of a link at path. + test( + `extract-audio-data replaces a ${kind} at audio-data.json, never its target`, + { skip: !python }, + (t) => { + const dir = mkdtempSync(join(tmpdir(), "audio-data-link-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + const victim = join(dir, "victim.txt"); + writeFileSync(victim, "victim"); + const out = join(dir, "audio-data.json"); + plant(victim, out); + const result = spawnSync(python, ["-c", RUN, scripts, out], { encoding: "utf8" }); + assert.equal(result.status, 0, result.stderr); + assert.equal(readFileSync(victim, "utf8"), "victim"); + assert.deepEqual(JSON.parse(readFileSync(out, "utf8")), { + totalFrames: 0, + bands: 16, + frames: [], + }); + const entry = lstatSync(out); + assert.equal(entry.isFile(), true); + assert.equal(entry.nlink, 1); + assert.deepEqual(readdirSync(dir).sort(), ["audio-data.json", "victim.txt"]); + }, + ); +} diff --git a/skills/media-use/scripts/lib/link-safe-write.mjs b/skills/media-use/scripts/lib/link-safe-write.mjs new file mode 100644 index 0000000000..6a0b0cf1b6 --- /dev/null +++ b/skills/media-use/scripts/lib/link-safe-write.mjs @@ -0,0 +1,86 @@ +import { randomBytes } from "node:crypto"; +import { lstatSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; + +// Writes into a folder someone else may have filled: a link already at a name is replaced or refused, never followed. + +/** Folder `rel` under `base`, made if missing; throws when any folder on the way is a link. */ +export function ownFolder(base, rel) { + let dir = base; + // Each folder is looked at before it is made, so nothing is ever made through a link. + for (const part of rel.split(/[\\/]/).filter(Boolean)) { + dir = join(dir, part); + if (lstatSync(dir, { throwIfNoEntry: false })?.isSymbolicLink()) { + throw new Error( + `${dir} is a link; media is written only into real folders, so nothing was written there`, + ); + } + mkdirSync(dir, { recursive: true }); + } + return dir; +} + +/** A new temp file beside `path` holding `content`, with a random name, created exclusively. */ +export function writeTempBeside(path, content) { + // Same shape as core atomicTempPath, which Studio's project history skips. + const temp = `${path}.hf${randomBytes(3).toString("hex")}.tmp`; + try { + writeFileSync(temp, content, { flag: "wx" }); + } catch (error) { + // EEXIST: the random name belongs to another writer, so it is left alone. A failed cleanup must not hide `error`. + if (error?.code !== "EEXIST") { + try { + rmSync(temp, { force: true }); + } catch {} + } + throw error; + } + return temp; +} + +/** Writes `content` to a temp file beside `path`, then renames it over: a link at `path` is replaced, not followed. */ +export function replaceFile(path, content) { + publish(writeTempBeside(path, content), path); +} + +/** As replaceFile, with `write(temp)` filling the temp file (an ffmpeg run, say); a throw leaves `path` as it was. */ +export function replaceFileWith(path, write) { + const temp = writeTempBeside(path, ""); + try { + write(temp); + } catch (error) { + rmSync(temp, { force: true }); + throw error; + } + publish(temp, path); +} + +function publish(temp, path) { + try { + renameRidingWindowsHolds(temp, path); + } catch (error) { + rmSync(temp, { force: true }); + throw error; + } +} + +// Windows refuses a rename for a moment while antivirus or a just-exited process still holds the file. +const WINDOWS_HOLD = new Set(["EPERM", "EACCES", "EBUSY"]); +const HOLD_BACKOFF_MS = [10, 20, 40, 80, 160, 320, 640]; + +function renameRidingWindowsHolds(from, to) { + for (let attempt = 0; ; attempt++) { + try { + return renameSync(from, to); + } catch (error) { + const held = process.platform === "win32" && WINDOWS_HOLD.has(error?.code); + if (!held || attempt >= HOLD_BACKOFF_MS.length) throw error; + sleepMs(HOLD_BACKOFF_MS[attempt]); + } + } +} + +/** Sync sleep (no busy-spin). */ +export function sleepMs(ms) { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); +} diff --git a/skills/media-use/scripts/lib/manifest.mjs b/skills/media-use/scripts/lib/manifest.mjs index dee46b397a..648ebcddaa 100644 --- a/skills/media-use/scripts/lib/manifest.mjs +++ b/skills/media-use/scripts/lib/manifest.mjs @@ -8,13 +8,15 @@ import { writeFileSync, writeSync, rmSync, - renameSync, lstatSync, realpathSync, constants, } from "node:fs"; import { randomBytes } from "node:crypto"; import { basename, join } from "node:path"; +import { ownFolder, replaceFile, sleepMs, writeTempBeside } from "./link-safe-write.mjs"; + +export { ownFolder, replaceFile, writeTempBeside }; const MANIFEST_FILE = "manifest.jsonl"; const INDEX_FILE = "index.md"; @@ -93,22 +95,6 @@ export function ownTypeDir(projectDir, type) { return ownFolder(ownMediaDir(projectDir), typeSubdir(type)); } -/** Folder `rel` under `base`, made if missing; throws when any folder on the way is a link. */ -export function ownFolder(base, rel) { - let dir = base; - // Each folder is looked at before it is made, so nothing is ever made through a link. - for (const part of rel.split(/[\\/]/).filter(Boolean)) { - dir = join(dir, part); - if (lstatSync(dir, { throwIfNoEntry: false })?.isSymbolicLink()) { - throw new Error( - `${dir} is a link; media is written only into real folders, so nothing was written there`, - ); - } - mkdirSync(dir, { recursive: true }); - } - return dir; -} - /** Throws when `path` is a link. */ export function refuseLink(path) { if (lstatSync(path, { throwIfNoEntry: false })?.isSymbolicLink()) { @@ -116,51 +102,6 @@ export function refuseLink(path) { } } -/** A new temp file beside `path` holding `content`, with a random name, created exclusively. */ -export function writeTempBeside(path, content) { - // Same shape as core atomicTempPath, which Studio's project history skips. - const temp = `${path}.hf${randomBytes(3).toString("hex")}.tmp`; - try { - writeFileSync(temp, content, { flag: "wx" }); - } catch (error) { - // EEXIST: the random name belongs to another writer, so it is left alone. A failed cleanup must not hide `error`. - if (error?.code !== "EEXIST") { - try { - rmSync(temp, { force: true }); - } catch {} - } - throw error; - } - return temp; -} - -/** Writes `content` to a temp file beside `path`, then renames it over: a link at `path` is replaced, not followed. */ -export function replaceFile(path, content) { - const temp = writeTempBeside(path, content); - try { - renameRidingWindowsHolds(temp, path); - } catch (error) { - rmSync(temp, { force: true }); - throw error; - } -} - -// Windows refuses a rename for a moment while antivirus or a just-exited process still holds the file. -const WINDOWS_HOLD = new Set(["EPERM", "EACCES", "EBUSY"]); -const HOLD_BACKOFF_MS = [10, 20, 40, 80, 160, 320, 640]; - -function renameRidingWindowsHolds(from, to) { - for (let attempt = 0; ; attempt++) { - try { - return renameSync(from, to); - } catch (error) { - const held = process.platform === "win32" && WINDOWS_HOLD.has(error?.code); - if (!held || attempt >= HOLD_BACKOFF_MS.length) throw error; - sleepMs(HOLD_BACKOFF_MS[attempt]); - } - } -} - export function appendRecord(projectDir, record) { ownTypeDir(projectDir, record.type); @@ -257,11 +198,6 @@ export function nextId(projectDir, type) { return `${prefix}_${String(max + 1).padStart(3, "0")}`; } -// Sync sleep (no busy-spin) for the allocation lock retry. -function sleepMs(ms) { - Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); -} - // Coarse per-project lock so concurrent resolves don't race on id allocation. // ponytail: one lock file with a 15s stale-steal (a crashed holder can't wedge // the project); fine for agent-scale concurrency — revisit if throughput needs From 14d582c0f50e90c4820b8a54a78e0655e386754e Mon Sep 17 00:00:00 2001 From: Ular Kimsanov Date: Wed, 25 Nov 2026 05:02:23 +0000 Subject: [PATCH 07/17] fix(studio): apply-to-scope writes only the grading attribute, exactly as given (#8767) * fix(studio): apply-to-scope writes only the grading attribute, exactly as given patchMediaTag passed the new attribute to String.prototype.replace as a replacement string, so `$&`, `$'` and similar in a grading value were expanded from the old tag and could split the attribute. Its match also needed a quoted value, so an unquoted or valueless attribute was duplicated instead of replaced. It now walks the tag's attributes the way the browser reads them and slices out the data-color-grading spans: the first gets the new value, any later duplicate is removed. When a grading is copied to other media, an unknown preset id, an unknown color space, or a LUT source with a scheme other than http, https or data is dropped instead of being written into other files. Variable references stay. * fix(studio): apply-to-scope keeps a known bare preset id The attribute's short form is a preset id alone, which core reads as a preset. It is now kept when it is a known id or a variable reference instead of being refused as unreadable. The quick-save concurrency test applied the filler preset warm, which is not a preset; it applies warm-daylight now. * fix(studio): grading attribute scan splits on HTML whitespace, appends after the last attribute The scan used JavaScript's \s, which also splits on a no-break space that HTML keeps inside an unquoted value, so clearing a grade could cut the source. It now separates on HTML whitespace only. A new attribute goes after the last attribute the scan read, so the slash that ends an unquoted value such as src=images/ stays part of it. --- packages/core/src/colorGrading.ts | 4 + .../editor/colorGradingScopePatch.test.ts | 179 +++++++++++++++++- .../editor/colorGradingScopePatch.ts | 90 ++++++++- .../studioColorGradingScope.test.ts | 51 +++++ .../src/components/studioColorGradingScope.ts | 18 +- .../src/hooks/timelineQuickSaves.test.ts | 4 +- 6 files changed, 330 insertions(+), 16 deletions(-) create mode 100644 packages/studio/src/components/studioColorGradingScope.test.ts diff --git a/packages/core/src/colorGrading.ts b/packages/core/src/colorGrading.ts index d3a08bc3bc..8a8dbd514f 100644 --- a/packages/core/src/colorGrading.ts +++ b/packages/core/src/colorGrading.ts @@ -646,6 +646,10 @@ const PRESETS_BY_ID = new Map( const VARIABLE_REF_RE = /^\$(?:\{([A-Za-z0-9_.:-]+)\}|([A-Za-z0-9_.:-]+))$/; +export function isHfColorGradingVariableRef(value: unknown): boolean { + return typeof value === "string" && VARIABLE_REF_RE.test(value.trim()); +} + const ADJUST_LIMITS: Record = { exposure: { min: -2, max: 2 }, contrast: { min: -1, max: 1 }, diff --git a/packages/studio/src/components/editor/colorGradingScopePatch.test.ts b/packages/studio/src/components/editor/colorGradingScopePatch.test.ts index 0684cef339..c9a5e852ec 100644 --- a/packages/studio/src/components/editor/colorGradingScopePatch.test.ts +++ b/packages/studio/src/components/editor/colorGradingScopePatch.test.ts @@ -1,5 +1,9 @@ +// @vitest-environment happy-dom import { describe, expect, it } from "vitest"; -import { patchMediaColorGradingInHtml } from "./colorGradingScopePatch"; +import { + keepKnownColorGradingValues, + patchMediaColorGradingInHtml, +} from "./colorGradingScopePatch"; describe("patchMediaColorGradingInHtml", () => { it.each(['"', "'"])("replaces and removes long grading values quoted with %s", (quote) => { @@ -92,3 +96,176 @@ describe("patchMediaColorGradingInHtml", () => { ); }); }); + +function readTag(html: string): { names: string[]; grading: string | null } { + const element = new DOMParser().parseFromString(html, "text/html").querySelector("video"); + if (!element) throw new Error(`no video in ${html}`); + return { + names: element.getAttributeNames(), + grading: element.getAttribute("data-color-grading"), + }; +} + +describe("patchMediaColorGradingInHtml with replacement patterns in the value", () => { + const patterns = [ + "$&", + "$'", + "$`", + "$1", + "$$", + "$", + "' data-extra='x' a='", + '" data-extra="x" a="', + ]; + it.each(['"', "'"])("writes the value as given into a tag quoted with %s", (quote) => { + const old = quote === '"' ? "{"preset":"old"}" : '{"preset":"old"}'; + const before = ``; + for (const pattern of patterns) { + const value = JSON.stringify({ preset: `a${pattern}b`, lut: { src: `${pattern}.cube` } }); + const { html, count } = patchMediaColorGradingInHtml(before, value); + expect(count).toBe(1); + expect(readTag(html)).toEqual({ + names: ["id", "data-color-grading", "muted"], + grading: value, + }); + } + }); +}); + +describe("patchMediaColorGradingInHtml with other ways to write the attribute", () => { + it.each([ + ["unquoted", "data-color-grading=clean-studio"], + ["with no value", "data-color-grading"], + ["with spaces around =", "data-color-grading = 'x'"], + ])("replaces an attribute written %s", (_, attribute) => { + const before = ``; + const value = '{"preset":"mono-clean"}'; + expect(readTag(patchMediaColorGradingInHtml(before, value).html)).toEqual({ + names: ["data-color-grading", "src"], + grading: value, + }); + expect(patchMediaColorGradingInHtml(before, null).html).toBe(``); + }); + + it.each([ + [ + "its own unquoted value holding =", + `