diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index e7e1e63ed2..5b7f3067a4 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "hyperframes", "description": "HyperFrames by HeyGen. Write HTML, render video. Compositions, GSAP and runtime adapter animations, captions, voiceovers, audio-reactive visuals, and website capture for HyperFrames.", - "version": "0.8.166", + "version": "0.8.169", "author": { "name": "HeyGen", "email": "hyperframes@heygen.com", diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 5619aa6646..7584f4af32 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "hyperframes", "description": "Write HTML, render video. Compositions, Tailwind v4 styles, GSAP and runtime adapter animations, captions, voiceovers, audio-reactive visuals, and website capture for HyperFrames.", - "version": "0.8.166", + "version": "0.8.169", "author": { "name": "HeyGen", "email": "hyperframes@heygen.com", diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json index 19e3b67443..3ed3dbcef3 100644 --- a/.cursor-plugin/plugin.json +++ b/.cursor-plugin/plugin.json @@ -3,7 +3,7 @@ "name": "hyperframes", "displayName": "HyperFrames by HeyGen", "description": "Write HTML, render video. Compositions, Tailwind v4 styles, GSAP and runtime adapter animations, captions, voiceovers, audio-reactive visuals, and website capture for HyperFrames.", - "version": "0.8.166", + "version": "0.8.169", "author": { "name": "HeyGen", "email": "hyperframes@heygen.com" diff --git a/docs/changelog.mdx b/docs/changelog.mdx index d06c3f29a2..3ea87c13ea 100644 --- a/docs/changelog.mdx +++ b/docs/changelog.mdx @@ -8,6 +8,88 @@ Recent HyperFrames releases, including user-facing features, fixes, and migratio {/* New release entries are prepended by `bun run changelog:draft --write`. */} + +Rendering from inside an agent's macOS sandbox now works, because Chrome starts as one process instead of several that the sandbox blocks. + +## Fixes + +- **CLI:** Chrome starts inside an agent's macOS sandbox as one process over a pipe ([5e7ba0be944](https://github.com/heygen-com/hyperframes/commit/5e7ba0be944b076d514fc082c25a0b7e35eeb42f), [#5781](https://github.com/heygen-com/hyperframes/pull/5781)). +- **Gcp Cloud Run:** The BeginFrame contract image resolves the engine's core import ([b18b3e958aa](https://github.com/heygen-com/hyperframes/commit/b18b3e958aa199529fa5fa06728e81b97d520021), [#5785](https://github.com/heygen-com/hyperframes/pull/5785)). + +## Internal + +- **Studio:** The edit accuracy bench starts one server when node is a Volta shim ([c7151399769](https://github.com/heygen-com/hyperframes/commit/c71513997694f6f56e230d768b6f5c9ed7a73fab), [#5779](https://github.com/heygen-com/hyperframes/pull/5779)). + +[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.8.168...v0.8.169). + + + +Scrubbing back across a scene in the preview now shows its content instead of an empty frame. Cloud renders size their chunks to the worker limit and assemble in one pass, so long videos finish faster. + +## Features + +- **Producer:** Distributed renders accept 25 fps ([cc9e1bb33a4](https://github.com/heygen-com/hyperframes/commit/cc9e1bb33a430b878af6dcb257ce5c9a70f9f180), [#5423](https://github.com/heygen-com/hyperframes/pull/5423)). +- **Producer:** Render at 720p and 480p from a larger composition ([09c0307c3fd](https://github.com/heygen-com/hyperframes/commit/09c0307c3fd0318a7ea77e6b41df4e5d30a1902b), [#5724](https://github.com/heygen-com/hyperframes/pull/5724)). + +## Fixes + +- **Core:** Scrubbing back across a scene no longer leaves its content hidden ([4cf0e3a0e59](https://github.com/heygen-com/hyperframes/commit/4cf0e3a0e599c73a9a96efcee8f62099323a08cf), [#5766](https://github.com/heygen-com/hyperframes/pull/5766)). +- **Engine:** Local renders lay out width-only videos like the browser ([fc41fa277a5](https://github.com/heygen-com/hyperframes/commit/fc41fa277a5649eb4879b524192dd6bee39d7465), [#5771](https://github.com/heygen-com/hyperframes/pull/5771)). +- **CLI:** A browser a sandbox refuses says to rerun the command with escalation ([fa936691562](https://github.com/heygen-com/hyperframes/commit/fa9366915620ea9baa1d03b0eb44caaca013dc21), [#5734](https://github.com/heygen-com/hyperframes/pull/5734)). +- **CLI:** Check's dense overlap pass takes at most 240 samples, at clip windows first ([caea3863b07](https://github.com/heygen-com/hyperframes/commit/caea3863b075f5f79d1c77dd084d05ea05aa0529), [#5764](https://github.com/heygen-com/hyperframes/pull/5764)). +- **Lint:** Stop flagging dir on \; a render test now guards RTL export ([e6ce7337962](https://github.com/heygen-com/hyperframes/commit/e6ce73379620fb2abf73e0ab681e85fd7f938725), [#5744](https://github.com/heygen-com/hyperframes/pull/5744)). +- **Skills:** Regenerate manifest after HyperFrames guidance update ([40c64255e8c](https://github.com/heygen-com/hyperframes/commit/40c64255e8c0a3d11a0d6e8229b7a88877c84401), [#5747](https://github.com/heygen-com/hyperframes/pull/5747)). +- **CLI:** Honour HYPERFRAMES_SKIP_SKILLS in skills update and bare skills ([6dba67a0c3a](https://github.com/heygen-com/hyperframes/commit/6dba67a0c3a0a51247ab85bbc245f1cf3effa0dc), [#5743](https://github.com/heygen-com/hyperframes/pull/5743)). +- **CLI:** Timeline lists clips nested in a timed element and lint flags ones that never show ([eab6ca15b1a](https://github.com/heygen-com/hyperframes/commit/eab6ca15b1af7ec7bca0bbeb4cd0330e677467a5), [#5732](https://github.com/heygen-com/hyperframes/pull/5732)). +- **Engine:** A WebGPU block mounted as a sub-composition gets WebGPU like a root one ([4e6ee6d2300](https://github.com/heygen-com/hyperframes/commit/4e6ee6d2300290b638042ec88ef5afb7a0c27408), [#5735](https://github.com/heygen-com/hyperframes/pull/5735)). +- **Core:** A composition mounted twice keeps each mount's own timeline ([c38e9f350b4](https://github.com/heygen-com/hyperframes/commit/c38e9f350b4dbe6b09a6a35d5db0d437b9464220), [#5729](https://github.com/heygen-com/hyperframes/pull/5729)). + +## Performance + +- **Producer:** Assemble in one pass and keep its disk use under one output copy ([a498cf2032c](https://github.com/heygen-com/hyperframes/commit/a498cf2032c6b22492dedb475ad6196a8d6c6797), [#5768](https://github.com/heygen-com/hyperframes/pull/5768)). +- **Producer:** Size distributed chunks to the worker limit and concurrency ([c69fd2c6eca](https://github.com/heygen-com/hyperframes/commit/c69fd2c6ecadedff88cdc09d37854a658bffb733), [#5765](https://github.com/heygen-com/hyperframes/pull/5765)). + +## Internal + +- **Core:** One owner for the distributed fps set ([d5162beb50a](https://github.com/heygen-com/hyperframes/commit/d5162beb50a402a69423df106647347bd0f8763e), [#5756](https://github.com/heygen-com/hyperframes/pull/5756)). + +[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.8.167...v0.8.168). + + + +Long projects preview more smoothly: the preview's work now follows what is playing, not the total clip count. Bundling a project also stops freezing the app that runs it. + +## Fixes + +- **Core:** Bundling a project no longer blocks the host's thread on esbuild ([b1cf6e3c517](https://github.com/heygen-com/hyperframes/commit/b1cf6e3c517e227d1dca1b212e7637c19e502a64), [#5714](https://github.com/heygen-com/hyperframes/pull/5714)). +- **CLI:** Page loads stop timing out while a busy machine's Chrome warms up ([41486b9725a](https://github.com/heygen-com/hyperframes/commit/41486b9725ab2aae4f457d75dcd625931d103bb3), [#5705](https://github.com/heygen-com/hyperframes/pull/5705)). + +## Performance + +- **Core:** Hold a clip at 0 inside a later scene until it is due ([13ea8349597](https://github.com/heygen-com/hyperframes/commit/13ea8349597bbcb874402d1771aea65766fd7ffc), [#5716](https://github.com/heygen-com/hyperframes/pull/5716)). +- **Core:** A preview's composition scripts give the page a turn every 50 ms, not one long task ([12d8df37f4d](https://github.com/heygen-com/hyperframes/commit/12d8df37f4db8ccf019da32c97cc1352f8db9652), [#5713](https://github.com/heygen-com/hyperframes/pull/5713)). +- **Lint:** Strip stylesheet comments once per canvas zoom scan ([0bff8342c38](https://github.com/heygen-com/hyperframes/commit/0bff8342c389c1841d3b8d858168700f13627e48), [#5712](https://github.com/heygen-com/hyperframes/pull/5712)). +- **Core:** Preview runtime scales with what plays, not with the film's clip count ([d05bc4215d5](https://github.com/heygen-com/hyperframes/commit/d05bc4215d5757da86956217f4a8a4b2ab11b1fd), [#5674](https://github.com/heygen-com/hyperframes/pull/5674)). + +## Internal + +- **CLI:** Caption image test checks the close itself, not a reusable file number ([eace3d28b6c](https://github.com/heygen-com/hyperframes/commit/eace3d28b6cb721ec1f9a96d7d2ea76bf215551a), [#5707](https://github.com/heygen-com/hyperframes/pull/5707)). + +[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.8.166...v0.8.167). + + ` or `` renders correctly in preview and snapshot but produces a fully blank or black video from render — a confirmed, silent failure. `dir="ltr"` is not flagged. - -**Fix:** Remove `dir` from ``, keep `lang`, and scope the direction to individual text-containing elements instead — `direction: rtl` in CSS, or `dir="auto"` on the element. - ### `invalid_parent_traversal_in_asset_path` **Error.** Asset paths use `../` to traverse above the project root; render and preview clamp or misresolve them. diff --git a/gemini-extension.json b/gemini-extension.json index 7b7d98e37e..2118433d10 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,5 +1,5 @@ { "name": "hyperframes", - "version": "0.8.166", + "version": "0.8.169", "description": "HyperFrames by HeyGen. Write HTML, render video. Compositions, GSAP and runtime adapter animations, captions, voiceovers, audio-reactive visuals, and website capture for HyperFrames." } diff --git a/packages/aws-lambda/package.json b/packages/aws-lambda/package.json index 82b54243db..1a7e745e10 100644 --- a/packages/aws-lambda/package.json +++ b/packages/aws-lambda/package.json @@ -1,6 +1,6 @@ { "name": "@hyperframes/aws-lambda", - "version": "0.8.166", + "version": "0.8.169", "description": "AWS Lambda adapter for HyperFrames distributed rendering — handler, client-side SDK, and CDK construct.", "repository": { "type": "git", diff --git a/packages/aws-lambda/src/events.ts b/packages/aws-lambda/src/events.ts index 8b25122dc5..c15b52d679 100644 --- a/packages/aws-lambda/src/events.ts +++ b/packages/aws-lambda/src/events.ts @@ -164,7 +164,7 @@ interface PlanLambdaResultBase { PlanHash: string; ChunkCount: number; TotalFrames: number; - Fps: 24 | 30 | 60; + Fps: SerializableDistributedRenderConfig["fps"]; Width: number; Height: number; Format: DistributedFormat; diff --git a/packages/aws-lambda/src/handler.test.ts b/packages/aws-lambda/src/handler.test.ts index ec8a3d5404..9160725c19 100644 --- a/packages/aws-lambda/src/handler.test.ts +++ b/packages/aws-lambda/src/handler.test.ts @@ -15,7 +15,7 @@ * the glue's contract. */ -import { afterEach, beforeEach, describe, expect, it, mock } from "bun:test"; +import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from "bun:test"; import { createHash } from "node:crypto"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -247,6 +247,43 @@ describe("handler dispatch", () => { ).toBe(true); }); + it("plans against the function's own timeout unless the config pins one", async () => { + const seen: Array = []; + for (const pinned of [undefined, 300]) { + const tmpRoot = makeTmpRoot(); + const s3 = new FakeS3Client(); + s3.objects.set("s3://bucket/project.tar.gz", await makeMinimalProjectTar()); + await handler( + { + Action: "plan", + PlanProtocol: "v1", + ProjectS3Uri: "s3://bucket/project.tar.gz", + PlanOutputS3Prefix: "s3://bucket/renders/timeout/", + Config: { fps: 30, width: 640, height: 360, format: "mp4", workerTimeoutSeconds: pinned }, + }, + { + s3: s3 as unknown as import("@aws-sdk/client-s3").S3Client, + primitives: { + plan: mock(async (_dir: string, config: { workerTimeoutSeconds?: number }) => { + seen.push(config.workerTimeoutSeconds); + throw new Error("stop after config"); + }) as unknown as typeof import("@hyperframes/producer/distributed").plan, + renderChunk: mock(async () => { + throw new Error("unused"); + }) as unknown as typeof import("@hyperframes/producer/distributed").renderChunk, + assemble: mock(async () => { + throw new Error("unused"); + }) as unknown as typeof import("@hyperframes/producer/distributed").assemble, + }, + tmpRoot, + skipChromeResolution: true, + getRemainingTimeInMillis: () => 899_987, + }, + ).catch(() => undefined); + } + expect(seen).toEqual([900, 300]); + }); + it("normalizes producer workflow codes to Step Functions error names", async () => { for (const code of [ "PLAN_TOO_LARGE", @@ -257,6 +294,8 @@ describe("handler dispatch", () => { "VIDEO_SOURCE_UNRENDERABLE", "VIDEO_EXTRACTION_FAILED", "INVALID_VIDEO_METADATA", + "FORMAT_NOT_SUPPORTED_IN_DISTRIBUTED", + "CHUNK_EXCEEDS_WORKER_TIMEOUT", ] as const) { const tmpRoot = makeTmpRoot(); const s3 = new FakeS3Client(); @@ -619,6 +658,10 @@ describe("handler dispatch", () => { skipChromeResolution: true, }; + const logged: string[] = []; + const logSpy = spyOn(console, "log").mockImplementation((line: string) => { + logged.push(line); + }); const planned = await handler( { Action: "plan", @@ -627,7 +670,12 @@ describe("handler dispatch", () => { Config: { fps: 30, width: 640, height: 360, format: "mp4" }, }, deps, - ); + ).finally(() => logSpy.mockRestore()); + const stageLines = logged + .filter((line) => line.includes('"plan_stage"')) + .map((line) => JSON.parse(line) as { stage?: string; ms?: unknown }); + expect(stageLines.map((line) => line.stage)).toEqual(["download", "untar"]); + expect(stageLines.every((line) => typeof line.ms === "number")).toBe(true); expect(planned).toMatchObject({ PlanProtocol: "v2", PlanV2ManifestS3Uri: "s3://bucket/renders/v2/v2/manifest.json", diff --git a/packages/aws-lambda/src/handler.ts b/packages/aws-lambda/src/handler.ts index 08fc2caf39..4c8cbb5e0a 100644 --- a/packages/aws-lambda/src/handler.ts +++ b/packages/aws-lambda/src/handler.ts @@ -91,6 +91,11 @@ export interface HandlerDeps { tmpRoot?: string; /** Skip Chrome resolution (used by handler dispatch tests that mock renderChunk). */ skipChromeResolution?: boolean; + /** + * The Lambda runtime's `Context` arrives as this second argument and supplies it. Plan + * and chunk share one function, so its remaining time at plan start is the chunk limit. + */ + getRemainingTimeInMillis?: () => number; } /** @@ -162,7 +167,9 @@ function normalizeTerminalErrorName(error: unknown): void { candidate.code === "NOT_MEDIA_PAYLOAD" || candidate.code === "VIDEO_SOURCE_UNRENDERABLE" || candidate.code === "VIDEO_EXTRACTION_FAILED" || - candidate.code === "INVALID_VIDEO_METADATA" + candidate.code === "INVALID_VIDEO_METADATA" || + candidate.code === "FORMAT_NOT_SUPPORTED_IN_DISTRIBUTED" || + candidate.code === "CHUNK_EXCEEDS_WORKER_TIMEOUT" ) { candidate.name = candidate.code; } @@ -316,6 +323,14 @@ function primeRuntimeEnv(): void { // ── Plan ──────────────────────────────────────────────────────────────────── +function planConfig(event: PlanEvent, deps?: HandlerDeps): DistributedRenderConfig { + const remainingMs = deps?.getRemainingTimeInMillis?.(); + if (event.Config.workerTimeoutSeconds !== undefined || remainingMs === undefined) { + return { ...event.Config }; + } + return { ...event.Config, workerTimeoutSeconds: Math.ceil(remainingMs / 1000) }; +} + // The v1 handler owns one transactional download, plan, archive, upload, and cleanup lifecycle. // fallow-ignore-next-line complexity async function handlePlan(event: PlanEvent, deps?: HandlerDeps): Promise { @@ -323,6 +338,7 @@ async function handlePlan(event: PlanEvent, deps?: HandlerDeps): Promise> { const started = Date.now(); + const config = planConfig(event, deps); const s3 = deps?.s3 ?? getS3Client(); const primitive = deps?.primitives?.planV2WithPublisher ?? planV2WithPublisher; if (!deps?.skipChromeResolution && !process.env.PRODUCER_HEADLESS_SHELL_PATH) { @@ -413,14 +427,18 @@ async function handlePlanV2( const projectArchive = join(work, "project.tar.gz"); const projectDir = join(work, "project"); try { + let stageStarted = Date.now(); await downloadS3ObjectToFile(s3, event.ProjectS3Uri, projectArchive); + logEvent({ event: "plan_stage", stage: "download", ms: Date.now() - stageStarted }); + stageStarted = Date.now(); await untarDirectory(projectArchive, projectDir); + logEvent({ event: "plan_stage", stage: "untar", ms: Date.now() - stageStarted }); const publisher = new S3PlanV2ArtifactPublisher({ s3, planOutputS3Prefix: event.PlanOutputS3Prefix, temporaryRoot: work, }); - const manifest: PlanV2Manifest = await primitive(projectDir, { ...event.Config }, publisher, { + const manifest: PlanV2Manifest = await primitive(projectDir, config, publisher, { stagingParentDir: work, }); @@ -663,7 +681,9 @@ async function handleAssembleV2( // `downloadAndMaterializePlanV2` materializes atomically. Audio is // assembler-only and lives at the familiar v1-compatible location. const audioPath = resolvePlanAudioPath(planDir); + const chunksStarted = Date.now(); const chunkPaths = await downloadChunkObjects(s3, event.ChunkS3Uris, work, event.Format); + const chunksMs = Date.now() - chunksStarted; const finalOutput = event.Format === "png-sequence" ? join(work, "output-frames") @@ -671,6 +691,7 @@ async function handleAssembleV2( const result = await primitive(planDir, chunkPaths, audioPath, finalOutput, { cfr: event.Cfr === true, }); + const uploadStarted = Date.now(); if (event.Format === "png-sequence") { const tarball = `${finalOutput}.tar.gz`; await tarDirectory(finalOutput, tarball); @@ -678,6 +699,13 @@ async function handleAssembleV2( } else { await uploadFileToS3(s3, finalOutput, event.OutputS3Uri); } + logEvent({ + event: "assemble_stages", + planMs: chunksStarted - started, + chunksMs, + assembleMs: result.durationMs, + uploadMs: Date.now() - uploadStarted, + }); return { Action: "assemble", OutputS3Uri: event.OutputS3Uri, diff --git a/packages/aws-lambda/src/s3PlanV2Publisher.test.ts b/packages/aws-lambda/src/s3PlanV2Publisher.test.ts index 94a35a6e68..9b437f9cf3 100644 --- a/packages/aws-lambda/src/s3PlanV2Publisher.test.ts +++ b/packages/aws-lambda/src/s3PlanV2Publisher.test.ts @@ -19,12 +19,14 @@ interface PutOperation { class FakeS3 { readonly objects = new Map(); readonly puts: PutOperation[] = []; + sends = 0; asClient(): import("@aws-sdk/client-s3").S3Client { return this as unknown as import("@aws-sdk/client-s3").S3Client; } async send(command: unknown): Promise { + this.sends += 1; // AWS command inputs are the runtime boundary exercised by this fake. const value = command as unknown as { readonly constructor: { readonly name: string }; @@ -139,6 +141,22 @@ describe("S3PlanV2ArtifactPublisher", () => { expect(s3.objects.get(manifestUri)?.bytes.toString("utf8")).toBe(manifest); }); + it("sends nothing for a digest it already published", async () => { + const source = makeSource("hello"); + const s3 = new FakeS3(); + const publisher = new S3PlanV2ArtifactPublisher({ + s3: s3.asClient(), + planOutputS3Prefix: "s3://bucket/render", + temporaryRoot: source.root, + }); + const blob = { sourcePath: source.path, sha256: source.digest, sizeBytes: source.sizeBytes }; + + await publisher.putBlob(blob); + const sendsAfterFirst = s3.sends; + await publisher.putBlob(blob); + expect(s3.sends).toBe(sendsAfterFirst); + }); + it("refuses to expose a manifest that references an unpublished digest", async () => { const source = makeSource("hello"); const s3 = new FakeS3(); diff --git a/packages/aws-lambda/src/s3PlanV2Publisher.ts b/packages/aws-lambda/src/s3PlanV2Publisher.ts index afcb45928e..8eee0d8681 100644 --- a/packages/aws-lambda/src/s3PlanV2Publisher.ts +++ b/packages/aws-lambda/src/s3PlanV2Publisher.ts @@ -83,6 +83,7 @@ export class S3PlanV2ArtifactPublisher implements PlanV2ArtifactPublisher { async putBlob(blob: Readonly): Promise { this.#assertOpen("publish a blob"); const digest = assertSha256(blob.sha256, "S3 published blob sha256"); + if (this.#publishedDigests.has(digest)) return; const sourceSize = statSync(blob.sourcePath).size; if (sourceSize !== blob.sizeBytes) { throw new PlanV2IntegrityError( diff --git a/packages/aws-lambda/src/s3Transport.test.ts b/packages/aws-lambda/src/s3Transport.test.ts index cd101ad090..6e5ea6dd58 100644 --- a/packages/aws-lambda/src/s3Transport.test.ts +++ b/packages/aws-lambda/src/s3Transport.test.ts @@ -6,6 +6,7 @@ */ import { afterAll, beforeAll, describe, expect, it } from "bun:test"; +import { createHash } from "node:crypto"; import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -116,6 +117,19 @@ describe("content-addressed v2 artifacts", () => { expect(s3.putCount).toBe(1); }); + it("leaves verifying the local bytes to the S3 checksum instead of hashing them again", async () => { + const source = join(scratchRoot, "artifact-changed.bin"); + writeFileSync(source, "bytes that changed"); + const digest = createHash("sha256").update("bytes as hashed").digest("hex"); + const uri = `s3://bucket/v2/artifacts/sha256/${digest.slice(0, 2)}/${digest}`; + const s3 = new ContentAddressedFakeS3(); + + await expect( + uploadContentAddressedFileToS3(s3.asClient(), source, uri, digest), + ).rejects.toMatchObject({ name: "BadDigest" }); + expect(s3.objects.has(uri)).toBe(false); + }); + it("refuses to overwrite an immutable key with conflicting metadata", async () => { const source = join(scratchRoot, "artifact-conflict.bin"); writeFileSync(source, "expected bytes"); @@ -199,6 +213,7 @@ class ContentAddressedFakeS3 { Key: string; Body?: NodeJS.ReadableStream; Metadata?: Record; + ChecksumSHA256?: string; }; }; const uri = `s3://${value.input.Bucket}/${value.input.Key}`; @@ -238,6 +253,12 @@ class ContentAddressedFakeS3 { const chunks: Buffer[] = []; for await (const chunk of value.input.Body ?? []) chunks.push(Buffer.from(chunk)); const bytes = Buffer.concat(chunks); + const checksum = createHash("sha256").update(bytes).digest("base64"); + if (value.input.ChecksumSHA256 !== undefined && value.input.ChecksumSHA256 !== checksum) { + const error = new Error("checksum mismatch"); + error.name = "BadDigest"; + throw error; + } this.objects.set(uri, { bytes, sha256: value.input.Metadata?.sha256 ?? "", diff --git a/packages/aws-lambda/src/s3Transport.ts b/packages/aws-lambda/src/s3Transport.ts index 5efbac7be1..379fa147ab 100644 --- a/packages/aws-lambda/src/s3Transport.ts +++ b/packages/aws-lambda/src/s3Transport.ts @@ -131,11 +131,9 @@ export async function uploadFileToS3( } /** - * Upload one content-addressed plan-v2 artifact exactly once. - * - * Existing objects are reused only when their immutable digest metadata and - * byte length agree. A conflicting object is never overwritten: doing so - * could change a plan already being consumed by another chunk invocation. + * Upload one content-addressed plan-v2 artifact exactly once; S3 verifies the bytes against + * `ChecksumSHA256`. An existing object is reused only when its digest metadata and length agree, + * and a conflicting one is never overwritten, since a chunk may already be reading that plan. */ export async function uploadContentAddressedFileToS3( client: S3Client, @@ -148,15 +146,6 @@ export async function uploadContentAddressedFileToS3( if (!existsSync(localPath)) { throw new Error(`[s3Transport] upload source missing: ${localPath}`); } - const actualSha256 = await sha256File(localPath); - if (actualSha256 !== expectedSha256) { - const error = new Error( - `[s3Transport] PLAN_ARTIFACT_DIGEST_MISMATCH: local artifact ${localPath} expected ${expectedSha256}, got ${actualSha256}`, - ); - error.name = "PLAN_ARTIFACT_DIGEST_MISMATCH"; - throw error; - } - const { bucket, key } = parseS3Uri(uri); const size = statSync(localPath).size; const existing = await inspectContentAddressedObject(client, bucket, key, size, expectedSha256); diff --git a/packages/aws-lambda/src/sdk/renderToLambda.test.ts b/packages/aws-lambda/src/sdk/renderToLambda.test.ts index bb9007bb06..9e36eeaf15 100644 --- a/packages/aws-lambda/src/sdk/renderToLambda.test.ts +++ b/packages/aws-lambda/src/sdk/renderToLambda.test.ts @@ -173,7 +173,7 @@ describe("renderToLambda", () => { projectDir, bucketName: "test-bucket", stateMachineArn: "arn:aws:states:us-east-1:1234:stateMachine:hf", - config: { ...baseConfig, fps: 25 as 24 | 30 | 60 }, + config: { ...baseConfig, fps: 50 as never }, sfn: asSFNClient(sfn), s3: asS3Client(s3), }); diff --git a/packages/aws-lambda/src/sdk/validateConfig.test.ts b/packages/aws-lambda/src/sdk/validateConfig.test.ts index daf2250f7d..8edba86ae1 100644 --- a/packages/aws-lambda/src/sdk/validateConfig.test.ts +++ b/packages/aws-lambda/src/sdk/validateConfig.test.ts @@ -20,6 +20,11 @@ describe("validateDistributedRenderConfig", () => { expect(validateDistributedRenderConfig(VALID)).toBe(VALID); }); + it("accepts 25 fps", () => { + const cfg: SerializableDistributedRenderConfig = { ...VALID, fps: 25 }; + expect(validateDistributedRenderConfig(cfg)).toBe(cfg); + }); + it("accepts optional fields when valid", () => { const cfg: SerializableDistributedRenderConfig = { ...VALID, @@ -39,7 +44,7 @@ describe("validateDistributedRenderConfig", () => { ["null config", null as unknown as SerializableDistributedRenderConfig, "config"], [ "wrong fps", - { ...VALID, fps: 25 as 24 | 30 | 60 } satisfies SerializableDistributedRenderConfig, + { ...VALID, fps: 50 as never } satisfies SerializableDistributedRenderConfig, "config.fps", ], [ @@ -116,6 +121,16 @@ describe("validateDistributedRenderConfig", () => { { ...VALID, maxParallelChunks: 0 } satisfies SerializableDistributedRenderConfig, "config.maxParallelChunks", ], + [ + "workerTimeoutSeconds 0", + { ...VALID, workerTimeoutSeconds: 0 } satisfies SerializableDistributedRenderConfig, + "config.workerTimeoutSeconds", + ], + [ + "fractional workerConcurrency", + { ...VALID, workerConcurrency: 1.5 } satisfies SerializableDistributedRenderConfig, + "config.workerConcurrency", + ], [ "unknown runtimeCap", { diff --git a/packages/cli/package.json b/packages/cli/package.json index 0633a353e7..fe903d7b53 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@hyperframes/cli", - "version": "0.8.166", + "version": "0.8.169", "description": "HyperFrames CLI — create, preview, and render HTML video compositions", "license": "Apache-2.0", "repository": { diff --git a/packages/cli/src/audio/analysis/targets.test.ts b/packages/cli/src/audio/analysis/targets.test.ts index cefc9b442f..1e02812ed2 100644 --- a/packages/cli/src/audio/analysis/targets.test.ts +++ b/packages/cli/src/audio/analysis/targets.test.ts @@ -20,6 +20,7 @@ function row( host: null, hostRow: null, children: [], + parentRow: null, trackIndex: 0, src: "audio/a.wav", sourceFile: null, diff --git a/packages/cli/src/browser/launch.ts b/packages/cli/src/browser/launch.ts index b31bb0b9dc..4417f9b094 100644 --- a/packages/cli/src/browser/launch.ts +++ b/packages/cli/src/browser/launch.ts @@ -7,6 +7,13 @@ import { import { normalizeErrorMessage } from "../utils/errorMessage.js"; import { requestCliExit } from "../utils/commandResult.js"; import { processIsAlive } from "../utils/processTree.js"; +import { + inAgentSandbox, + isOneProcessOverPipe, + machServiceDenied, + oneProcessOverPipe, + sandboxDeniedRemediation, +} from "./sandboxDenied.js"; export class BrowserCleanupError extends AggregateError {} @@ -55,9 +62,7 @@ export async function resolveManagedGpuMode( context.signal?.throwIfAborted(); const browser = await launchManagedBrowser(puppeteer, { ...options, - ...(context.noListen - ? { pipe: true, args: [...(options.args ?? []), "--single-process"] } - : {}), + ...(context.noListen ? oneProcessOverPipe(options) : {}), signal: context.signal, }); try { @@ -75,6 +80,29 @@ export async function resolveManagedGpuMode( export async function launchManagedBrowser( puppeteer: PuppeteerNode, options: LaunchOptions, +): Promise { + const sandboxed = isOneProcessOverPipe(options) || inAgentSandbox(); + try { + return await launchOwnedBrowser(puppeteer, sandboxed ? oneProcessOverPipe(options) : options); + } catch (error) { + const unnamedSeatbelt = !sandboxed && machServiceDenied(normalizeErrorMessage(error)); + if (!unnamedSeatbelt) throw withRemediation(error); + return launchOwnedBrowser(puppeteer, oneProcessOverPipe(options)).catch( + (retryError: unknown) => { + throw withRemediation(retryError); + }, + ); + } +} + +function withRemediation(error: unknown): unknown { + const remediation = sandboxDeniedRemediation(normalizeErrorMessage(error)); + return remediation ? new Error(remediation, { cause: error }) : error; +} + +async function launchOwnedBrowser( + puppeteer: PuppeteerNode, + options: LaunchOptions, ): Promise { if (shutdown) throw new Error("The CLI is stopping; no browser can start."); ownSignals(); diff --git a/packages/cli/src/browser/sandboxDenied.test.ts b/packages/cli/src/browser/sandboxDenied.test.ts new file mode 100644 index 0000000000..d5a63b3f32 --- /dev/null +++ b/packages/cli/src/browser/sandboxDenied.test.ts @@ -0,0 +1,71 @@ +import { EventEmitter } from "node:events"; +import type { Browser, LaunchOptions, PuppeteerNode } from "puppeteer-core"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { launchManagedBrowser } from "./launch.js"; + +const SEATBELT_LAUNCH_FAILURE = [ + "Failed to launch the browser process: Code: null", + "", + "stderr:", + "[1016/170315.389548:FATAL:base/apple/mach_port_rendezvous_mac.cc:159] Check failed: kr == KERN_SUCCESS. bootstrap_check_in org.chromium.Chromium.MachPortRendezvousServer.26166: Permission denied (1100)", +].join("\n"); + +const failingPuppeteer = (message: string) => + ({ launch: async (_: LaunchOptions) => Promise.reject(new Error(message)) }) as PuppeteerNode; + +describe("a browser launch a sandbox refuses", () => { + it("tells the caller to rerun with escalation instead of showing Chrome's crash", async () => { + await expect( + launchManagedBrowser(failingPuppeteer(SEATBELT_LAUNCH_FAILURE), {}), + ).rejects.toMatchObject({ + message: + "The browser can't start inside this sandbox: macOS refused Chrome's mach service (bootstrap_check_in: Permission denied).\nRerun this command with escalation, outside the sandbox.", + cause: { message: SEATBELT_LAUNCH_FAILURE }, + }); + }); + + it("leaves any other launch failure as it was", async () => { + const other = "Failed to launch the browser process: Code: 1"; + await expect(launchManagedBrowser(failingPuppeteer(other), {})).rejects.toThrow(other); + }); +}); + +const fakeBrowser = () => ({ process: () => new EventEmitter() }) as unknown as Browser; + +function recordingPuppeteer(failures: string[]) { + const launches: LaunchOptions[] = []; + const puppeteer = { + launch: async (options: LaunchOptions) => { + launches.push(options); + const failure = failures.shift(); + if (failure) throw new Error(failure); + return fakeBrowser(); + }, + } as unknown as PuppeteerNode; + return { puppeteer, launches }; +} + +describe("a browser inside an agent's macOS seatbelt", () => { + const platform = process.platform; + afterEach(() => { + vi.unstubAllEnvs(); + Object.defineProperty(process, "platform", { value: platform }); + }); + + it("starts as one process over a pipe when Codex names its seatbelt", async () => { + vi.stubEnv("CODEX_SANDBOX", "seatbelt"); + Object.defineProperty(process, "platform", { value: "darwin" }); + const { puppeteer, launches } = recordingPuppeteer([]); + await launchManagedBrowser(puppeteer, { args: ["--headless"] }); + expect(launches).toHaveLength(1); + expect(launches[0]).toMatchObject({ pipe: true, args: ["--headless", "--single-process"] }); + }); + + it("relaunches as one process over a pipe when an unnamed sandbox refuses the mach service", async () => { + vi.stubEnv("CODEX_SANDBOX", ""); + const { puppeteer, launches } = recordingPuppeteer([SEATBELT_LAUNCH_FAILURE]); + await expect(launchManagedBrowser(puppeteer, { args: ["--headless"] })).resolves.toBeDefined(); + expect(launches.map((options) => options.pipe ?? false)).toEqual([false, true]); + expect(launches[1]!.args).toEqual(["--headless", "--single-process"]); + }); +}); diff --git a/packages/cli/src/browser/sandboxDenied.ts b/packages/cli/src/browser/sandboxDenied.ts new file mode 100644 index 0000000000..2268846be2 --- /dev/null +++ b/packages/cli/src/browser/sandboxDenied.ts @@ -0,0 +1,36 @@ +import type { LaunchOptions } from "puppeteer-core"; + +const MACH_SERVICE_DENIED = /bootstrap_check_in\b[^\n]*Permission denied/; +const SINGLE_PROCESS = "--single-process"; + +export function machServiceDenied(errorMessage: string): boolean { + return MACH_SERVICE_DENIED.test(errorMessage); +} + +/** Codex runs agent commands in a macOS seatbelt, which names itself in the environment. */ +export function inAgentSandbox(env = process.env, platform = process.platform): boolean { + return platform === "darwin" && env.CODEX_SANDBOX === "seatbelt"; +} + +/** The one launch a seatbelt allows: no child process can register its mach port and nothing may listen. */ +export function oneProcessOverPipe(options: LaunchOptions): LaunchOptions { + const args = options.args ?? []; + return { + ...options, + pipe: true, + args: args.includes(SINGLE_PROCESS) ? args : [...args, SINGLE_PROCESS], + }; +} + +export function isOneProcessOverPipe(options: LaunchOptions): boolean { + return options.pipe === true && (options.args ?? []).includes(SINGLE_PROCESS); +} + +/** A process sandbox (an agent's macOS seatbelt) refused Chrome its mach service, so no browser starts here. */ +export function sandboxDeniedRemediation(errorMessage: string): string | undefined { + if (!machServiceDenied(errorMessage)) return undefined; + return [ + "The browser can't start inside this sandbox: macOS refused Chrome's mach service (bootstrap_check_in: Permission denied).", + "Rerun this command with escalation, outside the sandbox.", + ].join("\n"); +} diff --git a/packages/cli/src/capture/captureCompositionFrame.test.ts b/packages/cli/src/capture/captureCompositionFrame.test.ts index 16c23b80c6..cd9a3f5ea9 100644 --- a/packages/cli/src/capture/captureCompositionFrame.test.ts +++ b/packages/cli/src/capture/captureCompositionFrame.test.ts @@ -27,7 +27,7 @@ function fakeSeekPage() { const evaluate = vi.fn( async ( _pageFunction: Parameters[0], - _value?: number, + _value?: Parameters[1], _fallbackToBridgeAndTimelines?: boolean, ): Promise => undefined, ); @@ -108,7 +108,7 @@ describe("seekCompositionTimeline", () => { expect(waitForFunction).not.toHaveBeenCalled(); expect(evaluate).toHaveBeenCalledTimes(4); expect(evaluate).toHaveBeenNthCalledWith(1, expect.any(Function), 1.25, false, false); - expect(evaluate).toHaveBeenNthCalledWith(2, expect.any(Function)); + expect(evaluate).toHaveBeenNthCalledWith(2, expect.any(Function), { videoFrames: true }); expect(evaluate.mock.calls[2]?.[0]).toContain("window.setTimeout(finish, 100)"); // Post-seek font settle: a seek can reveal glyphs whose unicode-range // subsets only start loading after the next layout (CJK snapshot reports). @@ -230,7 +230,7 @@ describe("seekCompositionTimeline", () => { expect(evaluate).toHaveBeenCalledTimes(4); expect(evaluate).toHaveBeenNthCalledWith(1, expect.any(Function), 4, true, false); - expect(evaluate).toHaveBeenNthCalledWith(2, expect.any(Function)); + expect(evaluate).toHaveBeenNthCalledWith(2, expect.any(Function), { videoFrames: true }); expect(evaluate).toHaveBeenNthCalledWith(3, expect.any(Function)); expect(evaluate).toHaveBeenNthCalledWith(4, expect.any(Function), 500); }); @@ -471,6 +471,26 @@ describe("installPageFunctionGuard", () => { }); describe("DENSE_GEOMETRY_SEEK_OPTIONS", () => { + // A 79 s project of 1080p H.264 clips: each of the 600 dense seeks waited ~185 ms for a video frame it never reads, + // so `check` ran past its deadline. Frame sources and hf-seek work can move the DOM, so those still hold it. + it("skips only the seek barrier's video-frame holds, while the audit seek waits for all", async () => { + const barrierCalls = async (options: Parameters[2]) => { + const { page, evaluate } = fakeSeekPage(); + const barrier = vi.fn(async (_options?: { videoFrames?: boolean }) => {}); + vi.stubGlobal("window", { __hfWaitForSeekCompletion: barrier }); + evaluate.mockImplementation(async (pageFunction, value) => + typeof pageFunction === "function" && typeof value === "object" + ? Reflect.apply(pageFunction, undefined, [value]) + : undefined, + ); + await seekCompositionTimeline(page, 3, options); + return barrier.mock.calls; + }; + + expect(await barrierCalls(DENSE_GEOMETRY_SEEK_OPTIONS)).toEqual([[{ videoFrames: false }]]); + expect(await barrierCalls(AUDIT_SEEK_OPTIONS)).toEqual([[{ videoFrames: true }]]); + }); + it("is genuinely geometry-only — no post-seek settle waits at the 600-sample cap", () => { // Dense pass must not inherit AUDIT's post-seek waits — geometry is valid synchronously after setTime, and waits multiply by sample count. expect(DENSE_GEOMETRY_SEEK_OPTIONS.animationFrameSettle).toBe("none"); diff --git a/packages/cli/src/capture/captureCompositionFrame.ts b/packages/cli/src/capture/captureCompositionFrame.ts index a029db5ca8..7a1406004b 100644 --- a/packages/cli/src/capture/captureCompositionFrame.ts +++ b/packages/cli/src/capture/captureCompositionFrame.ts @@ -3,6 +3,7 @@ import { launchManagedBrowser, resolveManagedGpuMode, } from "../browser/launch.js"; +import { oneProcessOverPipe } from "../browser/sandboxDenied.js"; import { spawn } from "node:child_process"; import type { Browser, Page } from "puppeteer-core"; import type { InProcessRequest, InProcessResponse } from "../utils/staticProjectServer.js"; @@ -40,6 +41,7 @@ export const DENSE_GEOMETRY_SEEK_OPTIONS = { animationFrameSettle: "none", waitForFontsMs: 0, settleMs: 0, + waitForVideoFrames: false, } as const; export interface SeekCompositionTimelineOptions { @@ -49,18 +51,22 @@ export interface SeekCompositionTimelineOptions { animationFrameSettle?: "race" | "double" | "none"; waitForFontsMs?: number; settleMs?: number; + waitForVideoFrames?: boolean; } +type SeekBarrierOptions = { videoFrames: boolean }; + type CompositionPageFunction = | string | (() => unknown) | ((value: number) => unknown) + | ((barrier: SeekBarrierOptions) => unknown) | ((value: number, fallbackToBridgeAndTimelines: boolean, exactTime: boolean) => unknown); export interface CompositionEvaluationPage { evaluate( pageFunction: CompositionPageFunction, - value?: number, + value?: number | SeekBarrierOptions, fallbackToBridgeAndTimelines?: boolean, exactTime?: boolean, ): Promise; @@ -225,7 +231,7 @@ export async function openSettledCompositionPage( headless: true, signal: options.signal, executablePath, - ...(answer ? { pipe: true, args: [...args, "--single-process"] } : { args }), + ...(answer ? oneProcessOverPipe({ args }) : { args }), }); }; @@ -341,12 +347,15 @@ export async function seekCompositionTimeline( options.exactTime === true, ); - await page.evaluate(async () => { - const waitForCompletion = Reflect.get(window, "__hfWaitForSeekCompletion"); - if (typeof waitForCompletion === "function") { - await Reflect.apply(waitForCompletion, window, []); - } - }); + await page.evaluate( + async (barrier: SeekBarrierOptions) => { + const waitForCompletion = Reflect.get(window, "__hfWaitForSeekCompletion"); + if (typeof waitForCompletion === "function") { + await Reflect.apply(waitForCompletion, window, [barrier]); + } + }, + { videoFrames: options.waitForVideoFrames !== false }, + ); const animationFrameSettle = options.animationFrameSettle ?? "race"; if (animationFrameSettle === "race") { diff --git a/packages/cli/src/commands/check.test.ts b/packages/cli/src/commands/check.test.ts index a9c8f4473a..06f211f508 100644 --- a/packages/cli/src/commands/check.test.ts +++ b/packages/cli/src/commands/check.test.ts @@ -163,6 +163,7 @@ function fakeDriver(overrides: Partial = {}): CheckAuditDriver getDuration: vi.fn(async () => 9), hasNoTimelineDeclaration: vi.fn(async () => false), getTransitionBoundaries: vi.fn(async () => []), + getClipEdges: vi.fn(async () => []), getCanvas: vi.fn(async () => ({ width: 1920, height: 1080 })), findAmbiguousSelectors: vi.fn(async (_selectors: string[]) => []), seek: vi.fn(async (_time: number) => undefined), @@ -2312,6 +2313,58 @@ describe("dense motion-overlap re-sampling", () => { expect(driver.collectOverlap).toHaveBeenCalled(); expect(report.layout.findings.some((f) => f.code === "content_overlap")).toBe(true); }); + + it("keeps a long film's dense pass to a fixed number of seeks", async () => { + const clipEdges = Array.from({ length: 433 }, (_, i) => [i * 1.2, i * 1.2 + 1.1]).flat(); + const driver = fakeDriver({ + getDuration: vi.fn(async () => 540), + getClipEdges: async () => clipEdges, + }); + await runScenario(driver); + expect(vi.mocked(driver.seekGeometry).mock.calls.length).toBeLessThanOrEqual(240); + }); + + it("still promotes an overlap held on a long film", async () => { + const held = (time: number): boolean => time >= 200 && time <= 260; + const driver = fakeDriver({ + getDuration: vi.fn(async () => 540), + collectLayout: vi.fn(async (_time: number) => []), + collectOverlap: vi.fn(async (time: number) => + held(time) ? [layoutIssue("warning", { time, code: "content_overlap" })] : [], + ), + }); + const { report } = await runScenario(driver); + expect(report.layout.findings).toContainEqual( + expect.objectContaining({ code: "content_overlap", severity: "error" }), + ); + expect(vi.mocked(driver.seekGeometry).mock.calls.length).toBeLessThanOrEqual(240); + }); + + it("spends one hold probe on an overlap that stays the whole film", async () => { + const driver = fakeDriver({ + getDuration: vi.fn(async () => 540), + collectLayout: vi.fn(async (_time: number) => []), + collectOverlap: vi.fn(async (time: number) => [ + layoutIssue("warning", { time, code: "content_overlap" }), + ]), + }); + await runScenario(driver); + expect(vi.mocked(driver.seekGeometry).mock.calls.length).toBeLessThanOrEqual(181); + }); + + it("samples a short clip the uniform grid steps over", async () => { + const inShortClip = (time: number): boolean => time > 101 && time < 101.8; + const driver = fakeDriver({ + getDuration: vi.fn(async () => 540), + getClipEdges: async () => [101, 101.8], + collectLayout: vi.fn(async (_time: number) => []), + collectOverlap: vi.fn(async (time: number) => + inShortClip(time) ? [layoutIssue("warning", { time, code: "content_overlap" })] : [], + ), + }); + const { report } = await runScenario(driver); + expect(report.layout.findings.some((f) => f.code === "content_overlap")).toBe(true); + }); }); describe("scoped check", () => { diff --git a/packages/cli/src/commands/check.ts b/packages/cli/src/commands/check.ts index 2b32f9cae0..e981a77800 100644 --- a/packages/cli/src/commands/check.ts +++ b/packages/cli/src/commands/check.ts @@ -55,11 +55,12 @@ export interface CheckCommandDependencies { const DEFAULT_COMMAND_DEPENDENCIES: CheckCommandDependencies = { resolveProject, async runPipeline(project, options) { - const capture = await captureArtifactRevision(project.dir).catch(warnNotRecorded); + const capturing = captureArtifactRevision(project.dir).catch(warnNotRecorded); const report = await runCheckPipeline(project, options); const images = (files: readonly string[]) => files.map((file) => resolve(project.dir, file)); reportArtifacts("check", "frame", images(report.snapshots.files)); reportArtifacts("check", "finding", images(report.snapshots.findingFiles)); + const capture = await capturing; if (!capture) return report; try { return { ...report, saved: await saveCheckReport(project, options, report, capture) }; diff --git a/packages/cli/src/commands/checkArtifacts.test.ts b/packages/cli/src/commands/checkArtifacts.test.ts index 5093395768..79439f7b34 100644 --- a/packages/cli/src/commands/checkArtifacts.test.ts +++ b/packages/cli/src/commands/checkArtifacts.test.ts @@ -71,7 +71,7 @@ it("only warns when the report cannot be recorded; the exit status is the check' } }); -it("still reports the check when another process holds history", async () => { +it("still reports the check when another process holds history, without waiting for it", async () => { const project = mkdtempSync(join(tmpdir(), "hf-check-history-held-")); const log = vi.spyOn(console, "log").mockImplementation(() => undefined); const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); @@ -80,7 +80,8 @@ it("still reports the check when another process holds history", async () => { "Missing composition metadata", ); const previousWait = historyDeps.ownerWaitMs; - historyDeps.ownerWaitMs = 0; + // A wait for the holder outlasts the test: recording the report must not take it. + historyDeps.ownerWaitMs = 60_000; const held = await openProjectHistory({ projectDir: project, historyRoot: historyDeps.historyRoot, diff --git a/packages/cli/src/commands/checkCapture.test.ts b/packages/cli/src/commands/checkCapture.test.ts new file mode 100644 index 0000000000..b7f9db8949 --- /dev/null +++ b/packages/cli/src/commands/checkCapture.test.ts @@ -0,0 +1,52 @@ +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { runCommand } from "citty"; +import { expect, it, vi } from "vitest"; +import check from "./check.js"; +import { consumeCommandResult } from "../utils/commandResult.js"; +import type { CheckReport } from "../utils/checkPipeline.js"; + +// The history capture answers only once the check has started: a check that waits for it never runs. +const gate = vi.hoisted(() => { + let open = () => {}; + const opened = new Promise((resolve) => (open = resolve)); + return { opened, open: () => open() }; +}); + +vi.mock("../utils/artifactCapture.js", () => ({ + captureArtifactRevision: async () => { + await gate.opened; + return undefined; + }, +})); + +vi.mock("../utils/checkPipeline.js", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + runCheckPipeline: (...args: Parameters) => { + gate.open(); + return actual.runCheckPipeline(...args); + }, + }; +}); + +it("runs the check while its history capture is still under way", async () => { + const project = mkdtempSync(join(tmpdir(), "hf-check-capture-")); + const log = vi.spyOn(console, "log").mockImplementation(() => undefined); + writeFileSync( + join(project, "index.html"), + "Missing composition metadata", + ); + try { + await runCommand(check, { rawArgs: [project, "--json"] }); + const output = JSON.parse(String(log.mock.calls.at(-1)?.[0])) as CheckReport; + expect(output.browserSkipped).toBe(true); + expect(output).not.toHaveProperty("saved"); + } finally { + log.mockRestore(); + consumeCommandResult(); + rmSync(project, { recursive: true, force: true }); + } +}); diff --git a/packages/cli/src/commands/cloudrun.ts b/packages/cli/src/commands/cloudrun.ts index 804bc7f9c1..8973b640b4 100644 --- a/packages/cli/src/commands/cloudrun.ts +++ b/packages/cli/src/commands/cloudrun.ts @@ -29,7 +29,9 @@ import { validateVariablesAgainstProject, } from "../utils/variables.js"; import { normalizeErrorMessage } from "../utils/errorMessage.js"; -import { readAllowedCompositionFpsFromDir } from "../utils/compositionFps.js"; +import { defaultCloudFps } from "../utils/compositionFps.js"; +import { DISTRIBUTED_FPS, type DistributedFps, isDistributedFps } from "@hyperframes/core"; +import { isMissingPackageError, missingPackageMessage } from "../utils/missingPackage.js"; export const examples: Example[] = [ ["Deploy the Cloud Run render stack", "hyperframes cloudrun deploy --project my-gcp-project"], @@ -100,20 +102,11 @@ function loadCloudRunAdapter(): Promise { } export function isMissingCloudRunAdapterError(error: unknown): boolean { - return ( - (error as NodeJS.ErrnoException)?.code === "ERR_MODULE_NOT_FOUND" && - normalizeErrorMessage(error).includes("@hyperframes/gcp-cloud-run") - ); + return isMissingPackageError(error, "@hyperframes/gcp-cloud-run"); } export function missingCloudRunAdapterMessage(subcommand: string): string { - return ( - `${c.error("@hyperframes/gcp-cloud-run is not installed.")} The ${c.accent(`hyperframes cloudrun ${subcommand}`)} command needs it at runtime.\n` + - `Install it alongside the CLI:\n` + - ` ${c.accent("npm install -g @hyperframes/gcp-cloud-run")}\n` + - `Or, for an opt-in project setup:\n` + - ` ${c.accent("npm install @hyperframes/gcp-cloud-run")}` - ); + return missingPackageMessage("@hyperframes/gcp-cloud-run", `hyperframes cloudrun ${subcommand}`); } export default defineCommand({ @@ -167,7 +160,7 @@ export default defineCommand({ "site-id": { type: "string", description: "Explicit site id (overrides content hash)" }, width: { type: "string", description: "Render width in pixels" }, height: { type: "string", description: "Render height in pixels" }, - fps: { type: "string", description: "Render fps (24 | 30 | 60)" }, + fps: { type: "string", description: `Render fps (${DISTRIBUTED_FPS.join(" | ")})` }, format: { type: "string", description: "mp4 | mov | png-sequence | webm (default: mp4)" }, codec: { type: "string", description: "h264 | h265 (mp4 only)" }, quality: { type: "string", description: "draft | standard | high" }, @@ -529,11 +522,12 @@ function resolveCloudRunFps( args: Record, projectDir: string, command: "render" | "render-batch", -): 24 | 30 | 60 { - const fps = - parseIntFlag(args.fps) ?? readAllowedCompositionFpsFromDir(projectDir, [24, 30, 60]) ?? 30; - if (fps === 24 || fps === 30 || fps === 60) return fps; - console.error(`[cloudrun ${command}] --fps must be 24, 30, or 60; got ${fps}.`); +): DistributedFps { + const fps = parseIntFlag(args.fps) ?? defaultCloudFps(projectDir); + if (isDistributedFps(fps)) return fps; + console.error( + `[cloudrun ${command}] --fps must be one of ${DISTRIBUTED_FPS.join(", ")}; got ${fps}.`, + ); failCommand(); } diff --git a/packages/cli/src/commands/lambda.ts b/packages/cli/src/commands/lambda.ts index 5265602a08..b60edecd71 100644 --- a/packages/cli/src/commands/lambda.ts +++ b/packages/cli/src/commands/lambda.ts @@ -11,11 +11,12 @@ import { failCommand } from "../utils/commandResult.js"; import { defineCommand } from "citty"; import type { DistributedFormat } from "@hyperframes/aws-lambda/sdk"; -import { type CanvasResolution } from "@hyperframes/core"; +import { type CanvasResolution, DISTRIBUTED_FPS, isDistributedFps } from "@hyperframes/core"; import { parseOutputResolutionFlag } from "../utils/parseOutputResolution.js"; import type { Example } from "./_examples.js"; import { c } from "../ui/colors.js"; -import { readAllowedCompositionFpsFromDir } from "../utils/compositionFps.js"; +import { defaultCloudFps } from "../utils/compositionFps.js"; +import { isMissingPackageError, missingPackageMessage } from "../utils/missingPackage.js"; export const examples: Example[] = [ ["Deploy the Lambda render stack to AWS", "hyperframes lambda deploy"], @@ -126,12 +127,20 @@ export default defineCommand({ description: "Output resolution preset that engages Chrome deviceScaleFactor supersampling. Accepts canonical names (landscape, landscape-4k, portrait, portrait-4k, square, square-4k) and aliases (1080p, 4k, uhd, hd). When set, the composition's authored data-width/data-height is supersampled to the target preset without changing the layout.", }, - fps: { type: "string", description: "Render fps (24 | 30 | 60)" }, + fps: { type: "string", description: `Render fps (${DISTRIBUTED_FPS.join(" | ")})` }, format: { type: "string", description: "mp4 | mov | png-sequence | webm (default: mp4)" }, codec: { type: "string", description: "h264 | h265 (mp4 only)" }, quality: { type: "string", description: "draft | standard | high" }, - "chunk-size": { type: "string", description: "Frames per chunk (default: 240)" }, - "max-parallel-chunks": { type: "string", description: "Max concurrent chunks (default: 16)" }, + "chunk-size": { + type: "string", + description: + "Frames per chunk (default: sized so each chunk fits the Lambda timeout, one wave across --concurrency)", + }, + "max-parallel-chunks": { + type: "string", + description: + "Max chunks per render (default: one wave across the deploy's --concurrency, widened to fit the Lambda timeout)", + }, "target-chunk-frames": { type: "string", description: @@ -231,13 +240,9 @@ export default defineCommand({ try { await import("@hyperframes/aws-lambda/sdk"); } catch (err) { - if ((err as NodeJS.ErrnoException).code === "ERR_MODULE_NOT_FOUND") { + if (isMissingPackageError(err, "@hyperframes/aws-lambda")) { console.error( - `${c.error("@hyperframes/aws-lambda is not installed.")} The ${c.accent(`hyperframes lambda ${subcommand}`)} command needs it at runtime.\n` + - `Install it alongside the CLI:\n` + - ` ${c.accent("npm install -g @hyperframes/aws-lambda")}\n` + - `Or, for an opt-in dev setup:\n` + - ` ${c.accent("npm install @hyperframes/aws-lambda")}`, + missingPackageMessage("@hyperframes/aws-lambda", `hyperframes lambda ${subcommand}`), ); failCommand(); } @@ -296,12 +301,11 @@ export default defineCommand({ console.error("[lambda render] --width and --height are required."); failCommand(); } - const fpsRaw = - parseIntFlag(args.fps) ?? - readAllowedCompositionFpsFromDir(projectDir, [24, 30, 60]) ?? - 30; - if (fpsRaw !== 24 && fpsRaw !== 30 && fpsRaw !== 60) { - console.error(`[lambda render] --fps must be 24, 30, or 60; got ${fpsRaw}.`); + const fpsRaw = parseIntFlag(args.fps) ?? defaultCloudFps(projectDir); + if (!isDistributedFps(fpsRaw)) { + console.error( + `[lambda render] --fps must be one of ${DISTRIBUTED_FPS.join(", ")}; got ${fpsRaw}.`, + ); failCommand(); } const { runRender } = await import("./lambda/render.js"); @@ -353,12 +357,11 @@ export default defineCommand({ console.error("[lambda render-batch] --width and --height are required."); failCommand(); } - const fpsRaw = - parseIntFlag(args.fps) ?? - readAllowedCompositionFpsFromDir(projectDir, [24, 30, 60]) ?? - 30; - if (fpsRaw !== 24 && fpsRaw !== 30 && fpsRaw !== 60) { - console.error(`[lambda render-batch] --fps must be 24, 30, or 60; got ${fpsRaw}.`); + const fpsRaw = parseIntFlag(args.fps) ?? defaultCloudFps(projectDir); + if (!isDistributedFps(fpsRaw)) { + console.error( + `[lambda render-batch] --fps must be one of ${DISTRIBUTED_FPS.join(", ")}; got ${fpsRaw}.`, + ); failCommand(); } const { runRenderBatch } = await import("./lambda/render-batch.js"); diff --git a/packages/cli/src/commands/lambda/deploy.ts b/packages/cli/src/commands/lambda/deploy.ts index d6276c323f..10b18ea4d4 100644 --- a/packages/cli/src/commands/lambda/deploy.ts +++ b/packages/cli/src/commands/lambda/deploy.ts @@ -86,6 +86,7 @@ export async function runDeploy(args: Partial = {}): Promise { stateMachineArn: outputs.stateMachineArn, functionName: outputs.functionName, lambdaMemoryMb: resolved.lambdaMemoryMb, + reservedConcurrency: resolved.reservedConcurrency, deployedAt: new Date().toISOString(), }); diff --git a/packages/cli/src/commands/lambda/render-batch.test.ts b/packages/cli/src/commands/lambda/render-batch.test.ts index 16470ddcf5..81fa926db7 100644 --- a/packages/cli/src/commands/lambda/render-batch.test.ts +++ b/packages/cli/src/commands/lambda/render-batch.test.ts @@ -167,4 +167,8 @@ describe("buildLambdaBatchRenderConfig — aspect-agnostic wire threading", () = expect(config.outputResolution).toBe("portrait-4k"); expect(config.outputResolutionAspectAgnostic).toBeUndefined(); }); + + it("hands the deploy's reserved concurrency to the planner", () => { + expect(buildLambdaBatchRenderConfig(baseArgs, 64).workerConcurrency).toBe(64); + }); }); diff --git a/packages/cli/src/commands/lambda/render-batch.ts b/packages/cli/src/commands/lambda/render-batch.ts index a071122fd9..8aff5360e2 100644 --- a/packages/cli/src/commands/lambda/render-batch.ts +++ b/packages/cli/src/commands/lambda/render-batch.ts @@ -29,7 +29,7 @@ import type { SerializableDistributedRenderConfig, SiteHandle, } from "@hyperframes/aws-lambda/sdk"; -import type { CanvasResolution } from "@hyperframes/core"; +import type { CanvasResolution, DistributedFps } from "@hyperframes/core"; import { c } from "../../ui/colors.js"; import { errorBox } from "../../ui/format.js"; import { @@ -61,7 +61,7 @@ export interface RenderBatchArgs { */ siteId?: string; /** Composition config — fps/width/height/format required, rest optional. */ - fps: 24 | 30 | 60; + fps: DistributedFps; width: number; height: number; /** See {@link RenderArgs.outputResolution}. */ @@ -217,7 +217,10 @@ export async function runRenderBatch(args: RenderBatchArgs): Promise { failCommand(); } - const config: SerializableDistributedRenderConfig = buildLambdaBatchRenderConfig(args); + const config: SerializableDistributedRenderConfig = buildLambdaBatchRenderConfig( + args, + stack.reservedConcurrency, + ); // Deploy the site once and reuse it across every entry. --site-id and // --dry-run both skip the deploy via a synthesised handle. @@ -354,6 +357,7 @@ function makePlaceholderSiteHandle(siteId: string, bucketName: string): SiteHand */ export function buildLambdaBatchRenderConfig( args: RenderBatchArgs, + workerConcurrency?: number, ): SerializableDistributedRenderConfig { const config: SerializableDistributedRenderConfig = { fps: args.fps, @@ -366,6 +370,7 @@ export function buildLambdaBatchRenderConfig( chunkSize: args.chunkSize, maxParallelChunks: args.maxParallelChunks, targetChunkFrames: args.targetChunkFrames, + workerConcurrency, runtimeCap: "lambda", }; if (args.outputResolutionAspectAgnostic) { diff --git a/packages/cli/src/commands/lambda/render.test.ts b/packages/cli/src/commands/lambda/render.test.ts index ef3305f5ac..9c8648f74c 100644 --- a/packages/cli/src/commands/lambda/render.test.ts +++ b/packages/cli/src/commands/lambda/render.test.ts @@ -10,6 +10,7 @@ */ import { describe, expect, it } from "vitest"; +import lambdaCommand from "../lambda.js"; import { buildLambdaRenderConfig, type RenderArgs } from "./render.js"; const BASE_ARGS: RenderArgs = { @@ -55,3 +56,18 @@ describe("buildLambdaRenderConfig — aspect-agnostic wire threading", () => { expect(config.variables).toEqual({ alice: "hello" }); }); }); + +describe("lambda render chunk sizing", () => { + it("hands the deploy's reserved concurrency to the planner", () => { + expect(buildLambdaRenderConfig(BASE_ARGS, undefined, 64).workerConcurrency).toBe(64); + expect(buildLambdaRenderConfig(BASE_ARGS, undefined).workerConcurrency).toBeUndefined(); + }); + + it("help no longer claims --chunk-size defaults to 240", () => { + const chunkSizeArg = lambdaCommand.args + ? Reflect.get(lambdaCommand.args, "chunk-size") + : undefined; + expect(chunkSizeArg?.description).not.toContain("240"); + expect(chunkSizeArg?.description).toContain("timeout"); + }); +}); diff --git a/packages/cli/src/commands/lambda/render.ts b/packages/cli/src/commands/lambda/render.ts index 14063c1b54..358d900613 100644 --- a/packages/cli/src/commands/lambda/render.ts +++ b/packages/cli/src/commands/lambda/render.ts @@ -11,7 +11,7 @@ import type { DistributedFormat, SerializableDistributedRenderConfig, } from "@hyperframes/aws-lambda/sdk"; -import type { CanvasResolution } from "@hyperframes/core"; +import type { CanvasResolution, DistributedFps } from "@hyperframes/core"; import { c } from "../../ui/colors.js"; import { reportVariableIssues, @@ -32,7 +32,7 @@ export interface RenderArgs { stackName: string; siteId?: string; /** Composition config — fps/width/height/format required, rest optional. */ - fps: 24 | 30 | 60; + fps: DistributedFps; width: number; height: number; /** @@ -124,7 +124,11 @@ export async function runRender(args: RenderArgs): Promise { } } - const config: SerializableDistributedRenderConfig = buildLambdaRenderConfig(args, variables); + const config: SerializableDistributedRenderConfig = buildLambdaRenderConfig( + args, + variables, + stack.reservedConcurrency, + ); // When the caller passes only --site-id, synthesise the minimum-shape // SiteHandle pointing at the deterministic content-addressed key. The @@ -241,6 +245,7 @@ function sleep(ms: number): Promise { export function buildLambdaRenderConfig( args: RenderArgs, variables: Record | undefined, + workerConcurrency?: number, ): SerializableDistributedRenderConfig { const config: SerializableDistributedRenderConfig = { fps: args.fps, @@ -253,6 +258,7 @@ export function buildLambdaRenderConfig( chunkSize: args.chunkSize, maxParallelChunks: args.maxParallelChunks, targetChunkFrames: args.targetChunkFrames, + workerConcurrency, runtimeCap: "lambda", variables, }; diff --git a/packages/cli/src/commands/lambda/state.ts b/packages/cli/src/commands/lambda/state.ts index f55c53e53c..03d6158a9e 100644 --- a/packages/cli/src/commands/lambda/state.ts +++ b/packages/cli/src/commands/lambda/state.ts @@ -23,6 +23,7 @@ export interface StackOutputs { functionName: string; /** Lambda memory MB used during deploy; carried so cost math doesn't have to re-derive it. */ lambdaMemoryMb: number; + reservedConcurrency?: number; deployedAt: string; } diff --git a/packages/cli/src/commands/layout-audit.browser.js b/packages/cli/src/commands/layout-audit.browser.js index 9ba3269eb3..235733f938 100644 --- a/packages/cli/src/commands/layout-audit.browser.js +++ b/packages/cli/src/commands/layout-audit.browser.js @@ -704,9 +704,24 @@ return colorAlpha(getComputedStyle(element).color) >= 0.35; } + const RUNTIME_HIDDEN_CLIP = '[data-hf-clip-hidden][style*="visibility: hidden"]'; + + // Core's timedClipHide rule hides these clips' whole subtrees: skipping them bounds work by what is on screen. + function elementsOnScreenScenes(root) { + const elements = []; + const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, { + acceptNode: (element) => + element.matches(RUNTIME_HIDDEN_CLIP) ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT, + }); + for (let element = walker.nextNode(); element; element = walker.nextNode()) { + elements.push(element); + } + return elements; + } + function collectSolidTextBlocks(root) { const blocks = []; - for (const element of Array.from(root.querySelectorAll("*"))) { + for (const element of elementsOnScreenScenes(root)) { if (!isSolidTextBlock(element)) continue; const rects = visibleTextClientRects(element, true); const rect = unionRects(rects); diff --git a/packages/cli/src/commands/layout-audit.browser.test.ts b/packages/cli/src/commands/layout-audit.browser.test.ts index a30d4e31ce..7184a7787f 100644 --- a/packages/cli/src/commands/layout-audit.browser.test.ts +++ b/packages/cli/src/commands/layout-audit.browser.test.ts @@ -2360,6 +2360,32 @@ describe("layout-audit.browser content overlap", () => { }); }); + it("never reads inside a scene the runtime hid", () => { + document.body.innerHTML = ` +
+ +
Current scene line
+
+ `; + installOverlapStyles( + { a: "rgb(0, 0, 0)", b: "rgb(0, 0, 0)" }, + { a: "none", b: "none" }, + {}, + { host: "hidden", a: "visible", b: "visible" }, + ); + installOverlapGeometry({ + a: [rect({ left: 100, top: 100, width: 400, height: 100 })], + b: [rect({ left: 300, top: 120, width: 400, height: 100 })], + }); + installAuditScript(); + + const audit = (window as unknown as { __hyperframesOverlapAudit: OverlapAudit }) + .__hyperframesOverlapAudit; + expect(audit({ time: 1 })).toEqual([]); + const read = vi.mocked(window.getComputedStyle).mock.calls.map(([element]) => element.id); + expect(read).not.toContain("a"); + }); + // A typewriter span clipped to nothing (clip-path: inset(0 100% 0 0)) keeps a // normal box but paints zero pixels; overlapping it must not flag the visible // block beneath. The clipped element is unreachable by elementFromPoint, which @@ -3726,6 +3752,8 @@ interface AuditIssue { coveredFraction?: number; } +type OverlapAudit = (options: { time: number }) => AuditIssue[]; + function runAudit(options?: { proseCoverageFloor?: number }): AuditIssue[] { const audit = ( window as unknown as { diff --git a/packages/cli/src/commands/render.test.ts b/packages/cli/src/commands/render.test.ts index 7a8a78066c..752189d78a 100644 --- a/packages/cli/src/commands/render.test.ts +++ b/packages/cli/src/commands/render.test.ts @@ -1871,10 +1871,10 @@ describe("checkRenderResolutionPreflight", () => { expect(result?.kind).toBe("hdr-incompatible"); }); - it("classifies a preset smaller than the composition as downsampling", async () => { - // 3840×2160 comp + landscape (1920×1080): same 16:9 aspect, target smaller. + it("passes a preset smaller than the composition", async () => { + // 3840×2160 comp + landscape (1920×1080): same 16:9 aspect, rendered at 0.5× DPR. const result = await checkRenderResolutionPreflight(comp(3840, 2160), "landscape", noModes); - expect(result?.kind).toBe("downsampling"); + expect(result).toBeUndefined(); }); it("classifies a non-integer upscale as non-integer-scale", async () => { @@ -1944,12 +1944,18 @@ describe("checkRenderResolutionPreflight", () => { expect(result?.kind).toBe("hdr-incompatible"); }); - it("still flags downsampling + aspect-agnostic (same-orientation, smaller preset)", async () => { - // 3840×2160 comp with `--resolution 1080p` → `landscape` (1920×1080). - // Same orientation, but tier smaller than comp — user asked for a - // downsample. That's a real incompatibility, not an orientation swap. + it("passes `--resolution 1080p` on a 4K composition (a smaller, same-orientation preset)", async () => { const result = await checkRenderResolutionPreflight(comp(3840, 2160), "landscape", agnostic); - expect(result?.kind).toBe("downsampling"); + expect(result).toBeUndefined(); + }); + + it("never adapts `--resolution 4k` to another tier: a 1922×1080 composition is refused, not rendered at 480p", async () => { + const result = await checkRenderResolutionPreflight( + comp(1922, 1080), + "landscape-4k", + agnostic, + ); + expect(result?.kind).toBeDefined(); }); it("does NOT auto-clear when the flag was explicit (orientation-locked preset stays strict)", async () => { @@ -1983,14 +1989,10 @@ describe("checkRenderResolutionPreflight", () => { expect(result?.message).toMatch(/preset whose orientation matches|omit --resolution/i); }); - it("blocks a portrait-4K comp + `1080p` downsample early (orientation-flip masks the tier gap)", async () => { - // 2160×3840 (portrait 4K) + `--resolution 1080p` — the compile stage - // remaps `landscape` → `portrait` (1080×1920), and *then* the preset - // is smaller than the composition. The un-remapped preflight let this - // slip through as an aspect-mismatch downgrade; the remap-then-check - // catches the real failure — downsampling — early. + it("passes a portrait-4K comp + `1080p` once remapped to portrait (a smaller preset)", async () => { + // 2160×3840 + `--resolution 1080p` remaps `landscape` → `portrait` (1080×1920), rendered at 0.5× DPR. const result = await checkRenderResolutionPreflight(comp(2160, 3840), "landscape", agnostic); - expect(result?.kind).toBe("downsampling"); + expect(result).toBeUndefined(); }); it("blocks a portrait 720p comp + `1080p` non-integer upscale early (orientation-flip masks the fractional DPR)", async () => { diff --git a/packages/cli/src/commands/render.ts b/packages/cli/src/commands/render.ts index c3dfd7178e..913109d64f 100644 --- a/packages/cli/src/commands/render.ts +++ b/packages/cli/src/commands/render.ts @@ -118,6 +118,7 @@ import { import { chromeLaunchRemediation } from "../browser/linuxDeps.js"; import { macosOldChromeCrashRemediation } from "../browser/macosOldChromeCrash.js"; import { windowsChromeCrashRemediation } from "../browser/windowsCrash.js"; +import { sandboxDeniedRemediation } from "../browser/sandboxDenied.js"; import { killOrphanedProcessesForRender } from "../utils/orphanCleanup.js"; import { createRenderCancellationScope } from "../utils/renderCancellation.js"; import { @@ -1759,6 +1760,11 @@ function handleRenderError( // failure on Linux/WSL is an environment problem, not a composition bug. // Replace the generic "Try --docker" hint with the exact per-distro // remediation and a pointer at `doctor`. + const sandboxRemediation = sandboxDeniedRemediation(message); + if (sandboxRemediation) { + errorBox("Render failed — Chrome could not launch", message, sandboxRemediation); + failCommand(); + } const remediation = chromeLaunchRemediation(message); if (remediation) { errorBox("Render failed — Chrome could not launch", message, remediation); diff --git a/packages/cli/src/commands/skills.test.ts b/packages/cli/src/commands/skills.test.ts index 20591e09bd..979c18069f 100644 --- a/packages/cli/src/commands/skills.test.ts +++ b/packages/cli/src/commands/skills.test.ts @@ -640,6 +640,87 @@ describe("hyperframes skills", () => { expect(await commandExitCode()).toBe(1); }); + // GH #5695: the router runs `skills update ` before every workflow, so a + // team that pins its skills and sets HYPERFRAMES_SKIP_SKILLS=1 (like `init` + // honours) must not have that pin replaced by the latest upstream skills. + describe("with HYPERFRAMES_SKIP_SKILLS=1", () => { + beforeEach(() => { + vi.stubEnv("HYPERFRAMES_SKIP_SKILLS", "1"); + invalidateSkillsCache.mockClear(); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it("named `skills update` leaves a pinned install alone and exits 0", async () => { + setPlatform("linux"); + const logSpy = vi.spyOn(console, "log"); + const { checkSkills } = await import("../utils/skillsManifest.js"); + + await runSkillsUpdateWith(["product-launch-video"]); + + expect(state.spawnCalls).toHaveLength(0); + expect(vi.mocked(checkSkills)).not.toHaveBeenCalled(); + expect(invalidateSkillsCache).not.toHaveBeenCalled(); + expect(await commandExitCode()).toBe(0); + expect(String(logSpy.mock.calls.at(-1)?.[0] ?? "")).toMatch(/managed externally/); + }); + + it("bare `skills update` neither installs nor prunes", async () => { + setPlatform("linux"); + const { checkSkills } = await import("../utils/skillsManifest.js"); + vi.mocked(checkSkills).mockImplementation( + async () => + ({ + ...DEFAULT_CHECK, + skills: [...DEFAULT_CHECK.skills, { name: "graphic-overlays", status: "removed" }], + }) as never, + ); + + await runSkillsUpdate(); + + expect(state.spawnCalls).toHaveLength(0); + expect(vi.mocked(checkSkills)).not.toHaveBeenCalled(); + expect(await commandExitCode()).toBe(0); + }); + + it("bare `skills` does not install the full set", async () => { + setPlatform("linux"); + + const { default: skillsCmd } = await import("./skills.js"); + await skillsCmd.run?.({ args: {}, rawArgs: [], cmd: skillsCmd } as never); + + expect(state.spawnCalls).toHaveLength(0); + expect(invalidateSkillsCache).not.toHaveBeenCalled(); + expect(await commandExitCode()).toBe(0); + }); + + it("--json reports the skip as parseable JSON", async () => { + setPlatform("linux"); + const logSpy = vi.spyOn(console, "log"); + + await runSkillsUpdateWith(["pr-to-video"], { json: true }); + + expect(await commandExitCode()).toBe(0); + const parsed = JSON.parse(String(logSpy.mock.calls.at(-1)?.[0] ?? "")) as { + skipped?: boolean; + requested?: string[]; + }; + expect(parsed.skipped).toBe(true); + expect(parsed.requested).toEqual(["pr-to-video"]); + }); + + it("still rejects flag-like skill names", async () => { + setPlatform("linux"); + + await runSkillsUpdateWith(["--all"]); + + expect(state.spawnCalls).toHaveLength(0); + expect(await commandExitCode()).toBe(1); + }); + }); + // The stale-24h-cache regression: the skills commands are excluded from the // background nudge pipeline (cli.ts), so unless they drop the cached verdict // themselves, a successful install keeps the pre-install "N out of date or diff --git a/packages/cli/src/commands/skills.ts b/packages/cli/src/commands/skills.ts index 5920bc27c4..38d4d60a95 100644 --- a/packages/cli/src/commands/skills.ts +++ b/packages/cli/src/commands/skills.ts @@ -615,6 +615,37 @@ const checkCommand = defineCommand({ }, }); +// ── externally managed installs ──────────────────────────────────────────────── + +/** + * `HYPERFRAMES_SKIP_SKILLS=1` means something other than this CLI owns the skills + * install: CI, tests, or a team that pins the skills to one commit. `init` and the + * background nudge already stand down for it; the install commands must too, or + * the router's trigger-time `skills update ` replaces a pinned install + * with the latest upstream skills (GH #5695). + */ +function skillsManagedExternally(): boolean { + return process.env["HYPERFRAMES_SKIP_SKILLS"] === "1"; +} + +const SKILLS_MANAGED_EXTERNALLY_NOTICE = + "HYPERFRAMES_SKIP_SKILLS=1: skills are managed externally, so the installed skills were left unchanged."; + +/** The skip line for an externally managed install: JSON for agents, one dim line for humans. */ +function reportSkillsManagedExternally(requested: readonly string[], json: boolean): void { + if (json) { + console.log( + JSON.stringify( + withMeta({ skipped: true, reason: SKILLS_MANAGED_EXTERNALLY_NOTICE, requested }), + null, + 2, + ), + ); + return; + } + console.log(c.dim(SKILLS_MANAGED_EXTERNALLY_NOTICE)); +} + // ── update ─────────────────────────────────────────────────────────────────── /** @@ -713,6 +744,13 @@ const updateCommand = defineCommand({ return; } + // Exit 0 without installing, pruning or touching the nudge cache: the pinned + // install is the one the caller wants, so the router's step keeps working. + if (skillsManagedExternally()) { + reportSkillsManagedExternally(requested, args.json === true); + return; + } + // Targeted, not full-set: refresh the core set (entry router + shared // domain skills) plus whatever is already installed, plus anything named // above. Without names a deliberate partial install stays partial @@ -813,6 +851,10 @@ export default defineCommand({ // the positional so bare `hyperframes skills` installs, while // `hyperframes skills check|update` does not also re-install. if (!args._?.[0]) { + if (skillsManagedExternally()) { + reportSkillsManagedExternally([], false); + return; + } await updateSkills({ all: true }); // Same as updateSkills: a full install supersedes the background // nudge's cached pre-install verdict. diff --git a/packages/cli/src/renderSetupWorker.priority.test.ts b/packages/cli/src/renderSetupWorker.priority.test.ts index 65fae559c7..784a978f72 100644 --- a/packages/cli/src/renderSetupWorker.priority.test.ts +++ b/packages/cli/src/renderSetupWorker.priority.test.ts @@ -1,5 +1,5 @@ import { constants } from "node:os"; -import { afterEach, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; const os = vi.hoisted(() => ({ setPriority: vi.fn() })); vi.mock("node:os", async (importOriginal) => ({ @@ -8,11 +8,15 @@ vi.mock("node:os", async (importOriginal) => ({ })); vi.mock("./utils/lintProject.js", () => ({ lintProject: vi.fn(async () => ({ ok: true })) })); +beforeEach(() => { + vi.resetModules(); + os.setPriority.mockReset(); + process.argv[2] = "lint"; + process.env.HYPERFRAMES_RENDER_SETUP_INPUT = JSON.stringify({ projectDir: "/project" }); +}); afterEach(() => vi.restoreAllMocks()); it("lints at the lowest CPU priority so it never competes with a Studio boot", async () => { - process.argv[2] = "lint"; - process.env.HYPERFRAMES_RENDER_SETUP_INPUT = JSON.stringify({ projectDir: "/project" }); const write = vi.spyOn(process.stdout, "write").mockImplementation(() => true); await import("./renderSetupWorker.js"); @@ -20,3 +24,17 @@ it("lints at the lowest CPU priority so it never competes with a Studio boot", a expect(os.setPriority).toHaveBeenCalledWith(constants.priority.PRIORITY_LOW); expect(write).toHaveBeenCalledWith(expect.stringContaining('{"ok":true}')); }); + +it("still lints when a sandbox forbids lowering the priority", async () => { + os.setPriority.mockImplementation(() => { + throw new Error("uv_os_setpriority returned EPERM (operation not permitted)"); + }); + const write = vi.spyOn(process.stdout, "write").mockImplementation(() => true); + const warn = vi.spyOn(process.stderr, "write").mockImplementation(() => true); + + await import("./renderSetupWorker.js"); + + expect(write).toHaveBeenCalledWith(expect.stringContaining('{"ok":true}')); + expect(warn).toHaveBeenCalledTimes(1); + expect(warn).toHaveBeenCalledWith(expect.stringContaining("EPERM")); +}); diff --git a/packages/cli/src/renderSetupWorker.ts b/packages/cli/src/renderSetupWorker.ts index 5a12ab0405..38a23f60b8 100644 --- a/packages/cli/src/renderSetupWorker.ts +++ b/packages/cli/src/renderSetupWorker.ts @@ -18,11 +18,19 @@ const disposeSignalHandlers = installRenderSetupSignalHandlers( process.env.HYPERFRAMES_RENDER_DETACHED !== "1", ); +function lowerPriority(): void { + try { + setPriority(constants.priority.PRIORITY_LOW); + } catch (error) { + process.stderr.write(`Lint runs at normal priority: ${(error as Error).message}\n`); + } +} + async function runMode(): Promise { if (mode === "browser") return ensureBrowser(input); if (mode === "lint") { // Nobody waits on a background lint the way they wait on a Studio boot, so it takes idle CPU only. - setPriority(constants.priority.PRIORITY_LOW); + lowerPriority(); return lintProject( input.projectDir, input.entryFile, diff --git a/packages/cli/src/timeline/a2Shared.ts b/packages/cli/src/timeline/a2Shared.ts index 44ddd5e6d2..44bab9d666 100644 --- a/packages/cli/src/timeline/a2Shared.ts +++ b/packages/cli/src/timeline/a2Shared.ts @@ -137,6 +137,19 @@ export function diff(before: string, after: string): string { return output.length <= 8_000 ? output : `${output.slice(0, 7_997)}...`; } +function isAncestorOf(ancestor: TimelineRow, row: TimelineRow, timeline: ProjectTimeline): boolean { + for (let pointer = row.parentRow; pointer; ) { + const parent = rowAt(timeline, pointer); + if (parent === ancestor) return true; + pointer = parent.parentRow; + } + return false; +} + +function sameLineage(a: TimelineRow, b: TimelineRow, timeline: ProjectTimeline): boolean { + return isAncestorOf(a, b, timeline) || isAncestorOf(b, a, timeline); +} + function overlap( row: TimelineRow, timeline: ProjectTimeline, @@ -146,6 +159,7 @@ function overlap( return allRows(timeline).find( (candidate) => candidate !== row && + !sameLineage(candidate, row, timeline) && candidate.file === row.file && candidate.trackIndex === row.trackIndex && spansShareTime(start, end, candidate.start, candidate.end), @@ -429,6 +443,7 @@ export function mutationConflict( if (verb === "duplicate") { const conflict = allRows(timeline).find( (candidate) => + !sameLineage(candidate, row, timeline) && candidate.file === row.file && candidate.trackIndex === row.trackIndex && isInsideSpan(nextStart, candidate.start, candidate.end), diff --git a/packages/cli/src/timeline/describeProject.inPoint.test.ts b/packages/cli/src/timeline/describeProject.inPoint.test.ts index 1caf194d04..79b95c3cd1 100644 --- a/packages/cli/src/timeline/describeProject.inPoint.test.ts +++ b/packages/cli/src/timeline/describeProject.inPoint.test.ts @@ -18,12 +18,12 @@ const SCENE = `