diff --git a/.agents/skills/README.md b/.agents/skills/README.md index 2effc3c4de..dbf7a8459a 100644 --- a/.agents/skills/README.md +++ b/.agents/skills/README.md @@ -49,7 +49,9 @@ Claude Code users get the same auto-discover behaviour — keep the two in sync when editing. A `scripts/check-skill-mirror.mjs` check enforces this at CI time. -Each repo-native skill declares `metadata.internal: true`, so `npx skills add` -skips it during normal installs (including `--all`). This does not change local -agent discovery. To explicitly install these skills elsewhere, set -`INSTALL_INTERNAL_SKILLS=1` when running the installer. +Each repo-native skill declares `metadata.internal: true`. That excludes it from +normal `npx skills add` discovery and from `npx skills add ... --all`. A named +`npx skills add ... --skill ` still installs a matching skill regardless of +`metadata.internal`; no environment variable is needed. `INSTALL_INTERNAL_SKILLS=1` +opts internal skills into normal discovery and bulk installation. This does not +change local agent discovery. diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 7c4f45aae1..f051d60f12 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.111", + "version": "0.8.114", "author": { "name": "HeyGen", "email": "hyperframes@heygen.com", diff --git a/.claude/skills/README.md b/.claude/skills/README.md index 435cec5bb6..08e55f384b 100644 --- a/.claude/skills/README.md +++ b/.claude/skills/README.md @@ -11,6 +11,8 @@ manifested by `.claude-plugin/`). Two separate namespaces, on purpose: - `skills/` — **marketplace-distributable**, installed into other projects via `npx hyperframes skills` or `npx skills add heygen-com/hyperframes`. +> **Warning:** Never run `npx skills add ... --all` from inside a HyperFrames checkout: it selects the OpenClaw target, whose `skills/` directory is the repo's own `skills/`, and removes each existing `skills/` destination before linking. A fresh clone restores tracked source, but uncommitted work under `skills/` does not recover. Run it from an empty directory or from your own project root. This happens regardless of `metadata.internal`. + ## Weekly changelog video The `changelog-video` skill turns a weekly changelog markdown into a @@ -47,7 +49,9 @@ CLI users get the same auto-discover behaviour — keep the two in sync when editing. A `scripts/check-skill-mirror.mjs` check enforces this at CI time. -Each repo-native skill declares `metadata.internal: true`, so `npx skills add` -skips it during normal installs (including `--all`). This does not change local -agent discovery. To explicitly install these skills elsewhere, set -`INSTALL_INTERNAL_SKILLS=1` when running the installer. +Each repo-native skill declares `metadata.internal: true`. That excludes it from +normal `npx skills add` discovery and from `npx skills add ... --all`. A named +`npx skills add ... --skill ` still installs a matching skill regardless of +`metadata.internal`; no environment variable is needed. `INSTALL_INTERNAL_SKILLS=1` +opts internal skills into normal discovery and bulk installation. This does not +change local agent discovery. diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 275fe2f048..f8a1bb3282 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.111", + "version": "0.8.114", "author": { "name": "HeyGen", "email": "hyperframes@heygen.com", diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json index 5375af9b50..242d0a504d 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.111", + "version": "0.8.114", "author": { "name": "HeyGen", "email": "hyperframes@heygen.com" diff --git a/.fallowrc.jsonc b/.fallowrc.jsonc index cee55ad865..c94e4cb47b 100644 --- a/.fallowrc.jsonc +++ b/.fallowrc.jsonc @@ -39,6 +39,7 @@ "packages/cli/src/commands/layout-audit.browser.js", "packages/cli/src/commands/contrast-audit.browser.js", "packages/cli/src/commands/motion-sample.browser.js", + "packages/cli/src/commands/motion-signature.browser.js", // Worker entry points loaded dynamically by their *Pool.ts companions. "packages/producer/src/services/pngDecodeBlitWorker.ts", "packages/producer/src/services/shaderTransitionWorker.ts", diff --git a/.github/renovate.json b/.github/renovate.json index 56277761f0..820d0e57fc 100644 --- a/.github/renovate.json +++ b/.github/renovate.json @@ -15,6 +15,10 @@ "labels": ["security"] }, "packageRules": [ + { + "matchDepTypes": ["engines", "peerDependencies"], + "rangeStrategy": "widen" + }, { "matchUpdateTypes": ["minor", "patch"], "matchDepTypes": ["devDependencies"], diff --git a/.github/workflows/canary-sunset.yml b/.github/workflows/canary-sunset.yml index 5883f997be..9fbca63566 100644 --- a/.github/workflows/canary-sunset.yml +++ b/.github/workflows/canary-sunset.yml @@ -23,7 +23,7 @@ jobs: sunset: runs-on: ubuntu-latest steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: latest diff --git a/.github/workflows/catalog-previews.yml b/.github/workflows/catalog-previews.yml index 1c0feff3e4..5eec507648 100644 --- a/.github/workflows/catalog-previews.yml +++ b/.github/workflows/catalog-previews.yml @@ -32,7 +32,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 5 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - uses: ./.github/actions/preflight render-previews: @@ -41,7 +41,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 30 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: fetch-depth: 0 diff --git a/.github/workflows/catalog-publish.yml b/.github/workflows/catalog-publish.yml index bbe9b33acc..25730ac324 100644 --- a/.github/workflows/catalog-publish.yml +++ b/.github/workflows/catalog-publish.yml @@ -22,7 +22,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 30 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: ref: main fetch-depth: 0 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 072552fc92..4a979d6b22 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -41,7 +41,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 2 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: fetch-depth: 0 - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 @@ -79,13 +79,13 @@ jobs: # Force git-based change detection instead of the pull_request REST API. # The API path can fail the whole workflow on transient listFiles # timeouts before any real CI work starts. - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: fetch-depth: 0 - name: Reject accidental file deletions if: github.event_name == 'pull_request' run: node scripts/check-no-main-deletions.mjs --base origin/main - - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4 + - uses: dorny/paths-filter@ceb8a2b8f2d89434be7ff52d3de7ec3738c5cc9d # v4 id: filter with: token: "" @@ -206,15 +206,15 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 15 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: lfs: true - - uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3 + - uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3 - name: Build BeginFrame contract image # A hung bun install (Dockerfile.test, run 35468046055) would # otherwise eat the whole job timeout instead of failing at this step. timeout-minutes: 10 - uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6 + uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6 with: context: . file: packages/gcp-cloud-run/Dockerfile @@ -236,7 +236,7 @@ jobs: run: | echo "::error::Change detection did not succeed, so this required check cannot pass." exit 1 - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: lfs: true - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 @@ -265,7 +265,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 5 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: lfs: true fetch-depth: 0 @@ -288,7 +288,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 15 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: fetch-depth: 0 - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 @@ -341,7 +341,7 @@ jobs: contents: read pull-requests: write steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: # Full history so `--base origin/main` can diff against the merge # base on stacked PRs, not just the shallow tip. @@ -399,7 +399,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 5 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: lfs: true - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 @@ -423,7 +423,7 @@ jobs: run: | echo "::error::Change detection did not succeed, so this required check cannot pass." exit 1 - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: lfs: true - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 @@ -443,7 +443,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 10 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: lfs: true fetch-depth: 0 @@ -467,7 +467,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 10 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: lfs: true - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 @@ -489,7 +489,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 10 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: lfs: true fetch-depth: 0 @@ -557,7 +557,7 @@ jobs: matrix: lane: [unit, integration] steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: lfs: true - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 @@ -589,7 +589,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 5 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version: 22 @@ -622,7 +622,7 @@ jobs: runs-on: windows-latest timeout-minutes: 5 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version: 24 @@ -645,7 +645,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 3 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 with: @@ -661,7 +661,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 3 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 - name: Verify skills-manifest.json matches skills/ run: bun packages/cli/scripts/gen-skills-manifest.ts --check @@ -678,7 +678,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 3 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 - name: Lint SKILL.md files across skills/, .claude/skills/, .agents/skills/ run: bun scripts/lint-skills.ts @@ -692,7 +692,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 3 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version: 22 @@ -716,7 +716,7 @@ jobs: matrix: os: [ubuntu-latest, macos-latest, windows-latest] steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: @@ -736,7 +736,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 5 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 - run: bash scripts/ci/install-workspace-dependencies.sh # Build workspace deps so the sdk's @hyperframes/parsers + core subpath @@ -758,7 +758,7 @@ jobs: run: | echo "::error::Change detection did not succeed, so this required check cannot pass." exit 1 - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: lfs: true - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 @@ -779,7 +779,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 5 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: lfs: true - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 @@ -825,7 +825,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 18 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: @@ -960,7 +960,7 @@ jobs: node packages/studio/tests/e2e/perf-ratchet.mjs check \ packages/studio/tests/e2e/perf-ceilings.json studio-open /tmp/studio-open-counts.json \ /tmp/base-perf-ceilings.json - - name: Measure the fade handle tabs and click every Renders select + - name: Check fade handles, render selects and thumbnail connection release if: success() || failure() run: | set -euo pipefail @@ -975,12 +975,14 @@ jobs: echo "FAIL: studio dev server did not start on port 5316" exit 1 fi - # Both checks run even when the first fails. + # All checks run even when an earlier one fails. rc=0 STUDIO_URL="http://localhost:5316/#project/fade-handles" \ node packages/studio/tests/e2e/fade-handles.mjs || rc=1 STUDIO_URL="http://localhost:5316/#project/fade-handles?tab=renders" \ node packages/studio/tests/e2e/render-selects.mjs || rc=1 + STUDIO_URL="http://localhost:5316/" \ + node packages/studio/tests/e2e/thumbnail-save.mjs || rc=1 exit "$rc" - name: Measure the caret of a text edited in place if: success() || failure() @@ -1048,7 +1050,7 @@ jobs: matrix: shard: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: @@ -1096,7 +1098,7 @@ jobs: contents: read pull-requests: write steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version: 22 @@ -1144,7 +1146,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 10 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: lfs: true - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 @@ -1216,7 +1218,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 25 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: lfs: true - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 @@ -1341,7 +1343,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 1 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: fetch-depth: 0 - name: Check file sizes (max 600 lines) @@ -1403,7 +1405,7 @@ jobs: with: types: ${{ env.PR_TITLE_TYPES }} - if: github.event_name == 'workflow_dispatch' - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: persist-credentials: false - if: github.event_name == 'workflow_dispatch' @@ -1412,7 +1414,7 @@ jobs: env: GH_TOKEN: ${{ github.token }} - if: github.event_name == 'workflow_dispatch' - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: repository: amannn/action-semantic-pull-request ref: e32d7e603df1aa1ba07e981f2a23455dee596825 # v5 diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 159b501b68..94a0529ebe 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -43,16 +43,16 @@ jobs: build-mode: none steps: - name: Checkout - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - name: Initialize CodeQL - uses: github/codeql-action/init@7211b7c8077ea37d8641b6271f6a365a22a5fbfa # v4 + uses: github/codeql-action/init@2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2 # v4 with: languages: ${{ matrix.language }} build-mode: ${{ matrix.build-mode }} config-file: ./.github/codeql/codeql-config.yml - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@7211b7c8077ea37d8641b6271f6a365a22a5fbfa # v4 + uses: github/codeql-action/analyze@2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2 # v4 with: category: "/language:${{ matrix.language }}" diff --git a/.github/workflows/comments.yml b/.github/workflows/comments.yml index 5c0a048b90..188a62501b 100644 --- a/.github/workflows/comments.yml +++ b/.github/workflows/comments.yml @@ -25,7 +25,7 @@ jobs: scripts/check-comment-citations.mjs scripts/check-comment-citations.test.mjs scripts/comment-ratchet.mjs scripts/comment-ratchet.test.mjs steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: # The PR's own head, graded against its merge-base: not the merge preview, which would # charge the branch for every comment main changed since it forked. @@ -40,7 +40,7 @@ jobs: for script in $COMMENT_SCRIPTS; do [ -f "pr/$script" ] || dir=base; done echo "CHECKS_DIR=$dir" >> "$GITHUB_ENV" - if: env.CHECKS_DIR == 'base' - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: ref: ${{ github.event.pull_request.base.sha }} path: base diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 3ca7a00ea7..9417b77a0f 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -34,7 +34,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 5 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: diff --git a/.github/workflows/fast-video-validation.yml b/.github/workflows/fast-video-validation.yml index c73e3ced4e..09ca7c46d5 100644 --- a/.github/workflows/fast-video-validation.yml +++ b/.github/workflows/fast-video-validation.yml @@ -28,7 +28,7 @@ jobs: validate: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - name: Set up Docker Buildx uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3 diff --git a/.github/workflows/player-perf.yml b/.github/workflows/player-perf.yml index 7bcfd1aa71..f8310a70f1 100644 --- a/.github/workflows/player-perf.yml +++ b/.github/workflows/player-perf.yml @@ -27,10 +27,10 @@ jobs: steps: # Force git-based change detection instead of the pull_request REST API. # The API path can fail the perf workflow on transient listFiles timeouts. - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: fetch-depth: 0 - - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4 + - uses: dorny/paths-filter@ceb8a2b8f2d89434be7ff52d3de7ec3738c5cc9d # v4 id: filter with: token: "" @@ -49,7 +49,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 5 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - uses: ./.github/actions/preflight perf-shards: @@ -78,7 +78,7 @@ jobs: scenarios: parity runs: "3" steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 diff --git a/.github/workflows/pr-captures.yml b/.github/workflows/pr-captures.yml index 2d81404a67..67e7896900 100644 --- a/.github/workflows/pr-captures.yml +++ b/.github/workflows/pr-captures.yml @@ -25,7 +25,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 10 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: fetch-depth: 0 - id: pr diff --git a/.github/workflows/preview-regression.yml b/.github/workflows/preview-regression.yml index 8ab6b25085..f7666d8361 100644 --- a/.github/workflows/preview-regression.yml +++ b/.github/workflows/preview-regression.yml @@ -26,10 +26,10 @@ jobs: outputs: preview: ${{ steps.filter.outputs.preview }} steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: fetch-depth: 0 - - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4 + - uses: dorny/paths-filter@ceb8a2b8f2d89434be7ff52d3de7ec3738c5cc9d # v4 id: filter with: token: "" @@ -56,7 +56,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 5 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - uses: ./.github/actions/preflight preview-parity: @@ -66,7 +66,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 20 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index de0544ae4e..6ce255bb8e 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -33,7 +33,7 @@ jobs: (github.event.pull_request.merged == true && startsWith(github.event.pull_request.head.ref, 'release/v')) steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: fetch-depth: 0 # Pin every release to an immutable ref. In particular, a merged diff --git a/.github/workflows/regression.yml b/.github/workflows/regression.yml index 0c486b046f..5b42d5515e 100644 --- a/.github/workflows/regression.yml +++ b/.github/workflows/regression.yml @@ -47,10 +47,10 @@ jobs: # Force git-based change detection instead of the pull_request REST API. # The API path can fail the whole workflow on transient listFiles # timeouts before any regression shard even starts. - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: fetch-depth: 0 - - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4 + - uses: dorny/paths-filter@ceb8a2b8f2d89434be7ff52d3de7ec3738c5cc9d # v4 id: filter if: github.event_name != 'schedule' with: @@ -79,7 +79,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 5 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - uses: ./.github/actions/preflight regression-shards: @@ -95,7 +95,7 @@ jobs: matrix: ${{ fromJSON(needs.changes.outputs.matrix) }} steps: - name: Checkout (with LFS) - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: lfs: true diff --git a/.github/workflows/studio-drag-frames.yml b/.github/workflows/studio-drag-frames.yml index 9c95f2cd75..54553941f2 100644 --- a/.github/workflows/studio-drag-frames.yml +++ b/.github/workflows/studio-drag-frames.yml @@ -14,19 +14,31 @@ on: ref: description: Commit, branch or tag to measure default: main + filter: + description: Case ids to run (a regular expression) + default: "^(move|resize|rotate|crop)-(none|tween)-px-r0-root-z100$" + grid: + description: The grid the ids come from (pr or full) + default: pr pull_request: paths: - ".github/workflows/studio-drag-frames.yml" jobs: drag-frames: - name: "Studio: drag frames" + name: "Studio: drag frames (run ${{ matrix.run }})" runs-on: ubuntu-latest timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + run: [1, 2, 3, 4, 5] env: BENCH_REF: ${{ inputs.ref || 'main' }} + BENCH_FILTER: ${{ inputs.filter || '^(move|resize|rotate|crop)-(none|tween)-px-r0-root-z100$' }} + BENCH_GRID: ${{ inputs.grid || 'pr' }} steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: ref: ${{ env.BENCH_REF }} lfs: true @@ -40,17 +52,14 @@ jobs: - run: bash scripts/ci/install-workspace-dependencies.sh - run: bun run build - run: node packages/cli/dist/cli.js browser ensure - - name: Run the drag cases five times + - name: Run the drag cases working-directory: packages/studio run: | set -euo pipefail echo "Measuring $(git rev-parse HEAD)" - for n in 1 2 3 4 5; do - bun tests/e2e/edit-accuracy/run.mjs --grid pr \ - --filter '^(move|resize|rotate|crop)-(none|tween)-px-r0-root-z100$' \ - --jobs 1 --port 5961 --cli "$GITHUB_WORKSPACE/packages/cli/dist/cli.js" \ - --out "$RUNNER_TEMP/drag-frames/run-$n" - done + bun tests/e2e/edit-accuracy/run.mjs --grid "$BENCH_GRID" --filter "$BENCH_FILTER" \ + --jobs 1 --port 5961 --cli "$GITHUB_WORKSPACE/packages/cli/dist/cli.js" \ + --out "$RUNNER_TEMP/drag-frames/run-${{ matrix.run }}" - name: Require a quiet box (the blank page dropped no frame) run: | # shellcheck disable=SC2016 # the backticks are JavaScript template strings @@ -70,7 +79,7 @@ jobs: - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 if: always() with: - name: studio-drag-frames + name: studio-drag-frames-${{ matrix.run }} path: ${{ runner.temp }}/drag-frames if-no-files-found: error retention-days: 30 diff --git a/.github/workflows/sync-skills-to-clawhub.yml b/.github/workflows/sync-skills-to-clawhub.yml index 33bb87cae3..ec6eb1be3f 100644 --- a/.github/workflows/sync-skills-to-clawhub.yml +++ b/.github/workflows/sync-skills-to-clawhub.yml @@ -33,7 +33,7 @@ jobs: env: CLAWHUB_DISABLE_TELEMETRY: "1" steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: diff --git a/.github/workflows/windows-render.yml b/.github/workflows/windows-render.yml index 28ee42a7c7..6b79739d68 100644 --- a/.github/workflows/windows-render.yml +++ b/.github/workflows/windows-render.yml @@ -50,10 +50,10 @@ jobs: # Force git-based change detection instead of the pull_request REST API. # The API path can fail the workflow on transient listFiles timeouts # before the Windows render jobs even start. - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: fetch-depth: 0 - - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4 + - uses: dorny/paths-filter@ceb8a2b8f2d89434be7ff52d3de7ec3738c5cc9d # v4 id: filter with: token: "" @@ -74,7 +74,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 5 steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: ref: ${{ inputs.ref || github.sha }} - uses: ./.github/actions/preflight @@ -101,7 +101,7 @@ jobs: run: Set-MpPreference -DisableRealtimeMonitoring $true - name: Checkout - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: ref: ${{ inputs.ref || github.sha }} lfs: true @@ -426,7 +426,7 @@ jobs: run: Set-MpPreference -DisableRealtimeMonitoring $true - name: Checkout - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: ref: ${{ inputs.ref || github.sha }} # Only the engine-cli lane reads an LFS file (engine's ffprobe test parses a producer HDR PNG). diff --git a/CLAUDE.md b/CLAUDE.md index 64c77db284..a7c5ef381a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -9,10 +9,13 @@ This repo ships 21 AI agent skills via [vercel-labs/skills](https://github.com/v ```bash npx hyperframes skills update # default: installs/refreshes the core set — workflows install on demand npx hyperframes skills # all 21 published skills at once — only on explicit request -npx skills add heygen-com/hyperframes # interactive picker (terminal only; --all also pulls the 6 repo-internal skills under .claude/skills) -npx skills add heygen-com/hyperframes --skill # just one (bare name, no leading slash) +npx skills add heygen-com/hyperframes # interactive picker; internal skills require INSTALL_INTERNAL_SKILLS=1 for discovery +npx skills add heygen-com/hyperframes --all # excludes internal skills unless INSTALL_INTERNAL_SKILLS=1 +npx skills add heygen-com/hyperframes --skill # a named match installs regardless of metadata.internal (bare name, no leading slash) ``` +> **Warning:** Never run `npx skills add ... --all` from inside a HyperFrames checkout: it selects the OpenClaw target, whose `skills/` directory is the repo's own `skills/`, and removes each existing `skills/` destination before linking. A fresh clone restores tracked source, but uncommitted work under `skills/` does not recover. Run it from an empty directory or from your own project root. This happens regardless of `metadata.internal`. + `skills add` resolves the skills.sh registry blob, which can lag `main` by hours, so a freshly added skill may be a little behind. `npx hyperframes skills update` installs from the current `main`; prefer it when freshness matters. **`/hyperframes` is the entry skill — read it first.** It's the capability map for the domain skills below, the intent layer that confirms every creation brief up front, AND the intent router for the creation workflows. The full README skills section mirrors this list; keep them in sync (see "Skill catalog maintenance" below). diff --git a/Dockerfile.test b/Dockerfile.test index 47f9061f64..e85da3f21e 100644 --- a/Dockerfile.test +++ b/Dockerfile.test @@ -10,7 +10,7 @@ # docker run --rm -v ./packages/producer/tests:/app/packages/producer/tests hyperframes-producer:test # docker run --rm -v ./packages/producer/tests:/app/packages/producer/tests hyperframes-producer:test --update -FROM node:22-bookworm-slim +FROM node:22.23.3-bookworm-slim # ── System dependencies (identical to production) ──────────────────────────── RUN apt-get update && apt-get install -y --no-install-recommends \ diff --git a/bun.lock b/bun.lock index ca3e7512e1..11a5bc144b 100644 --- a/bun.lock +++ b/bun.lock @@ -24,7 +24,7 @@ }, "packages/aws-lambda": { "name": "@hyperframes/aws-lambda", - "version": "0.8.62", + "version": "0.8.111", "dependencies": { "@aws-sdk/client-s3": "^3.700.0", "@aws-sdk/client-sfn": "^3.700.0", @@ -57,7 +57,7 @@ }, "packages/cli": { "name": "@hyperframes/cli", - "version": "0.8.62", + "version": "0.8.111", "bin": { "hyperframes": "./bin/hyperframes.mjs", "hyperframes-localize-fonts": "./bin/hyperframes-localize-fonts.mjs", @@ -109,7 +109,7 @@ }, "packages/core": { "name": "@hyperframes/core", - "version": "0.8.62", + "version": "0.8.111", "dependencies": { "@chenglou/pretext": "^0.0.5", "@hyperframes/lint": "workspace:*", @@ -135,7 +135,7 @@ }, "packages/engine": { "name": "@hyperframes/engine", - "version": "0.8.62", + "version": "0.8.111", "dependencies": { "@hono/node-server": "^2.0.5", "@hyperframes/core": "workspace:^", @@ -154,7 +154,7 @@ }, "packages/gcp-cloud-run": { "name": "@hyperframes/gcp-cloud-run", - "version": "0.8.62", + "version": "0.8.111", "dependencies": { "@google-cloud/storage": "^7.14.0", "@google-cloud/workflows": "^4.2.0", @@ -175,7 +175,7 @@ }, "packages/lint": { "name": "@hyperframes/lint", - "version": "0.8.62", + "version": "0.8.111", "dependencies": { "@hyperframes/parsers": "workspace:*", "acorn": "^8.17.0", @@ -195,7 +195,7 @@ }, "packages/parsers": { "name": "@hyperframes/parsers", - "version": "0.8.62", + "version": "0.8.111", "dependencies": { "@babel/parser": "^7.27.0", "acorn": "^8.17.0", @@ -215,7 +215,7 @@ }, "packages/player": { "name": "@hyperframes/player", - "version": "0.8.62", + "version": "0.8.111", "dependencies": { "@hyperframes/core": "workspace:*", }, @@ -230,7 +230,7 @@ }, "packages/producer": { "name": "@hyperframes/producer", - "version": "0.8.62", + "version": "0.8.111", "dependencies": { "@fontsource/archivo-black": "^5.2.8", "@fontsource/eb-garamond": "^5.2.7", @@ -275,7 +275,7 @@ }, "packages/sdk": { "name": "@hyperframes/sdk", - "version": "0.8.62", + "version": "0.8.111", "dependencies": { "@hyperframes/core": "workspace:*", "@hyperframes/parsers": "workspace:*", @@ -305,7 +305,7 @@ }, "packages/shader-transitions": { "name": "@hyperframes/shader-transitions", - "version": "0.8.62", + "version": "0.8.111", "dependencies": { "html2canvas": "^1.4.1", }, @@ -317,7 +317,7 @@ }, "packages/studio": { "name": "@hyperframes/studio", - "version": "0.8.62", + "version": "0.8.111", "dependencies": { "@base-ui/react": "1.7.0", "@codemirror/autocomplete": "^6.20.1", @@ -370,7 +370,7 @@ }, "packages/studio-server": { "name": "@hyperframes/studio-server", - "version": "0.8.62", + "version": "0.8.111", "dependencies": { "@hyperframes/core": "workspace:*", "@hyperframes/parsers": "workspace:*", diff --git a/docs/changelog.mdx b/docs/changelog.mdx index 17efd3f0bb..50e2d26612 100644 --- a/docs/changelog.mdx +++ b/docs/changelog.mdx @@ -8,6 +8,118 @@ Recent HyperFrames releases, including user-facing features, fixes, and migratio {/* New release entries are prepended by `bun run changelog:draft --write`. */} + +Renaming a file in Studio now rewrites only the references that point at it, and keyframe edits no longer copy other animations' values. Manual edits also stay under 8 ms per frame, and Studio reads modern CSS colors. + +## Fixes + +- **Studio Server:** A rename rewrites only references that name the renamed path ([1168bb740d33](https://github.com/heygen-com/hyperframes/commit/1168bb740d336f366849c91308a3c2bbb850c570), [#4915](https://github.com/heygen-com/hyperframes/pull/4915)). +- **Studio:** Parse modern CSS colors without a new dependency ([5c52f72399e2](https://github.com/heygen-com/hyperframes/commit/5c52f72399e21f8dcf3ede2bf2d24978c6522a94), [#3931](https://github.com/heygen-com/hyperframes/pull/3931)). +- **Studio:** Keep a keyframe edit from copying other tweens' channels ([dc9c38efd8f6](https://github.com/heygen-com/hyperframes/commit/dc9c38efd8f6eadefb654d73f55e6e8671a1c8f4), [#4918](https://github.com/heygen-com/hyperframes/pull/4918)). +- **CLI:** Select containing source frames in snapshots ([0d3d42320015](https://github.com/heygen-com/hyperframes/commit/0d3d423200153fa96d82ca5bc5b91565b87e5f29), [#4809](https://github.com/heygen-com/hyperframes/pull/4809)). +- **Studio:** One GSAP-writes check that sees every keyframe form ([00b61b8b7611](https://github.com/heygen-com/hyperframes/commit/00b61b8b7611f68e3c52f29314015b00cd241bf6), [#4781](https://github.com/heygen-com/hyperframes/pull/4781)). +- **CLI:** A background preview launch keeps only the server its own child started ([fd2f90c7d81d](https://github.com/heygen-com/hyperframes/commit/fd2f90c7d81d4c2a57848bb21e225cbccc66ec4f), [#4914](https://github.com/heygen-com/hyperframes/pull/4914)). + +## Performance + +- **Studio:** Manual edits stay under 8 ms per frame ([438ea9d59fd5](https://github.com/heygen-com/hyperframes/commit/438ea9d59fd5c1e720cc55311150dd3b25fab3db), [#4898](https://github.com/heygen-com/hyperframes/pull/4898)). + +## Internal + +- **Studio:** Give the real-Chrome undo test a time budget Windows can meet ([d5b56426c2a6](https://github.com/heygen-com/hyperframes/commit/d5b56426c2a65eddce404e74b04992fff2c2b87d), [#4912](https://github.com/heygen-com/hyperframes/pull/4912)). + +[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.8.113...v0.8.114). + + + +Exported videos no longer blink layers on animation steps, and an intro set at frame 0 still shows. CLI commands now reject stray extra words, and background previews keep the port you ask for. + +## Fixes + +- **Core:** Render GSAP set steps on the frame they land on ([02775c716](https://github.com/heygen-com/hyperframes/commit/02775c716fe7de72a7e384823373f9e7a8040c16), [#4911](https://github.com/heygen-com/hyperframes/pull/4911)). +- **CLI:** Reject extra positional arguments on every command ([4178a8f95](https://github.com/heygen-com/hyperframes/commit/4178a8f95d3d3439ddde6b5d20a317ef01c97d61), [#4905](https://github.com/heygen-com/hyperframes/pull/4905)). +- **CLI:** Honor an explicit --port for background preview reuse and launch ([fcc637068](https://github.com/heygen-com/hyperframes/commit/fcc637068c1e22b48efcead0c1b41362fc2dc1af), [#3915](https://github.com/heygen-com/hyperframes/pull/3915)). +- **Lint:** Flag digit-leading ids used by toArray and ScrollTrigger selectors ([fc5390874](https://github.com/heygen-com/hyperframes/commit/fc53908742066f8f1e3c4e37204181afd7117cd6), [#4908](https://github.com/heygen-com/hyperframes/pull/4908)). +- **CLI:** Hide console windows on Windows for background/detached spawns ([821e8c8ad](https://github.com/heygen-com/hyperframes/commit/821e8c8ad03aa070b65a195443e9cf1926864d5a), [#3996](https://github.com/heygen-com/hyperframes/pull/3996)). +- **CLI:** Stop browser --force from deleting chrome under running renders ([f16e50983](https://github.com/heygen-com/hyperframes/commit/f16e509832d4fa02bbc9a5f81b59ff78f9d466af), [#4901](https://github.com/heygen-com/hyperframes/pull/4901)). + +## Catalog + +- **Registry:** Add 4 community components ([04acbb4d9](https://github.com/heygen-com/hyperframes/commit/04acbb4d9eaac198421ba1ef007dc3ce6a72ef9c), [#4906](https://github.com/heygen-com/hyperframes/pull/4906)). + +[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.8.112...v0.8.113). + + + +Studio now shows where a dragged clip will land as a new track, and saves no longer wait on thumbnails. Nearly thirty CLI, lint and render fixes make checks quieter and more exact. + +## Features + +- **Studio:** Export timeline row order and fade handle boxes, readable fx badge ([05145bf73](https://github.com/heygen-com/hyperframes/commit/05145bf73c6a9f3f9e8cae9d970e43a0707df800), [#4904](https://github.com/heygen-com/hyperframes/pull/4904)). +- **Studio:** Preview timeline track insertion ([67dbcf7bd](https://github.com/heygen-com/hyperframes/commit/67dbcf7bdbe68eb4ad7a710676272552813955a8), [#4907](https://github.com/heygen-com/hyperframes/pull/4907)). +- **Skills:** Motion-blur-streak — per-frame-driven form for elements riding a baked track ([0a04f80bb](https://github.com/heygen-com/hyperframes/commit/0a04f80bbe4edb13332338f197f12f2728cf79c7), [#3781](https://github.com/heygen-com/hyperframes/pull/3781)). +- **Studio:** Give timeline clips a Filmstrip name band ([0b1f5979f](https://github.com/heygen-com/hyperframes/commit/0b1f5979fd1458686da51705cb9832c45c5f946e), [#4897](https://github.com/heygen-com/hyperframes/pull/4897)). + +## Fixes + +- **Lint:** Fail skill lint on unresolved doc cross-references ([e8ff5ca8c](https://github.com/heygen-com/hyperframes/commit/e8ff5ca8c23e67d6da188c66abdee50ce159d6d8), [#3922](https://github.com/heygen-com/hyperframes/pull/3922)). +- **Lint:** Flag static composition hosts without opt-out ([9a4b2a2d7](https://github.com/heygen-com/hyperframes/commit/9a4b2a2d74d3f6a3b8f7bdb43803201f91b73b9f), [#3763](https://github.com/heygen-com/hyperframes/pull/3763)). +- **Skills:** Stop mirroring skills into Codex and remove old mirror links ([d865b5a7c](https://github.com/heygen-com/hyperframes/commit/d865b5a7cb2e715d97d9dd3f225702a4cd755a55), [#4105](https://github.com/heygen-com/hyperframes/pull/4105)). +- **Lint:** Flag seek-unsafe CSS transitions ([f2eb6d9cc](https://github.com/heygen-com/hyperframes/commit/f2eb6d9cc14004fd02f9997a8916f0ceae4e6529), [#3797](https://github.com/heygen-com/hyperframes/pull/3797)). +- **CLI:** Distinguish a skipped browser check from a genuinely clean one ([b31fb02c7](https://github.com/heygen-com/hyperframes/commit/b31fb02c7e9a112d237b41d4a30782c107d2e282), [#3901](https://github.com/heygen-com/hyperframes/pull/3901)). +- **CLI:** Stop lambda deploy from pointing at a nonexistent --sam-template flag ([a7e95c0e3](https://github.com/heygen-com/hyperframes/commit/a7e95c0e37c05b198f07d9a46a51f7339f72917f), [#3879](https://github.com/heygen-com/hyperframes/pull/3879)). +- **Studio:** A saved clip volume reaches the timeline store ([30ed3cd12](https://github.com/heygen-com/hyperframes/commit/30ed3cd1242d0fd18c8d204bd8826671b1315884), [#4883](https://github.com/heygen-com/hyperframes/pull/4883)). +- **Ci:** Skill docs may name the project files a workflow writes ([84898fbe8](https://github.com/heygen-com/hyperframes/commit/84898fbe858ea66094350a56c6f00c575690abfd), [#4902](https://github.com/heygen-com/hyperframes/pull/4902)). +- **CLI:** Recapture snapshot composites after video injection ([bad0bc7ce](https://github.com/heygen-com/hyperframes/commit/bad0bc7ce27429659470ae9e04b64c13b9ae3763), [#4767](https://github.com/heygen-com/hyperframes/pull/4767)). +- **Engine:** Preserve composition root background in alpha exports ([d7285e414](https://github.com/heygen-com/hyperframes/commit/d7285e414b36c89ba2bdf248966bd8388db25862), [#3976](https://github.com/heygen-com/hyperframes/pull/3976)). +- **Lint:** Dedupe CSS transform text in gsap_css_transform_conflict ([50864d57a](https://github.com/heygen-com/hyperframes/commit/50864d57a649004670fd7ac1f2f5792ae8974a70), [#3761](https://github.com/heygen-com/hyperframes/pull/3761)). +- **CLI:** Reject extra positional arguments passed to add ([ded5fa866](https://github.com/heygen-com/hyperframes/commit/ded5fa8661d5645ea87e17f82a09ff37017d3105), [#3891](https://github.com/heygen-com/hyperframes/pull/3891)). +- **CLI:** Recognize textual motion in sweep checks ([e8659cb65](https://github.com/heygen-com/hyperframes/commit/e8659cb65364154e030338b74589c649a9dd8408), [#3707](https://github.com/heygen-com/hyperframes/pull/3707)). +- **CLI:** Keep check --json stdout pure by sending proxy pre-resolve diagnostics to stderr ([1a619785d](https://github.com/heygen-com/hyperframes/commit/1a619785d5ef476f3495a1c08556481f189cc17f), [#3836](https://github.com/heygen-com/hyperframes/pull/3836)). +- **CLI:** Connector dash gate honours pathLength ([5aa3c8f72](https://github.com/heygen-com/hyperframes/commit/5aa3c8f72f26cbcc23dbef397281fc35a4569313), [#3954](https://github.com/heygen-com/hyperframes/pull/3954)). +- **CLI:** Refuse capture folders that resolve outside the output root ([d2cdad418](https://github.com/heygen-com/hyperframes/commit/d2cdad418a633cf686b7a7ff784b8e2db7da520f), [#4789](https://github.com/heygen-com/hyperframes/pull/4789)). +- **Media Use:** Honour HYPERFRAMES_PYTHON in the audio engine (#4614) ([f1b79d8e7](https://github.com/heygen-com/hyperframes/commit/f1b79d8e7bdb2f17224737e6b9990e9ace3dd5c6), [#4723](https://github.com/heygen-com/hyperframes/pull/4723)). +- **CLI:** Capture snapshot --at at the exact requested instant ([8aefd91bf](https://github.com/heygen-com/hyperframes/commit/8aefd91bf82c687222082a80a3c5845ff37e6ca6), [#4827](https://github.com/heygen-com/hyperframes/pull/4827)). +- **CLI:** Connector_detached now skips fully dash-hidden connector shafts ([efdabb758](https://github.com/heygen-com/hyperframes/commit/efdabb758d05f2666b1e4e13f32e447c4edfe760), [#3912](https://github.com/heygen-com/hyperframes/pull/3912)). +- **Lint:** Error on digit-leading ids only when a selector targets them ([385e9cf33](https://github.com/heygen-com/hyperframes/commit/385e9cf337c103d0918f9ea962c4e3859a2cc75f), [#3980](https://github.com/heygen-com/hyperframes/pull/3980)). +- **Lint:** Point the repeated fromTo baseline hint at immediateRender: false ([1248639e7](https://github.com/heygen-com/hyperframes/commit/1248639e71e08fd87722f9e5b186cf3fc514ca07), [#3895](https://github.com/heygen-com/hyperframes/pull/3895)). +- **Lint:** Flag an id override written with reduced-specificity selector forms ([9afafa79e](https://github.com/heygen-com/hyperframes/commit/9afafa79ec13cc52f14a83cadb3ec310a194b9c4), [#3871](https://github.com/heygen-com/hyperframes/pull/3871)). +- **Engine:** Warn when a video input declares alpha but decodes opaque ([cad7dbed0](https://github.com/heygen-com/hyperframes/commit/cad7dbed0dc29d53ec3a4bbb2b0bea2fa3c1495e), [#3771](https://github.com/heygen-com/hyperframes/pull/3771)). +- **CLI:** Route FFmpeg exec-failure hint through getFFmpegInstallHint() ([0eba8d6a0](https://github.com/heygen-com/hyperframes/commit/0eba8d6a06aafae286f9cbb784a121d1669d84a3), [#3877](https://github.com/heygen-com/hyperframes/pull/3877)). +- **Lint:** Ignore attribute values when checking media attributes ([924b93345](https://github.com/heygen-com/hyperframes/commit/924b9334566436be358b4ff0958a583e053fceec), [#4396](https://github.com/heygen-com/hyperframes/pull/4396)). +- **Producer:** Honor FFMPEG_PROCESS_TIMEOUT_MS during video-frame extraction ([e0d4c9600](https://github.com/heygen-com/hyperframes/commit/e0d4c960033514d5582f643c975d435f367fabd2), [#3918](https://github.com/heygen-com/hyperframes/pull/3918)). +- Unbreak the regression suite on Windows (PSNR filtergraph escaping + console window popups) ([9d6ca4585](https://github.com/heygen-com/hyperframes/commit/9d6ca4585794f430901269109df4a66a873134ce), [#3839](https://github.com/heygen-com/hyperframes/pull/3839)). +- **Engine:** Pin capture surface scale to 1 device pixel per CSS pixel ([6632d99c9](https://github.com/heygen-com/hyperframes/commit/6632d99c9cab5877671853fff408bf0202f0d542), [#3782](https://github.com/heygen-com/hyperframes/pull/3782)). +- **Release:** Use portable Git paths in release guards ([74e6df437](https://github.com/heygen-com/hyperframes/commit/74e6df4370acdb2adf20c1d7525f97a30a4bea52), [#3766](https://github.com/heygen-com/hyperframes/pull/3766)). + +## Docs & Examples + +- **Skills:** Fix unresolved cross-references in skill docs ([94650480e](https://github.com/heygen-com/hyperframes/commit/94650480e2690a14bf867b44e8978637713dd678), [#3951](https://github.com/heygen-com/hyperframes/pull/3951)). +- Align infinite-repeat guidance with bounded repeat: -1 lint ([6f799aaa4](https://github.com/heygen-com/hyperframes/commit/6f799aaa41d5874222aece2f4b78b759dfb1c913), [#3795](https://github.com/heygen-com/hyperframes/pull/3795)). +- Clarify skills installer behavior ([ecfcbb0c6](https://github.com/heygen-com/hyperframes/commit/ecfcbb0c61420ee67f8febf0e17e4d6c4f507c9b), [#3863](https://github.com/heygen-com/hyperframes/pull/3863)). + +## Internal + +- **Deps:** Update node.js ([0b88cd053](https://github.com/heygen-com/hyperframes/commit/0b88cd0537f6710b8e153a5cf3dca0bb19529cc0), [#4245](https://github.com/heygen-com/hyperframes/pull/4245)). +- **Renovate:** Stop raising engines and peer dependency floors ([6090f539e](https://github.com/heygen-com/hyperframes/commit/6090f539e6b14e024c9281eebff8c7c87f436862), [#4900](https://github.com/heygen-com/hyperframes/pull/4900)). +- **Deps:** Update github-actions ([29ded9b0f](https://github.com/heygen-com/hyperframes/commit/29ded9b0fa27004b1e48ca4edc0cb63d32d424a0), [#3934](https://github.com/heygen-com/hyperframes/pull/3934)). +- **Studio:** Score edits on GSAP-animated size, scale, rotation and keyframes ([70ed332a4](https://github.com/heygen-com/hyperframes/commit/70ed332a455d100b6e80091aacf9f0be7d75b1bd), [#4866](https://github.com/heygen-com/hyperframes/pull/4866)). + +[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.8.111...v0.8.112). + + Filmstrip contract

Filmstrip timeline clips

Frames edge to edge, cropped to fill, with the name in its own 15px band above the picture.

audited 4 boundariestrusting 0not exercised 4decisions 0Studio @ 45b8e171e2792c89cc63b4d136de41eae6194b25
+
In one breath. Studio owns the name and picture wrapper; thumbnail components own cropping; a host can replace the content and override the CSS tokens.
+

Where the value travels

flowchart LR +A[App or host] --> B[TimelinePane] --> C[TimelineClip] +C --> D[renderClipChildren] +D --> E[useRenderClipContent] +E --> F[Thumbnail components] +G[Host CSS overrides] --> C +classDef audited fill:#e8f6ee,stroke:#178a5a,color:#0f3d28 +class A,B,C,D,E,F,G audited +

Source reachability is audited. No running build has been exercised.

+

The contract, per boundary

1. Clip-content callback

The same callback builds picture content for Studio and embedding hosts.

renderClipContent(element, clipStyle, context)
+
+if (!pid) return null;
+
+return createElement(CompositionThumbnail, {
+  previewUrl: buildProjectApiPath(pid, `/preview/comp/${encodePreviewPath(compSrc)}`),
+  label: "",
+  labelColor: style.label,
producer: src/hooks/useRenderClipContent.ts:136,166; accepting call: src/player/components/timelineClipChildren.tsx:67; app handoff: src/App.tsx:530; pane: src/components/nle/TimelinePane.tsx:107; package export: src/index.ts:67
exists: yesreachable: source auditedwritten/read: yesruntime: not exercised

2. Picture wrapper and name

The clip button supplies the name separately. The content wrapper currently fills the whole button.

const showLabel = ladder === "labeled";
+{showLabel && <span className="timeline-clip__label">{displayLabel}</span>}
+
+<div
+  className="absolute inset-0 overflow-hidden"
+  style={{ borderRadius: "inherit", pointerEvents: "none" }}
+>
name producer and consumer: src/player/components/TimelineClip.tsx:74,212; content consumer: src/player/components/timelineClipChildren.tsx:63; name paint: src/styles/components.css:334
exists: yesreachable: source auditedwritten/read: yesruntime: not exercised

3. Frame layout and fit

Video and image tiles already fill their rectangles. Composition tiles contain the picture, which leaves letterboxing.

const frameW = Math.max(minFrameWidth, Math.round(clipHeight * safeAspect));
+const frameCount = measured ? Math.max(1, Math.ceil(containerWidth / frameW)) : 1;
+
+// CompositionThumbnail rendered image class:
+className="absolute inset-0 h-full w-full object-contain"
layout producer: src/player/components/thumbnailUtils.ts:75; consumer: CompositionThumbnail.tsx:161; image consumer: CompositionThumbnail.tsx:185; video and image fit: VideoThumbnail.tsx:138, ImageThumbnail.tsx:61
exists: yesreachable: source auditedwritten/read: yesruntime: not exercised

4. Theme and host overrides

Changing the Studio defaults alone does not change an embedding host that writes its own token values or selection styles.

--timeline-clip-radius: 8px;
+--timeline-clip-audio-radius: 21px;
+
+clipRadius: "var(--timeline-clip-radius)",
+
+.timeline-clip.is-selected {
+  outline: 1.5px solid var(--timeline-clip-selection);
+  outline-offset: -1.5px;
+}
token producer: src/styles/theme.css:122; token consumer: src/player/components/timelineTheme.ts:73, TimelineClip.tsx:109; selection consumer: src/styles/components.css:307; package exports: package.json:39-43. Host override audit is local only; runtime propagation has not been tested.
exists: yesreachable: source auditedwritten/read: yesruntime: not exercised
+

How it says no

SignalOwnerMeaning
nulluseRenderClipContent:142No active project. No picture returned.
Hidden thumbnail modeuseRenderClipContent:148Pictures are suppressed; sound content follows the existing waveform path.
Loading or error snapshotThumbnail componentA picture is not ready. The band must keep its geometry while the existing loading/error state paints below.
Under 60pxclipWidthLadderThe baseline hides the label. The approved Filmstrip keeps the name band for visual clips; audio retains the width ladder. The full name remains on the button's accessible label and title.
+

Approved specification

Match the selected Filmstrip prototype: a dark 15px name band, no picture dimming, zero frame gap, a 1px selection ring, and 12px corners on video and image clips. Audio keeps its current radius. Composition pictures keep contain fitting.

The band-colour ambiguity is resolved. No open product decision remains.

Coverage, honestly

AuditedThe callback producer, both app and host handoffs, picture wrapper, thumbnail layout, CSS paint, package exports, and host overrides.
TrustingNone of the load-bearing claims above rely on comments or mocks.
Not exercisedStudio and host rendered builds, browser layout, selection/trim/fade hit targets, light and dark contrast, narrow clips.
+

What would prove this page wrong

  • A running fixture whose name overlaps its picture after reserving the band at the clip wrapper.
  • A host build still painting 8px corners or its existing 2px plus 3px selection ring after the Studio release. This would expose a missed override.
  • A composition picture cropped to fill instead of retaining contain fitting.
+
Source audit, 2026-10-01. Runtime verification remains outstanding. This page records the pre-implementation boundary audit and the resolved specification.
+ diff --git a/docs/contracts/2026-10-02-ghost-lane-membership.html b/docs/contracts/2026-10-02-ghost-lane-membership.html new file mode 100644 index 0000000000..dd10721f21 --- /dev/null +++ b/docs/contracts/2026-10-02-ghost-lane-membership.html @@ -0,0 +1,67 @@ + +New-track membership contract

New-track drops leave an audio group

A clip lands exactly where the ghost showed. One undo restores its track and membership.

audited 5trusting 0not exercised 1open decisions 0hyperframes @ de13693179f53c3f625b7b501f1f5fc7b083b6c9, working changes, 2026-10-02
+
In one breath. At the audited base, the move transaction saved track and timing but dropped membership before persistence. Detachment must travel through that transaction, rather than become a second save.
+

Where the value travels

Drop edits → Move adapter → Source patch → File + history → Undo restore
+

The contract, per boundary

+

Move payload

At the audited base, membership was absent from the move payload. The adapter explicitly selects only these fields.

edits.map(({ element, updates }) => ({
+  element,
+  start: updates.start,
+  track: operation === "timing" ? undefined : updates.track,
+}))
producer src/player/components/timelineClipDragCommit.ts:153; consumer src/hooks/timelineMoveAdapter.ts:37. Paths relative to packages/studio.
membership: absentreachable: nowritten: no
+

Atomic source edit

The group move turns all clip changes into source patches inside one queued file transaction. Track changes bypass the timing-only SDK path.

buildTimelineMoveTimingPatch(
+  original,
+  target,
+  toAuthoredStart(change.element, change.start),
+  change.element.duration,
+  change.track,
+)
producer src/hooks/useTimelineGroupEditing.ts:311; consumer src/hooks/timelineEditingHelpers.ts:235. SDK eligibility src/hooks/useTimelineGroupEditing.ts:299.
track: existsreachablewritten
+

Undo owns whole-file snapshots

One transaction records the complete before and after source. Including membership in the same patch gives undo its original value.

snapshots[path] = { before, after };
+await recordEdit({ label, coalesceKey, coalesceMs, files: snapshots });
producer src/utils/studioFileHistory.ts:128,144; undo consumer src/hooks/usePersistentEditHistory.ts:81,99; preview sync consumer src/hooks/useEditHistoryActions.ts:112.
snapshots: existreachablewritten and restored
+

How it says no

SignalMeaning and response
Locked shifted clipInsertion returns without persistence. Existing permission rules remain the owner.
Save rejectionThe file transaction restores already-written snapshots and rethrows. The optimistic clip rollback must restore membership alongside timing and track.
Undo content mismatchHistory refuses to overwrite a file changed since the edit and reports the conflict.
+

Decision already supplied

New tracks outside a group detach the dragged clip. Drops onto member tracks retain existing behavior. Cmd+Z restores membership. There is no open product decision.
+

Coverage, honestly

LabelCoverage
AuditedDrop edits, adapter, group move, source patch, snapshot and undo consumers opened at the named base.
Not exercisedThis page records the pre-implementation audit. Runtime proof is reported separately against the implementation head.
+

What would prove this page wrong

Drop a grouped clip at a group edge, reload the file, then Cmd+Z. The clip must lose membership after the drop, occupy the promised lane, and regain its original track and membership in one undo. A member-track drop must retain membership.

diff --git a/docs/contracts/2026-10-02-thumbnail-document-lifetime.html b/docs/contracts/2026-10-02-thumbnail-document-lifetime.html new file mode 100644 index 0000000000..1407a24e4c --- /dev/null +++ b/docs/contracts/2026-10-02-thumbnail-document-lifetime.html @@ -0,0 +1,59 @@ + +Thumbnail document lifetime

Thumbnail connections leave with their document

Saves must not queue behind media from a document the person already left.

2026-10-02 · source 0337620 · audited 4 · trusting 0 · not exercised 1 · decisions 0
+

In one breath

The scheduler bounds work in one document, but old documents retain thumbnail connections after navigation; the lifecycle actor must abort that work on pagehide and resume retained leases on pageshow.
+

Where the value travels

pagehide / pageshow → One lifecycle actor → Thumbnail scheduler → AbortSignal → fetch / media decoder
+

The verified boundaries

Scheduler owns work

entry.controller = new AbortController();
+entry.request.load(controller.signal)
Producer packages/studio/src/player/lib/thumbnailScheduler.ts:291-301; consumer packages/studio/src/player/components/CompositionThumbnail.tsx:104-112.

The controller exists, is passed to the actual fetch, and is already aborted when the final lease leaves. Document navigation currently has no scheduler actor.

+

Abort and retain

entry.preempted = true;
+entry.controller?.abort();
Producer thumbnailScheduler.ts:228-231; consumer catch/requeue/pump at :301-320 and :344-351. Paths relative to packages/studio/src/player/lib.

Existing preview reload preempts composition jobs and retains leases. Pagehide and document visibility suspension must be a separate cause: pageshow cannot release a preview-reload hold. While suspended, no queued thumbnail kind may start.

+

The receiving HTTP route

await thumbnailGenerationCoordinator.acquire(
+  cachePath, c.req.raw.signal, async (signal) => adapter.generateThumbnail({ signal, ... })
+)
packages/studio-server/src/routes/thumbnail.ts:227-244; client fetch signal at CompositionThumbnail.tsx:108-110.

Client abort releases its browser connection. Server cancellation propagation is a separate host concern; the dev HTTP bridge must forward response disconnects into that signal so queued renders lose their leases. The endpoint is a one-shot image response, not a stream or long poll. Its serial queue had no server deadline; the existing client deadline is 30 seconds, but old-document timers may stop after navigation. Lifecycle abort plus propagated disconnect removes abandoned work instead of waiting for that timer.

+

How it says no

SignalMeaning
AbortErrorRequested cancellation; retained leases return to the queue. No thumbnail error state.
Document hiddenAbort active work and hold all queued thumbnail kinds.
Preview reload remains activePageshow permits other thumbnail kinds, but composition work retains its existing hold.
+

Decision already supplied

Saves never queue behind media. Fix the held connections, preserve a tight persistence bound. No new product decision.
+

Coverage, honestly

Audited: scheduler, real composition fetch, preview-reload caller, server consumer. Runtime: Chrome NetLog shows all six sockets occupied by thumbnails, four from previous documents and two current, at a PUT stalled by the per-host socket limit. A real HTTP regression holds render responses open across hidden project documents and verifies a durable drop within 15 seconds. Removing the lifecycle binding fails that exact persistence assertion. Unit checks cover all thumbnail kinds, resumption, independent preview holds and actual HTTP disconnects.

+

What would prove this page wrong

Hold real thumbnail render responses open, leave two project documents, then drop a clip. Old-document render requests must cancel before the next document saves; the drop must persist within 15 seconds while current thumbnails remain unfinished. Cache-only poster reads return an image or 404 without entering the render queue. Retained leases must resume and preview-reload holds must survive pageshow.

diff --git a/docs/guides/claude-design-hyperframes.md b/docs/guides/claude-design-hyperframes.md index b16df8953e..d385055488 100644 --- a/docs/guides/claude-design-hyperframes.md +++ b/docs/guides/claude-design-hyperframes.md @@ -374,7 +374,7 @@ The skeleton handles most structural rules. These are the runtime rules the skel | `Math.random()` | Seeded PRNG (only if you need randomness) | | `Date.now()`, `performance.now()` | Hard-coded timing or `tl.time()` in `onUpdate` | | `setInterval`, `setTimeout` | Timeline tweens + `onUpdate` | -| `repeat: -1` | `repeat: Math.max(0, Math.floor(duration / cycle) - 1)` | +| `repeat: -1` without root `data-duration` | a finite root `data-duration` (export clips to it), or `repeat: Math.max(0, Math.floor(duration / cycle) - 1)` | | `stagger: { from: "random" }` | `from: "start"`, `"center"`, `"end"` | | Async timeline construction | Synchronous at page load | @@ -416,7 +416,7 @@ Run before delivering. Check with actual code, not assumptions. - [ ] Shader transitions have boundary INSIDE the window: `time < boundary < time + duration` - [ ] No transition shorter than 0.3s - [ ] No exit tweens except on the final scene -- [ ] No `Date.now()`, unseeded `Math.random()`, `repeat: -1` +- [ ] No `Date.now()`, unseeded `Math.random()`, or `repeat: -1` without a finite root `data-duration` - [ ] No SVG filter data URLs as `background-image` - [ ] `window.__timelines["main"] = tl` matches `data-composition-id` diff --git a/docs/guides/claude-design-send-to-hyperframes.md b/docs/guides/claude-design-send-to-hyperframes.md index bfb3aa8077..17c4a8defc 100644 --- a/docs/guides/claude-design-send-to-hyperframes.md +++ b/docs/guides/claude-design-send-to-hyperframes.md @@ -371,7 +371,7 @@ The cloud renderer seeks the timeline frame-by-frame. Non-deterministic or self- | `Date.now()`, `performance.now()` | hard-coded timing or `tl.time()` in `onUpdate` | | `setInterval`, `setTimeout` | timeline tweens + `onUpdate` | | `requestAnimationFrame` | GSAP tweens | -| `repeat: -1` | `repeat: Math.max(0, Math.floor(duration / cycle) - 1)` | +| `repeat: -1` without root `data-duration` | a finite root `data-duration` (export clips to it), or `repeat: Math.max(0, Math.floor(duration / cycle) - 1)` | | `stagger: { from: "random" }` | `from: "start"`, `"center"`, or `"end"` | | async timeline construction | build synchronously at page load | | `video.play()` / `audio.play()` | the framework owns playback | @@ -429,6 +429,6 @@ You don't author any of this. Produce a clean, on-brand, correctly-timed silent - [ ] No exit tweens except on the final scene **Renders correctly:** -- [ ] No `Date.now()`, unseeded `Math.random()`, `setInterval/Timeout`, `requestAnimationFrame`, `repeat: -1` +- [ ] No `Date.now()`, unseeded `Math.random()`, `setInterval/Timeout`, `requestAnimationFrame`, or `repeat: -1` without a finite root `data-duration` - [ ] Timeline built synchronously; paused; framework owns playback - [ ] Colors and fonts exact; brand substance preserved: real headline/copy, distinctive figures/stats/data points, product names, and signature visuals carried over verbatim (form adapted, never genericized or invented); no placeholders; ≥2 animation patterns + mid-scene activity per scene diff --git a/docs/packages/cli.mdx b/docs/packages/cli.mdx index 8b2d3d2b8d..d454219b52 100644 --- a/docs/packages/cli.mdx +++ b/docs/packages/cli.mdx @@ -662,7 +662,7 @@ did, in one command and one browser session. ```bash npx hyperframes check [dir] -npx hyperframes check [dir] --json # {ok, lint, runtime, layout, motion, contrast, snapshots} +npx hyperframes check [dir] --json # {ok, browserSkipped, lint, runtime, layout, motion, contrast, hdr, snapshots} npx hyperframes check [dir] --snapshots npx hyperframes check [dir] --at 1.5,4,7.25 npx hyperframes check [dir] --strict # warnings fail too @@ -674,6 +674,10 @@ running every audit at every sample: runtime console errors and failed requests, layout defects (overflow, clipping, held overlaps, occlusion, coordinate-frame drift), `*.motion.json` assertions, and WCAG AA contrast. +When the browser never ran (lint errors, a linter crash, or a browser launch +failure), `browserSkipped` is `true` and the `layout`, `motion` and `contrast` +sections are empty, not clean. + | Flag | Description | | -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `--json` | One aggregated envelope. Every finding carries a selector, `data-*` identity, source file, bbox, and sample time. | @@ -747,6 +751,16 @@ HTML. Without a sidecar, nothing changes. | `staysInFrame(selector)` | Off-frame drift — once visible, the box never leaves the canvas (`motion_off_frame`) | | `keepsMoving(withinSelector?)` | A frozen shot — no fully static window longer than `maxStaticSec`, default 2s (`motion_frozen`) | +`keepsMoving` uses the same motion classifier as the frozen-sweep guard: box +geometry, opacity, text and generated content, form-control state, painted CSS +counters, clip-path, variable-font axes, and the pixels of visible +canvas/video/img elements all count as motion — so a playing same-origin (or +CORS-readable) background video keeps a scope live on its own. Elements under +`data-layout-ignore` inside the scope never count; the opt-out does not apply to +the scope element itself, since naming it in an assertion outranks it. Content +the browser does not paint (`display: none` subtrees, `visibility: hidden` +boxes, skipped `content-visibility` contents) never counts as motion either. + `duration`, `keepsMoving.withinSelector`, and `keepsMoving.maxStaticSec` are optional. Findings use the same shape and envelope as layout findings and are errors by default, so a failed assertion fails the run. A selector that matches diff --git a/docs/packages/lint.mdx b/docs/packages/lint.mdx index 2a4e10fc68..414f9b3fd9 100644 --- a/docs/packages/lint.mdx +++ b/docs/packages/lint.mdx @@ -116,6 +116,8 @@ Detected issues include: reachable from timeline callbacks (`gsap_callback_dom_measurement`), and non-deterministic values like `gsap.utils.random()` / `"random(...)"` (`non_deterministic_code`) +- CSS `transition` declarations, which run on the browser clock and restart on a cold + render worker (`css_transition_used`, a warning); `none` and all-zero durations are allowed - SVG draw-on pitfalls: GSAP `strokeDasharray` writes on elements whose CSS declares a multi-component `stroke-dasharray` (`svg_drawon_css_dasharray_conflict`), `getTotalLength()` on paths with no `d` yet (`svg_measure_before_path_d`), and diff --git a/docs/reference/html-schema.mdx b/docs/reference/html-schema.mdx index 7c12049073..5127957bcc 100644 --- a/docs/reference/html-schema.mdx +++ b/docs/reference/html-schema.mdx @@ -297,6 +297,13 @@ A composition using GSAP must: HyperFrames controls seeking. Composition code describes how the visual state looks at a given time. +Every element with `data-composition-id` participates in timeline readiness. +For a static nested section, use an ordinary `id` instead, or add +`data-no-timeline` to declare that no timeline will be registered. Otherwise, +the renderer waits up to the player-ready timeout for that element's timeline. +`hyperframes lint` reports bare composition hosts that have neither a matching +timeline registration nor an explicit opt-out as `missing_data_no_timeline`. + ## Validate ```bash diff --git a/gemini-extension.json b/gemini-extension.json index 17d30a4b0f..a3d93791eb 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,5 +1,5 @@ { "name": "hyperframes", - "version": "0.8.111", + "version": "0.8.114", "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 1ff810a047..9ec364228c 100644 --- a/packages/aws-lambda/package.json +++ b/packages/aws-lambda/package.json @@ -1,6 +1,6 @@ { "name": "@hyperframes/aws-lambda", - "version": "0.8.111", + "version": "0.8.114", "description": "AWS Lambda adapter for HyperFrames distributed rendering — handler, client-side SDK, and CDK construct.", "repository": { "type": "git", diff --git a/packages/cli/package.json b/packages/cli/package.json index 599c6f7f9f..e4f1e6c7e0 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@hyperframes/cli", - "version": "0.8.111", + "version": "0.8.114", "description": "HyperFrames CLI — create, preview, and render HTML video compositions", "license": "Apache-2.0", "repository": { diff --git a/packages/cli/scripts/build-copy.mjs b/packages/cli/scripts/build-copy.mjs index 83e0fbc5c3..177ab7d1e7 100644 --- a/packages/cli/scripts/build-copy.mjs +++ b/packages/cli/scripts/build-copy.mjs @@ -118,6 +118,11 @@ async function main() { cpSync(contrastAuditScript, join(DIST, "commands", "contrast-audit.browser.js")); } + const motionSignatureScript = join(CLI_ROOT, "src", "commands", "motion-signature.browser.js"); + if (existsSync(motionSignatureScript)) { + cpSync(motionSignatureScript, join(DIST, "commands", "motion-signature.browser.js")); + } + const motionSampleScript = join(CLI_ROOT, "src", "commands", "motion-sample.browser.js"); if (existsSync(motionSampleScript)) { cpSync(motionSampleScript, join(DIST, "commands", "motion-sample.browser.js")); diff --git a/packages/cli/src/browser/manager.test.ts b/packages/cli/src/browser/manager.test.ts index 0490996773..e576f7d7aa 100644 --- a/packages/cli/src/browser/manager.test.ts +++ b/packages/cli/src/browser/manager.test.ts @@ -21,7 +21,9 @@ * `background-removal/manager.test.ts`) so we don't touch the real * `HOME` cache. */ -import { join, sep } from "node:path"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, relative, sep } from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { managedChromeVersion } from "./manager.js"; @@ -59,6 +61,27 @@ const TEST_LOCK_TIMINGS = { waitNoticeMs: 1_000, }; +// Points node:os homedir at a fresh temp dir so the manager runs against the real filesystem. +function useRealCacheHome(): string { + const home = mkdtempSync(join(tmpdir(), "hf-browser-cache-")); + vi.doMock("node:os", async (importOriginal) => ({ + ...(await importOriginal()), + homedir: () => home, + })); + return home; +} + +function writeStagedInstall(cacheDir: string, buildId: string, content: string) { + const path = join(cacheDir, "chrome-headless-shell", `linux-${buildId}`); + const executablePath = join(path, "chrome-headless-shell-linux64", "chrome-headless-shell"); + mkdirSync(dirname(executablePath), { recursive: true }); + writeFileSync(executablePath, content); + return { executablePath, path }; +} + +// The mocked fs path set of the current test, so the install mock can stage files into it. +let mockedPaths: Set | undefined; + interface FsMockOptions { existing: ReadonlySet; /** map of dir path -> entries returned by readdirSync */ @@ -79,13 +102,18 @@ function installFsMocks({ // Mutable, and returned, so tests can pre-seed a "lock already held" path or // assert the lock dir doesn't leak after ensureBrowser resolves. const paths = new Set(existing); + mockedPaths = paths; const mtimes = new Map([...existing].map((p) => [p, initialMtimeMs])); const contents = new Map(); vi.doMock("node:fs", () => ({ existsSync: (p: string) => paths.has(p), readdirSync: (p: string) => { const entries = dirs?.[p]; - if (!entries) throw new Error(`ENOENT: readdirSync mock had no entry for ${p}`); + if (!entries) { + const err = new Error(`ENOENT: readdirSync mock had no entry for ${p}`); + (err as NodeJS.ErrnoException).code = "ENOENT"; + throw err; + } return entries; }, mkdirSync: (p: string, opts?: { recursive?: boolean }) => { @@ -109,6 +137,18 @@ function installFsMocks({ } } }, + renameSync: (from: string, to: string) => { + const moved = [...paths].filter((p) => p === from || p.startsWith(from + sep)); + if (moved.length === 0) { + const err = new Error(`ENOENT: no such file or directory, rename '${from}'`); + (err as NodeJS.ErrnoException).code = "ENOENT"; + throw err; + } + for (const p of moved) { + paths.delete(p); + paths.add(to + p.slice(from.length)); + } + }, statSync: (p: string) => { if (!paths.has(p)) { const err = new Error(`ENOENT: no such file or directory, stat '${p}'`); @@ -160,10 +200,25 @@ function installPuppeteerBrowsersMock( }>; browserPlatform?: string; installedInHfCacheError?: Error; - installResult?: { executablePath: string }; - installImpl?: (options: { buildId: string }) => Promise<{ executablePath: string }>; + installResult?: { executablePath: string; path?: string }; + installImpl?: (options: { + buildId: string; + cacheDir: string; + }) => Promise<{ executablePath: string; path?: string }>; } = {}, ) { + const impl = + opts.installImpl ?? (async () => opts.installResult ?? { executablePath: HF_BINARY }); + // Fixtures name the binary where it lands in HF_CACHE; install() really writes it under its own cacheDir. + const stagedInstall = async (options: { buildId: string; cacheDir: string }) => { + const result = await impl(options); + if (result.path || !result.executablePath.startsWith(HF_CACHE + sep)) return result; + const rel = relative(HF_CACHE, result.executablePath); + const executablePath = join(options.cacheDir, rel); + const path = join(options.cacheDir, ...rel.split(sep).slice(0, 2)); + mockedPaths?.add(path).add(executablePath); + return { executablePath, path }; + }; vi.doMock("@puppeteer/browsers", () => ({ Browser: { CHROMEHEADLESSSHELL: "chrome-headless-shell" }, detectBrowserPlatform: () => opts.browserPlatform ?? "linux", @@ -175,11 +230,7 @@ function installPuppeteerBrowsersMock( ...browser, })), ), - install: vi - .fn() - .mockImplementation( - opts.installImpl ?? (async () => opts.installResult ?? { executablePath: HF_BINARY }), - ), + install: vi.fn().mockImplementation(stagedInstall), })); } @@ -378,8 +429,9 @@ describe("findBrowser — cache resolution", () => { // The stale install DIR is present (extraction got partway through, e.g. an // ABOUT/LICENSE-only extract) even though the exe itself is missing — // exercises the purge-before-redownload fix, not just the redownload path. + const staleLeftover = join(staleInstallDir, "ABOUT"); const paths = installFsMocks({ - existing: new Set([HF_CACHE, staleInstallDir]), + existing: new Set([HF_CACHE, staleInstallDir, staleLeftover]), }); installPuppeteerBrowsersMock({ installedInHfCache: [ @@ -402,13 +454,13 @@ describe("findBrowser — cache resolution", () => { source: "download", }); expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("Cached binary missing")); - // The stale directory must be gone before @puppeteer/browsers' install() - // sees it — otherwise install() throws "folder exists but exe missing" - // instead of re-extracting (the exact bug both feedback reports hit). - expect(paths.has(staleInstallDir)).toBe(false); + // The partial extract is replaced wholesale, not merged into (install() would + // otherwise throw "folder exists but exe missing", the bug both feedback reports hit). + expect(paths.has(staleLeftover)).toBe(false); + expect(paths.has(redownloadedBinary)).toBe(true); }); - it("ensureBrowser({force: true}) purges the whole cache before downloading, bypassing any cache/system shortcut", async () => { + it("ensureBrowser({force: true}) re-downloads without purging the cache, bypassing any cache/system shortcut", async () => { const staleInstallDir = join(HF_CACHE, "chrome-headless-shell", "linux-131.0.6778.85"); const downloadedBinary = join(HF_CACHE, "chrome-headless-shell", "force-downloaded"); // A HEALTHY cached binary AND system Chrome are both present — force must @@ -436,14 +488,88 @@ describe("findBrowser — cache resolution", () => { executablePath: downloadedBinary, source: "download", }); - // clearBrowser() wipes prior contents; withInstallLock uses a sibling lock - // outside CACHE_DIR, so assert the purge on what was actually INSIDE it, - // not the directory's own existence. - expect(paths.has(staleInstallDir)).toBe(false); - expect(paths.has(HF_BINARY)).toBe(false); + // Only the downloaded version dir is swapped in; other cache entries stay. + expect(paths.has(downloadedBinary)).toBe(true); + expect(paths.has(HF_BINARY)).toBe(true); }); - it("serializes concurrent force downloads so one purge cannot delete another installer's lock", async () => { + it("keeps a live reader's binary valid while a concurrent --force re-downloads it", async () => { + const home = useRealCacheHome(); + let label = "old"; + let seenMidInstall: string | undefined; + let liveBinary: string | undefined; + installPuppeteerBrowsersMock({ + installImpl: async ({ cacheDir, buildId }) => { + if (liveBinary) seenMidInstall = readFileSync(liveBinary, "utf8"); + return writeStagedInstall(cacheDir, buildId, label); + }, + }); + try { + const { ensureBrowser, CACHE_DIR } = await import("./manager.js"); + const otherVersion = join(CACHE_DIR, "chrome-headless-shell", "linux-1.0.0", "marker"); + mkdirSync(dirname(otherVersion), { recursive: true }); + writeFileSync(otherVersion, "other"); + + liveBinary = (await ensureBrowser({ force: true })).executablePath; + label = "new"; + const forced = await ensureBrowser({ force: true }); + + expect(seenMidInstall).toBe("old"); + expect(forced.executablePath).toBe(liveBinary); + expect(readFileSync(liveBinary, "utf8")).toBe("new"); + expect(readFileSync(otherVersion, "utf8")).toBe("other"); + } finally { + rmSync(home, { recursive: true, force: true }); + } + }); + + it("restores the previous version when the staged install cannot be moved in", async () => { + const home = useRealCacheHome(); + let stageNothing = false; + installPuppeteerBrowsersMock({ + installImpl: async ({ cacheDir, buildId }) => { + const staged = writeStagedInstall(cacheDir, buildId, "old"); + if (stageNothing) rmSync(staged.path, { recursive: true, force: true }); + return staged; + }, + }); + try { + const { ensureBrowser } = await import("./manager.js"); + const liveBinary = (await ensureBrowser({ force: true })).executablePath; + stageNothing = true; + + await expect(ensureBrowser({ force: true })).rejects.toThrow("HYPERFRAMES_BROWSER_PATH"); + expect(readFileSync(liveBinary, "utf8")).toBe("old"); + } finally { + rmSync(home, { recursive: true, force: true }); + } + }); + + it("sweeps dirs leaked by a killed install on the next install and on clear", async () => { + const home = useRealCacheHome(); + installPuppeteerBrowsersMock({ + installImpl: async ({ cacheDir, buildId }) => writeStagedInstall(cacheDir, buildId, "fresh"), + }); + const root = join(home, ".cache", "hyperframes"); + const leftovers = [join(root, ".chrome-staging-dead"), join(root, ".chrome-replaced-dead")]; + const seedLeftovers = () => { + for (const dir of leftovers) mkdirSync(join(dir, "partial"), { recursive: true }); + }; + try { + const { ensureBrowser, clearBrowser } = await import("./manager.js"); + seedLeftovers(); + await ensureBrowser({ force: true }); + expect(leftovers.filter((dir) => existsSync(dir))).toEqual([]); + + seedLeftovers(); + expect(clearBrowser()).toBe(true); + expect(leftovers.filter((dir) => existsSync(dir))).toEqual([]); + } finally { + rmSync(home, { recursive: true, force: true }); + } + }); + + it("serializes concurrent force downloads so they never install at the same time", async () => { const downloadedBinary = join(HF_CACHE, "chrome-headless-shell", "force-downloaded"); const paths = installFsMocks({ existing: new Set([CACHE_ROOT, HF_CACHE, HF_BINARY]), diff --git a/packages/cli/src/browser/manager.ts b/packages/cli/src/browser/manager.ts index 6ed2cfd578..6c19d2ba79 100644 --- a/packages/cli/src/browser/manager.ts +++ b/packages/cli/src/browser/manager.ts @@ -6,14 +6,14 @@ import { mkdirSync, readFileSync, readdirSync, + renameSync, rmSync, statSync, utimesSync, writeFileSync, } from "node:fs"; -import { basename } from "node:path"; import { homedir } from "node:os"; -import { join } from "node:path"; +import { basename, dirname, join, relative } from "node:path"; import { chromeMajorCeiling, exceedsChromeCeiling } from "@hyperframes/engine/chrome-host-ceiling"; import { normalizeErrorMessage } from "../utils/errorMessage.js"; import { runRenderSetupWorker } from "../utils/cancellableProcess.js"; @@ -244,8 +244,7 @@ export interface BrowserResult { export interface EnsureBrowserOptions { onProgress?: (downloadedBytes: number, totalBytes: number) => void; - // Purge any cached HF-managed download before resolving, so a stale or - // partially-extracted install can't make the retry look like a no-op. + // Re-download the managed build even when cached; only its version dir is replaced. force?: boolean; // Always resolve to OUR pinned `CHROME_VERSION` build (cached, or freshly // downloaded) — skip both the shared puppeteer-cache preference (some other @@ -264,23 +263,6 @@ export interface EnsureBrowserOptions { interface CacheLookupResult { result?: BrowserResult; staleHyperframesCachePath?: string; - // Root install-folder path for the stale entry (InstalledBrowser#path), NOT - // the missing executablePath above — this is what actually needs deleting. - staleInstallPath?: string; -} - -/** - * Remove one browser version's install directory (not the whole CACHE_DIR). - * @puppeteer/browsers' install() treats an existing-but-incomplete directory - * as already installed and throws "folder exists but executable is missing" - * rather than re-extracting — so an extraction interrupted by a Windows AV - * lock, a sleep/wake cycle, or ctrl-C (left with only alphabetically-early - * files like ABOUT/LICENSE, no exe) wedges every subsequent ensure/render - * with the same error until someone manually deletes the directory. Purging - * it first makes the retry actually retry. - */ -function purgeStaleInstall(installPath: string): void { - rmSync(installPath, { recursive: true, force: true }); } // --- Internal helpers ------------------------------------------------------- @@ -399,7 +381,7 @@ async function findFromHyperframesCache(): Promise { return { result: { executablePath: match.executablePath, source: "cache" } }; } if (match) { - return { staleHyperframesCachePath: match.executablePath, staleInstallPath: match.path }; + return { staleHyperframesCachePath: match.executablePath }; } return {}; } @@ -588,10 +570,7 @@ export async function findBrowser(): Promise { `[browser] Cached binary missing at ${fromCache.staleHyperframesCachePath} — re-downloading...`, ); try { - return await withInstallLock(async () => { - if (fromCache.staleInstallPath) purgeStaleInstall(fromCache.staleInstallPath); - return downloadBrowser(); - }); + return await withInstallLock(() => downloadBrowser()); } catch (err) { const cause = normalizeErrorMessage(err); throw new Error( @@ -684,10 +663,7 @@ async function ensureBrowserInCurrentProcess( console.warn( `[browser] Cached binary missing at ${fromCache.staleHyperframesCachePath} — re-downloading...`, ); - return withInstallLock(async () => { - if (fromCache.staleInstallPath) purgeStaleInstall(fromCache.staleInstallPath); - return downloadBrowser(options); - }); + return withInstallLock(() => downloadBrowser(options)); } if (!options?.preferManagedChrome) { @@ -700,24 +676,15 @@ async function ensureBrowserInCurrentProcess( } return withInstallLock(async () => { - if (options?.force) { - // `--force` means "always get a fresh managed download" — purging the - // whole HF-managed cache after acquiring the install lock keeps two - // concurrent force retries from deleting each other's in-flight lock or - // partially extracted install. - clearBrowser(); - } - // Re-check after acquiring the lock: a concurrent invocation may have // finished installing while we were waiting, in which case reuse its // result instead of downloading and extracting a second time. Skipped - // under --force, which already purged and always wants a fresh download. + // under --force, which always wants a fresh download. if (!options?.force) { const afterLock = await (options?.preferManagedChrome ? findFromHyperframesCache() : findFromCache()); if (afterLock.result) return afterLock.result; - if (afterLock.staleInstallPath) purgeStaleInstall(afterLock.staleInstallPath); } return downloadBrowser(options); }); @@ -837,43 +804,84 @@ async function downloadBrowser(options?: EnsureBrowserOptions): Promise rmSync(stagingDir, { recursive: true, force: true }); const runInstall = () => install({ - cacheDir: CACHE_DIR, + cacheDir: stagingDir, browser: Browser.CHROMEHEADLESSSHELL, buildId: managedChromeVersion(), platform, downloadProgressCallback: options?.onProgress, }); - let installed; try { - installed = await installWithCorruptArchiveRecovery( - runInstall, - () => { - rmSync(CACHE_DIR, { recursive: true, force: true }); - mkdirSync(CACHE_DIR, { recursive: true }); - }, - (err) => - console.warn( - `[hyperframes] Cached browser archive was corrupt (${normalizeErrorMessage(err)}); clearing the cache and re-downloading.`, - ), + const staged = await installWithCorruptArchiveRecovery(runInstall, clearStaging, (err) => + console.warn( + `[hyperframes] Downloaded browser archive was corrupt (${normalizeErrorMessage(err)}); re-downloading.`, + ), ); + return { executablePath: moveStagedInstallIntoCache(stagingDir, staged), source: "download" }; } catch (err) { throw wrapDownloadFailureWithBrowserPathHint(err); + } finally { + clearStaging(); } - - return { executablePath: installed.executablePath, source: "download" }; } -/** - * Remove the cached Chrome download directory. - * Returns true if anything was removed. - */ -export function clearBrowser(): boolean { - if (!existsSync(CACHE_DIR)) { - return false; +// Swap one staged version dir into CACHE_DIR by rename, never deleting the cache under live users: +// a running old binary keeps its inode, and a stale partial extract (exe missing) is replaced too. +function moveStagedInstallIntoCache( + stagingDir: string, + staged: { path: string; executablePath: string }, +): string { + const target = join(CACHE_DIR, relative(stagingDir, staged.path)); + const aside = join(CACHE_ROOT_DIR, `${REPLACED_PREFIX}${randomUUID()}`); + mkdirSync(dirname(target), { recursive: true }); + let replaced = false; + try { + renameSync(target, aside); + replaced = true; + } catch (err) { + if (!isErrno(err, "ENOENT")) throw err; } + try { + renameSync(staged.path, target); + } catch (err) { + if (replaced) renameSync(aside, target); + throw err; + } + if (replaced) rmSync(aside, { recursive: true, force: true }); + return join(target, relative(staged.path, staged.executablePath)); +} + +const STAGING_PREFIX = ".chrome-staging-"; +const REPLACED_PREFIX = ".chrome-replaced-"; + +// Staging and set-aside dirs outlive an install killed by a signal, since `finally` never runs. +function removeInstallLeftovers(): boolean { + let names: string[]; + try { + names = readdirSync(CACHE_ROOT_DIR); + } catch (err) { + if (isErrno(err, "ENOENT")) return false; + throw err; + } + const leftovers = names.filter( + (name) => name.startsWith(STAGING_PREFIX) || name.startsWith(REPLACED_PREFIX), + ); + for (const name of leftovers) + rmSync(join(CACHE_ROOT_DIR, name), { recursive: true, force: true }); + return leftovers.length > 0; +} + +// Deletes the managed Chrome cache and interrupted-install leftovers; true when any of them existed. +export function clearBrowser(): boolean { + const removedLeftovers = removeInstallLeftovers(); + if (!existsSync(CACHE_DIR)) return removedLeftovers; rmSync(CACHE_DIR, { recursive: true, force: true }); return true; } diff --git a/packages/cli/src/browser/preflight.test.ts b/packages/cli/src/browser/preflight.test.ts index fa55b8c79d..13ef3a2b32 100644 --- a/packages/cli/src/browser/preflight.test.ts +++ b/packages/cli/src/browser/preflight.test.ts @@ -162,10 +162,40 @@ describe("runEnvironmentChecks", () => { }); expect(ffmpeg?.detail).toContain(process.execPath); expect(ffmpeg?.detail).toContain("3221225781"); - expect(ffmpeg?.hint).toContain("working 64-bit FFmpeg build"); expect(result.ffmpegPath).toBeUndefined(); }); + // Windows DLL advice only on Windows; elsewhere the platform install hint. + describe("FFmpeg cannot-start hint is platform-specific", () => { + const realPlatform = process.platform; + + afterEach(() => { + Object.defineProperty(process, "platform", { value: realPlatform, configurable: true }); + }); + + it.each([ + { platform: "darwin" as const, expectedHint: "brew install ffmpeg" }, + { platform: "sunos" as const, expectedHint: "https://ffmpeg.org/download.html" }, + { + platform: "win32" as const, + expectedHint: "Install a working 64-bit FFmpeg build with all required runtime DLLs.", + }, + ])("gives the $platform cannot-start hint", async ({ platform, expectedHint }) => { + Object.defineProperty(process, "platform", { value: platform, configurable: true }); + runProcess.mockImplementation((binaryPath: string) => { + if (binaryPath !== process.env.HYPERFRAMES_FFMPEG_PATH) + return Promise.resolve({ stdout: "ffprobe version 7.1.1\n", stderr: "" }); + throw Object.assign(new Error("cannot execute binary file"), { status: 126 }); + }); + + const result = await runEnvironmentChecks(); + const ffmpeg = result.outcomes.find((outcome) => outcome.name === "FFmpeg"); + + expect(ffmpeg?.title).toBe("FFmpeg cannot start"); + expect(ffmpeg?.hint).toBe(expectedHint); + }); + }); + it("validates an explicit browser path without needing browser discovery", async () => { const result = await runEnvironmentChecks({ includeBrowser: true, diff --git a/packages/cli/src/browser/preflight.ts b/packages/cli/src/browser/preflight.ts index 40afdc2f09..d706192baa 100644 --- a/packages/cli/src/browser/preflight.ts +++ b/packages/cli/src/browser/preflight.ts @@ -122,7 +122,10 @@ async function checkFFmpeg(signal?: AbortSignal): Promise { }); }); }); + +describe("a planted directory link inside the capture directory (#4304)", () => { + // Creating symlinks needs elevated rights on Windows. + const posixOnly = it.skipIf(process.platform === "win32"); + + function plantedLink(root: string, link: string): { outputDir: string; outside: string } { + const outputDir = join(root, "capture"); + const outside = join(root, "outside"); + mkdirSync(join(outputDir, link, ".."), { recursive: true }); + mkdirSync(outside); + symlinkSync(outside, join(outputDir, link)); + return { outputDir, outside }; + } + + posixOnly.each(["assets", "assets/svgs"])( + "refuses to write page-derived assets through a planted %s/ symlink", + async (link) => { + await withTempDir(async (root) => { + const { outputDir, outside } = plantedLink(root, link); + const svgs = [ + { + outerHTML: ``, + isLogo: false, + }, + ]; + + await expect( + downloadAssets({ svgs, sections: [], ogImage: "" } as unknown as DesignTokens, outputDir), + ).rejects.toThrow(/outside the capture directory/); + expect(readdirSync(outside)).toEqual([]); + }); + }, + ); + + posixOnly("refuses a dangling assets/ symlink before its svgs folder", async () => { + await withTempDir(async (root) => { + const outputDir = join(root, "capture"); + const target = join(root, "missing"); + mkdirSync(outputDir); + symlinkSync(target, join(outputDir, "assets")); + + await expect( + downloadAssets( + { svgs: [], sections: [], ogImage: "" } as unknown as DesignTokens, + outputDir, + ), + ).rejects.toThrow(CaptureDirRefusedError); + expect(existsSync(target)).toBe(false); + }); + }); + + posixOnly("refuses to create the fonts directory through a planted assets/ symlink", async () => { + await withTempDir(async (root) => { + const { outputDir, outside } = plantedLink(root, "assets"); + + await expect(downloadAndRewriteFonts("", outputDir)).rejects.toThrow( + /outside the capture directory/, + ); + expect(readdirSync(outside)).toEqual([]); + }); + }); +}); diff --git a/packages/cli/src/capture/assetDownloader.ts b/packages/cli/src/capture/assetDownloader.ts index c0d8d9bd5b..3dbf6188a1 100644 --- a/packages/cli/src/capture/assetDownloader.ts +++ b/packages/cli/src/capture/assetDownloader.ts @@ -6,8 +6,7 @@ */ import { isBlockedNetworkHost } from "@hyperframes/engine"; -import { mkdirSync } from "node:fs"; -import { writeCaptureFileSync } from "./captureFile.js"; +import { ensureCaptureDirSync, writeCaptureFileSync } from "./captureFile.js"; import { join, extname } from "node:path"; import { createHash } from "node:crypto"; import type { DesignTokens, DownloadedAsset } from "./types.js"; @@ -317,14 +316,14 @@ export async function downloadAssets( ): Promise<{ assets: DownloadedAsset[]; drops: AssetDropCounts; icons: IconManifest }> { options = { ...options, byteBudget: options.byteBudget ?? createCaptureDownloadBudget() }; const assetsDir = join(outputDir, "assets"); - mkdirSync(assetsDir, { recursive: true }); + ensureCaptureDirSync(outputDir, assetsDir); const assets: DownloadedAsset[] = []; const drops = noDrops(); const downloadedUrls = new Set(); let icons: IconManifest = emptyIconManifest(); - mkdirSync(join(outputDir, "assets", "svgs"), { recursive: true }); + ensureCaptureDirSync(outputDir, join(outputDir, "assets", "svgs")); const usedSvgNames = new Set(); const MAX_INLINE_SVGS = 30; drops["cap-reached"] += Math.max(0, tokens.svgs.length - MAX_INLINE_SVGS); @@ -542,7 +541,7 @@ export async function downloadAndRewriteFonts( ): Promise<{ css: string; drops: AssetDropCounts }> { options = { ...options, byteBudget: options.byteBudget ?? createCaptureDownloadBudget() }; const assetsDir = join(outputDir, "assets", "fonts"); - mkdirSync(assetsDir, { recursive: true }); + ensureCaptureDirSync(outputDir, assetsDir); const drops = noDrops(); const fontUrlRegex = /url\(['"]?(https?:\/\/[^'")\s]+\.(?:woff2?|ttf|otf)[^'")\s]*?)['"]?\)/g; diff --git a/packages/cli/src/capture/captureAttempt.test.ts b/packages/cli/src/capture/captureAttempt.test.ts new file mode 100644 index 0000000000..c78ca995bc --- /dev/null +++ b/packages/cli/src/capture/captureAttempt.test.ts @@ -0,0 +1,47 @@ +import { mkdirSync, mkdtempSync, readdirSync, rmSync, symlinkSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it, onTestFinished, vi } from "vitest"; +import { captureWebsiteAttempt } from "./captureAttempt.js"; +import { CaptureDirRefusedError } from "./captureErrors.js"; +import type { CaptureWatchdog } from "./captureWatchdog.js"; +import { createPartialCaptureState } from "./partialCapture.js"; + +const { ensureBrowserMock } = vi.hoisted(() => ({ + ensureBrowserMock: vi.fn(async () => { + throw new Error("the browser must not start"); + }), +})); +vi.mock("../browser/manager.js", () => ({ ensureBrowser: ensureBrowserMock })); + +const watchdog: CaptureWatchdog = { + expired: () => false, + promise: new Promise(() => {}), + registerBrowser: () => {}, + unregisterBrowser: () => {}, + dispose: () => {}, +}; + +describe("captureWebsiteAttempt output folders", () => { + // Creating symlinks needs elevated rights on Windows. + it.skipIf(process.platform === "win32").each(["extracted", "screenshots", "assets"])( + "refuses a planted %s/ symlink before the browser starts (#4304)", + async (link) => { + const root = mkdtempSync(join(tmpdir(), "hf-capture-attempt-")); + onTestFinished(() => rmSync(root, { recursive: true, force: true })); + const outputDir = join(root, "capture"); + const outside = join(root, "outside"); + mkdirSync(outputDir); + mkdirSync(outside); + symlinkSync(outside, join(outputDir, link)); + const opts = { url: "https://example.com", outputDir }; + + await expect( + captureWebsiteAttempt(opts, undefined, false, watchdog, createPartialCaptureState(opts)), + ).rejects.toThrow(CaptureDirRefusedError); + + expect(readdirSync(outside)).toEqual([]); + expect(ensureBrowserMock).not.toHaveBeenCalled(); + }, + ); +}); diff --git a/packages/cli/src/capture/captureAttempt.ts b/packages/cli/src/capture/captureAttempt.ts index 9c333c5d2f..9303d642cb 100644 --- a/packages/cli/src/capture/captureAttempt.ts +++ b/packages/cli/src/capture/captureAttempt.ts @@ -5,9 +5,10 @@ import { createCaptureDownloadBudget } from "./readBoundedResponse.js"; * - Rich animation metadata for Claude Code to recreate */ -import { mkdirSync, existsSync } from "node:fs"; +import { existsSync } from "node:fs"; import { join } from "node:path"; import { noDrops } from "./assetDownloader.js"; +import { ensureCaptureDirSync } from "./captureFile.js"; import type { IconCandidate } from "./faviconRanker.js"; import { CAPTURE_USER_AGENT } from "./userAgent.js"; import { setupAnimationCapture, startCdpAnimationCapture } from "./animationCataloger.js"; @@ -101,9 +102,9 @@ export async function captureWebsiteAttempt( loadEnvFile(outputDir); // Create output directories - mkdirSync(join(outputDir, "extracted"), { recursive: true }); - mkdirSync(join(outputDir, "screenshots"), { recursive: true }); - mkdirSync(join(outputDir, "assets"), { recursive: true }); + ensureCaptureDirSync(outputDir, join(outputDir, "extracted")); + ensureCaptureDirSync(outputDir, join(outputDir, "screenshots")); + ensureCaptureDirSync(outputDir, join(outputDir, "assets")); // Launch browser progress("browser", "Launching headless Chrome..."); diff --git a/packages/cli/src/capture/captureCompositionFrame.test.ts b/packages/cli/src/capture/captureCompositionFrame.test.ts index 1fd125fbcc..7c3c0699cb 100644 --- a/packages/cli/src/capture/captureCompositionFrame.test.ts +++ b/packages/cli/src/capture/captureCompositionFrame.test.ts @@ -56,7 +56,7 @@ describe("seekCompositionTimeline", () => { expect(waitForFunction).not.toHaveBeenCalled(); expect(evaluate).toHaveBeenCalledTimes(4); - expect(evaluate).toHaveBeenNthCalledWith(1, expect.any(Function), 1.25, false); + expect(evaluate).toHaveBeenNthCalledWith(1, expect.any(Function), 1.25, false, false); expect(evaluate).toHaveBeenNthCalledWith(2, expect.any(Function)); expect(evaluate.mock.calls[2]?.[0]).toContain("window.setTimeout(finish, 100)"); // Post-seek font settle: a seek can reveal glyphs whose unicode-range @@ -93,6 +93,17 @@ describe("seekCompositionTimeline", () => { expect(timelineSeek).not.toHaveBeenCalled(); }); + it("asks renderSeek for the exact instant when exactTime is set", async () => { + const { page, evaluate } = fakeSeekPage(); + const renderSeek = vi.fn(); + vi.stubGlobal("window", { __player: { renderSeek } }); + + await seekCompositionTimeline(page, 19.019018, { exactTime: true }); + runBrowserSeek(evaluate); + + expect(renderSeek).toHaveBeenCalledWith(19.019018, { exact: true }); + }); + function fakeBridgeOnlySeekPage() { const { page, evaluate } = fakeSeekPage(); const bridgeSeek = vi.fn(); @@ -150,7 +161,7 @@ describe("seekCompositionTimeline", () => { expect(waitForFunction).toHaveBeenCalledWith(expect.any(Function), { timeout: 500 }); expect(evaluate).toHaveBeenCalledTimes(2); - expect(evaluate).toHaveBeenCalledWith(expect.any(Function), 3, true); + expect(evaluate).toHaveBeenCalledWith(expect.any(Function), 3, true, false); }); it("supports layout's ordered double-frame, bounded font, and sleep settles", async () => { @@ -167,7 +178,7 @@ describe("seekCompositionTimeline", () => { await pending; expect(evaluate).toHaveBeenCalledTimes(4); - expect(evaluate).toHaveBeenNthCalledWith(1, expect.any(Function), 4, true); + expect(evaluate).toHaveBeenNthCalledWith(1, expect.any(Function), 4, true, false); expect(evaluate).toHaveBeenNthCalledWith(2, expect.any(Function)); expect(evaluate).toHaveBeenNthCalledWith(3, expect.any(Function)); expect(evaluate).toHaveBeenNthCalledWith(4, expect.any(Function), 500); diff --git a/packages/cli/src/capture/captureCompositionFrame.ts b/packages/cli/src/capture/captureCompositionFrame.ts index df0b49b4eb..4b0aa39211 100644 --- a/packages/cli/src/capture/captureCompositionFrame.ts +++ b/packages/cli/src/capture/captureCompositionFrame.ts @@ -37,6 +37,7 @@ export const DENSE_GEOMETRY_SEEK_OPTIONS = { export interface SeekCompositionTimelineOptions { fallbackToBridgeAndTimelines?: boolean; + exactTime?: boolean; waitForPreferredSeekTargetMs?: number; animationFrameSettle?: "race" | "double" | "none"; waitForFontsMs?: number; @@ -47,13 +48,14 @@ type CompositionPageFunction = | string | (() => unknown) | ((value: number) => unknown) - | ((value: number, fallbackToBridgeAndTimelines: boolean) => unknown); + | ((value: number, fallbackToBridgeAndTimelines: boolean, exactTime: boolean) => unknown); export interface CompositionEvaluationPage { evaluate( pageFunction: CompositionPageFunction, value?: number, fallbackToBridgeAndTimelines?: boolean, + exactTime?: boolean, ): Promise; } @@ -247,7 +249,7 @@ export async function seekCompositionTimeline( await page.evaluate( // Serialized into the page; the seek-target cascade must stay one function. // fallow-ignore-next-line complexity - (t: number, fallbackToBridgeAndTimelines: boolean) => { + (t: number, fallbackToBridgeAndTimelines: boolean, exactTime: boolean) => { const getProperty = (target: unknown, key: string): unknown => { if ((typeof target !== "object" || target === null) && typeof target !== "function") { return undefined; @@ -271,7 +273,7 @@ export async function seekCompositionTimeline( // Prefer renderSeek because it also runs the runtime's data-start/data-duration // visibility sync; raw timeline seeks leave off-window clips visible to audits. - if (call(renderSeek, player, [safe])) { + if (call(renderSeek, player, exactTime ? [safe, { exact: true }] : [safe])) { // Preferred runtime target handled the seek. } else if (fallbackToBridgeAndTimelines && call(bridgeSeek, hf, [safe])) { // Producer bridge handled the seek. @@ -294,6 +296,7 @@ export async function seekCompositionTimeline( }, timeSeconds, options.fallbackToBridgeAndTimelines === true, + options.exactTime === true, ); await page.evaluate(async () => { diff --git a/packages/cli/src/capture/captureErrors.ts b/packages/cli/src/capture/captureErrors.ts index e8a051bc54..e3733d2a45 100644 --- a/packages/cli/src/capture/captureErrors.ts +++ b/packages/cli/src/capture/captureErrors.ts @@ -7,3 +7,10 @@ export class NavigationDeadlineError extends Error { this.name = "NavigationDeadlineError"; } } + +export class CaptureDirRefusedError extends Error { + constructor(message: string) { + super(message); + this.name = "CaptureDirRefusedError"; + } +} diff --git a/packages/cli/src/capture/captureFile.test.ts b/packages/cli/src/capture/captureFile.test.ts index fb83b61763..60b70cadb3 100644 --- a/packages/cli/src/capture/captureFile.test.ts +++ b/packages/cli/src/capture/captureFile.test.ts @@ -12,7 +12,7 @@ import { import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; -import { writeCaptureFileSync } from "./captureFile.js"; +import { ensureCaptureDirSync, writeCaptureFileSync } from "./captureFile.js"; const temporaryDirectories: string[] = []; @@ -122,3 +122,76 @@ describe("writeCaptureFileSync", () => { expect(readdirSync(outputDir).sort()).toEqual(["a.txt", "occupied"]); }); }); + +describe("ensureCaptureDirSync", () => { + it("creates nested directories under the root, and accepts them again on a re-run", () => { + const { outputDir } = scratch(); + const fonts = join(outputDir, "assets", "fonts"); + + expect(ensureCaptureDirSync(outputDir, fonts)).toBe(fonts); + expect(ensureCaptureDirSync(outputDir, fonts)).toBe(fonts); + + expect(lstatSync(fonts).isDirectory()).toBe(true); + }); + + posixOnly("refuses a planted directory symlink and creates nothing in its target", () => { + const { outputDir } = scratch(); + const outside = join(outputDir, "..", "outside"); + mkdirSync(outside); + symlinkSync(outside, join(outputDir, "assets")); + + expect(() => ensureCaptureDirSync(outputDir, join(outputDir, "assets", "fonts"))).toThrow( + /outside the capture directory/, + ); + expect(readdirSync(outside)).toEqual([]); + }); + + posixOnly("refuses a directory symlink even when it points elsewhere inside the root", () => { + const { outputDir } = scratch(); + mkdirSync(join(outputDir, "extracted")); + symlinkSync(join(outputDir, "extracted"), join(outputDir, "assets")); + + expect(() => ensureCaptureDirSync(outputDir, join(outputDir, "assets"))).toThrow( + /outside the capture directory/, + ); + }); + + posixOnly("refuses a dangling or looping directory symlink with the same message", () => { + const { outputDir } = scratch(); + symlinkSync(join(outputDir, "..", "missing"), join(outputDir, "assets")); + symlinkSync(join(outputDir, "screenshots"), join(outputDir, "screenshots")); + + for (const name of ["assets", "screenshots"]) { + expect(() => ensureCaptureDirSync(outputDir, join(outputDir, name))).toThrow( + /outside the capture directory/, + ); + } + }); + + posixOnly("trusts a root that is itself a symlink, as /tmp is on macOS", () => { + const { outputDir } = scratch(); + const linkedRoot = join(outputDir, "..", "linked-capture"); + symlinkSync(outputDir, linkedRoot); + + ensureCaptureDirSync(linkedRoot, join(linkedRoot, "assets", "svgs")); + + expect(lstatSync(join(outputDir, "assets", "svgs")).isDirectory()).toBe(true); + }); + + it("refuses a file sitting where a directory belongs", () => { + const { outputDir } = scratch(); + writeFileSync(join(outputDir, "assets"), "not a directory"); + + expect(() => ensureCaptureDirSync(outputDir, join(outputDir, "assets"))).toThrow( + /not a directory/, + ); + }); + + it("refuses a directory that is not under the root", () => { + const { outputDir } = scratch(); + + expect(() => ensureCaptureDirSync(outputDir, join(outputDir, "..", "elsewhere"))).toThrow( + /outside the capture directory/, + ); + }); +}); diff --git a/packages/cli/src/capture/captureFile.ts b/packages/cli/src/capture/captureFile.ts index a1128d53ce..a483e107ef 100644 --- a/packages/cli/src/capture/captureFile.ts +++ b/packages/cli/src/capture/captureFile.ts @@ -1,5 +1,14 @@ -import { mkdtempSync, renameSync, rmSync, writeFileSync } from "node:fs"; -import { basename, dirname, join } from "node:path"; +import { + mkdirSync, + mkdtempSync, + realpathSync, + renameSync, + rmSync, + statSync, + writeFileSync, +} from "node:fs"; +import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; +import { CaptureDirRefusedError } from "./captureErrors.js"; type WriteOptions = Parameters[2]; @@ -40,3 +49,59 @@ export function writeCaptureFileSync( } writeFileSync(path, data, { ...normalized, mode: 0o600 }); } + +function hasCode(error: unknown, ...codes: string[]): boolean { + return ( + error instanceof Error && + "code" in error && + typeof error.code === "string" && + codes.includes(error.code) + ); +} + +// The JS `realpathSync`, deliberately not `realpathSync.native`: native returns the on-disk case +// on macOS/Windows, so an existing `Assets/` asked for as `assets` would be falsely refused. The +// JS walk only rewrites the components that are links, which is exactly what is being checked. +function resolvedPath(path: string): string | undefined { + try { + return realpathSync(path); + } catch (error) { + // A dangling or looping link resolves nowhere: refuse it like any other escaping link. + if (hasCode(error, "ENOENT", "ELOOP")) return undefined; + throw error; + } +} + +// Creates `dir` under the trusted capture root, refusing any directory whose real path leaves it (#4304). +// Checked on creation, not on every write: a link swapped in later by a racing process is out of scope. +export function ensureCaptureDirSync(root: string, dir: string): string { + const rootPath = resolve(root); + const target = resolve(dir); + const rel = relative(rootPath, target); + if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) { + throw new CaptureDirRefusedError( + `Refusing to create ${target}: it is outside the capture directory ${rootPath}`, + ); + } + mkdirSync(rootPath, { recursive: true }); + let current = rootPath; + let expected = realpathSync(rootPath); + for (const segment of rel.split(sep).filter(Boolean)) { + current = join(current, segment); + expected = join(expected, segment); + try { + mkdirSync(current); + } catch (error) { + if (!hasCode(error, "EEXIST")) throw error; + } + if (resolvedPath(current) !== expected) { + throw new CaptureDirRefusedError( + `Refusing to write into ${current}: it resolves outside the capture directory ${rootPath}`, + ); + } + if (!statSync(current).isDirectory()) { + throw new CaptureDirRefusedError(`Refusing to write into ${current}: it is not a directory`); + } + } + return target; +} diff --git a/packages/cli/src/capture/coreExtractionPhase.ts b/packages/cli/src/capture/coreExtractionPhase.ts index d64ef31014..717923ff33 100644 --- a/packages/cli/src/capture/coreExtractionPhase.ts +++ b/packages/cli/src/capture/coreExtractionPhase.ts @@ -9,8 +9,8 @@ import type { IconCandidate } from "./faviconRanker.js"; import { startCdpAnimationCapture } from "./animationCataloger.js"; import { createCaptureDownloadBudget } from "./readBoundedResponse.js"; import { detectLibraries } from "./contentExtractor.js"; -import { mkdirSync } from "node:fs"; import { writeCaptureFileSync } from "./captureFile.js"; +import { CaptureDirRefusedError } from "./captureErrors.js"; import { join } from "node:path"; import { extractHtml } from "./htmlExtractor.js"; import { extractTokens } from "./tokenExtractor.js"; @@ -176,9 +176,13 @@ export async function runCoreExtraction(input: CoreExtractionInput): Promise 0 && remainingMs() > 0) { const lottieDir = join(outputDir, "assets", "lottie"); if (!canWrite()) return; - mkdirSync(lottieDir, { recursive: true }); const lottieBudget = { remainingMs, byteBudget: downloadByteBudget }; - const savedCount = await saveLottieAnimations(discoveredLotties, lottieDir, lottieBudget); + const savedCount = await saveLottieAnimations( + discoveredLotties, + lottieDir, + outputDir, + lottieBudget, + ); // Generate manifest + preview thumbnails so the agent can SEE what each animation is if (savedCount > 0 && remainingMs() > 0 && canWrite()) { await renderLottiePreviews(chromeBrowser, lottieDir, outputDir, lottieBudget); @@ -348,8 +352,10 @@ export async function runCoreExtraction(input: CoreExtractionInput): Promise { const saved = await saveLottieAnimations( [{ url: "https://one.example/a.json" }, { url: "https://two.example/b.json" }], dir, + dir, { remainingMs: () => remainingMs }, ); @@ -207,7 +209,9 @@ describe("Lottie capture rejects unsafe persistence", () => { "fetch", vi.fn(async () => new Response("not a zip")), ); - expect(await saveLottieAnimations([{ url: "https://public.example/bad.lottie" }], dir)).toBe(0); + expect( + await saveLottieAnimations([{ url: "https://public.example/bad.lottie" }], dir, dir), + ).toBe(0); expect(readdirSync(dir)).toEqual([]); }); it("does not publish truthy non-array layers", async () => { @@ -216,7 +220,9 @@ describe("Lottie capture rejects unsafe persistence", () => { "fetch", vi.fn(async () => new Response('{"w":100,"h":100,"layers":true}')), ); - expect(await saveLottieAnimations([{ url: "https://public.example/bad.json" }], dir)).toBe(0); + expect(await saveLottieAnimations([{ url: "https://public.example/bad.json" }], dir, dir)).toBe( + 0, + ); expect(readdirSync(dir)).toEqual([]); }); }); @@ -299,3 +305,90 @@ describe("media previews replace pre-planted links", () => { }, ); }); + +describe("media folders refuse a planted directory link (#4304)", () => { + // captureVideoManifest keeps any http(s) video it finds; only the URL matters here. + const descriptor = { src: "https://video.example/planted.mp4", filename: "planted.mp4" }; + + function plantedCapture(link: string): { dir: string; outside: string } { + const dir = tempDir(); + const outside = join(dir, "outside"); + mkdirSync(outside); + mkdirSync(join(dir, "extracted")); + mkdirSync(join(dir, link, ".."), { recursive: true }); + symlinkSync(outside, join(dir, link)); + return { dir, outside }; + } + + // Creating symlinks needs elevated rights on Windows. + it.skipIf(process.platform === "win32").each(["assets/videos", "assets/videos/previews"])( + "does not write the video manifest through a planted %s link", + async (link) => { + const { dir, outside } = plantedCapture(link); + const screenshot = vi.fn(); + const page = { evaluate: vi.fn(async () => [descriptor]), screenshot } as unknown as Page; + vi.stubGlobal( + "fetch", + vi.fn(async () => new Response(null, { status: 404 })), + ); + + await expect(captureVideoManifest(page, dir, () => {})).rejects.toThrow( + CaptureDirRefusedError, + ); + expect(readdirSync(outside)).toEqual([]); + expect(screenshot).not.toHaveBeenCalled(); + }, + ); + + it.skipIf(process.platform === "win32")( + "refuses a dangling assets/videos link before its previews folder", + async () => { + const dir = tempDir(); + const target = join(dir, "missing"); + mkdirSync(join(dir, "assets"), { recursive: true }); + symlinkSync(target, join(dir, "assets", "videos")); + const page = { + evaluate: vi.fn(async () => [descriptor]), + screenshot: vi.fn(), + } as unknown as Page; + + await expect(captureVideoManifest(page, dir, () => {})).rejects.toThrow( + CaptureDirRefusedError, + ); + expect(existsSync(target)).toBe(false); + }, + ); + + it.skipIf(process.platform === "win32")( + "does not save Lottie files through a planted assets/lottie link", + async () => { + const { dir, outside } = plantedCapture("assets/lottie"); + const fetchMock = vi.fn(); + vi.stubGlobal("fetch", fetchMock); + + await expect( + saveLottieAnimations( + [{ url: "https://public.example/a.json" }], + join(dir, "assets", "lottie"), + dir, + ), + ).rejects.toThrow(CaptureDirRefusedError); + expect(readdirSync(outside)).toEqual([]); + expect(fetchMock).not.toHaveBeenCalled(); + }, + ); + + it.skipIf(process.platform === "win32")( + "does not render Lottie previews through a planted previews link", + async () => { + const { dir, outside } = plantedCapture("assets/lottie/previews"); + const browser = { newPage: vi.fn() } as unknown as Browser; + + await expect( + renderLottiePreviews(browser, join(dir, "assets", "lottie"), dir), + ).rejects.toThrow(CaptureDirRefusedError); + expect(readdirSync(outside)).toEqual([]); + expect(browser.newPage).not.toHaveBeenCalled(); + }, + ); +}); diff --git a/packages/cli/src/capture/mediaCapture.ts b/packages/cli/src/capture/mediaCapture.ts index bf178b86df..4005962cb5 100644 --- a/packages/cli/src/capture/mediaCapture.ts +++ b/packages/cli/src/capture/mediaCapture.ts @@ -8,8 +8,8 @@ */ import type { Browser, Page } from "puppeteer-core"; -import { mkdirSync, readdirSync, readFileSync, statSync } from "node:fs"; -import { writeCaptureFileSync } from "./captureFile.js"; +import { readdirSync, readFileSync, statSync } from "node:fs"; +import { ensureCaptureDirSync, writeCaptureFileSync } from "./captureFile.js"; import { join, extname } from "node:path"; import { isPrivateUrl, safeFetch } from "./assetDownloader.js"; import { CAPTURE_USER_AGENT } from "./userAgent.js"; @@ -50,8 +50,10 @@ function liveRemainingMs(budget: RemainingBudget, fallbackMs: number): number { export async function saveLottieAnimations( discoveredLotties: DiscoveredLottie[], lottieDir: string, + outputDir: string, budget: RemainingBudget = {}, ): Promise { + ensureCaptureDirSync(outputDir, lottieDir); const byteBudget = budget.byteBudget ?? createCaptureDownloadBudget(); let savedCount = 0; const savedHashes = new Set(); // Deduplicate by content @@ -130,7 +132,7 @@ export async function renderLottiePreviews( layers: number; }> = []; const previewDir = join(lottieDir, "previews"); - mkdirSync(previewDir, { recursive: true }); + ensureCaptureDirSync(outputDir, previewDir); for (const file of readdirSync(lottieDir)) { if (!file.endsWith(".json")) continue; @@ -470,9 +472,9 @@ export async function captureVideoManifest( if (merged.length === 0) return; const videoManifestDir = join(outputDir, "assets", "videos"); - mkdirSync(videoManifestDir, { recursive: true }); + ensureCaptureDirSync(outputDir, videoManifestDir); const previewDir = join(videoManifestDir, "previews"); - mkdirSync(previewDir, { recursive: true }); + ensureCaptureDirSync(outputDir, previewDir); const videoManifest: Array<{ index: number; diff --git a/packages/cli/src/capture/partialCapture.test.ts b/packages/cli/src/capture/partialCapture.test.ts index 17392b228f..d23ea384fd 100644 --- a/packages/cli/src/capture/partialCapture.test.ts +++ b/packages/cli/src/capture/partialCapture.test.ts @@ -1,4 +1,12 @@ -import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + symlinkSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; @@ -45,4 +53,30 @@ describe("writePartialCaptureBundle", () => { partial: true, }); }); + + // Creating symlinks needs elevated rights on Windows. + it.skipIf(process.platform === "win32")( + "refuses to write through a planted extracted/ symlink (#4304)", + () => { + const root = mkdtempSync(join(tmpdir(), "hyperframes-partial-capture-")); + temporaryDirectories.push(root); + const outputDir = join(root, "capture"); + const outside = join(root, "outside"); + mkdirSync(outputDir); + mkdirSync(outside); + symlinkSync(outside, join(outputDir, "extracted")); + const opts = { url: "https://example.com", outputDir }; + + expect(() => + writePartialCaptureBundle(opts, createPartialCaptureState(opts), { + schema: CAPTURE_PHASE_SCHEMA, + phase: "complete", + status: "degraded", + remainingMs: null, + reason: "deadline", + }), + ).toThrow(/outside the capture directory/); + expect(readdirSync(outside)).toEqual([]); + }, + ); }); diff --git a/packages/cli/src/capture/partialCapture.ts b/packages/cli/src/capture/partialCapture.ts index 08156e610a..63239d5abc 100644 --- a/packages/cli/src/capture/partialCapture.ts +++ b/packages/cli/src/capture/partialCapture.ts @@ -1,5 +1,4 @@ -import { mkdirSync } from "node:fs"; -import { writeCaptureFileSync } from "./captureFile.js"; +import { ensureCaptureDirSync, writeCaptureFileSync } from "./captureFile.js"; import { join } from "node:path"; import { noDrops } from "./assetDownloader.js"; import type { @@ -74,9 +73,7 @@ export function writePartialCaptureBundle( lastPhase: CaptureResult["lastPhase"], ): CaptureResult { const hostname = new URL(opts.url).hostname.replace(/^www\./, ""); - mkdirSync(opts.outputDir, { recursive: true }); - const extractedDir = join(opts.outputDir, "extracted"); - mkdirSync(extractedDir, { recursive: true }); + const extractedDir = ensureCaptureDirSync(opts.outputDir, join(opts.outputDir, "extracted")); writeCaptureFileSync(join(extractedDir, "tokens.json"), serializeTokensForCapture(state.tokens)); writeCaptureFileSync( join(extractedDir, "design-styles.json"), diff --git a/packages/cli/src/capture/postExtractionPhase.test.ts b/packages/cli/src/capture/postExtractionPhase.test.ts new file mode 100644 index 0000000000..454ebe1dac --- /dev/null +++ b/packages/cli/src/capture/postExtractionPhase.test.ts @@ -0,0 +1,58 @@ +import { mkdirSync, mkdtempSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it, onTestFinished } from "vitest"; +import { noDrops } from "./assetDownloader.js"; +import { createPartialCaptureState } from "./partialCapture.js"; +import { runPostExtraction } from "./postExtractionPhase.js"; +import { createCaptureDownloadBudget } from "./readBoundedResponse.js"; + +const PLANTED_SVG = ``; + +describe("runPostExtraction", () => { + // Creating symlinks needs elevated rights on Windows. + it.skipIf(process.platform === "win32")( + "does not write the SVG contact sheet through a planted assets/svgs symlink under --skip-assets (#4304)", + async () => { + const root = mkdtempSync(join(tmpdir(), "hyperframes-post-extraction-")); + onTestFinished(() => rmSync(root, { recursive: true, force: true })); + const outputDir = join(root, "capture"); + const outside = join(root, "outside"); + for (const dir of ["extracted", "screenshots", "assets"]) { + mkdirSync(join(outputDir, dir), { recursive: true }); + } + mkdirSync(outside); + writeFileSync(join(outside, "planted.svg"), PLANTED_SVG); + symlinkSync(outside, join(outputDir, "assets", "svgs")); + + const state = createPartialCaptureState({ url: "https://example.com", outputDir }); + const warnings: string[] = []; + await runPostExtraction({ + state, + outputDir, + warnings, + progress: () => {}, + remainingMs: () => 60_000, + phase: () => {}, + animationCatalog: undefined, + catalogedAssets: [], + visibleTextContent: "", + faviconLinks: [], + tokens: state.tokens, + extracted: state.extracted, + skipAssets: true, + skipVision: true, + downloadByteBudget: createCaptureDownloadBudget(), + assets: [], + dropped: noDrops(), + fontDrops: noDrops(), + canWrite: () => true, + }); + + expect(readdirSync(outside)).toEqual(["planted.svg"]); + expect(warnings).toEqual([ + expect.stringMatching(/^SVG contact sheet skipped: Refusing to write/), + ]); + }, + ); +}); diff --git a/packages/cli/src/capture/postExtractionPhase.ts b/packages/cli/src/capture/postExtractionPhase.ts index 1163e1f18d..8733462c53 100644 --- a/packages/cli/src/capture/postExtractionPhase.ts +++ b/packages/cli/src/capture/postExtractionPhase.ts @@ -1,5 +1,6 @@ import { existsSync } from "node:fs"; -import { writeCaptureFileSync } from "./captureFile.js"; +import { ensureCaptureDirSync, writeCaptureFileSync } from "./captureFile.js"; +import { CaptureDirRefusedError } from "./captureErrors.js"; import { join } from "node:path"; import { downloadAssets, @@ -404,7 +405,9 @@ export async function runPostExtraction(input: PostExtractionInput): Promise { + // Creating symlinks needs elevated rights on Windows. + it.skipIf(process.platform === "win32")( + "refuses a planted screenshots/ symlink before touching the page", + async () => { + const dir = tempDir("hf-scroll-planted-"); + const outside = join(dir, "outside"); + mkdirSync(outside); + symlinkSync(outside, join(dir, "screenshots")); + const { page, evaluate, screenshot } = fakePage(); + + await expect(captureScrollScreenshots(page, dir)).rejects.toThrow(CaptureDirRefusedError); + + expect(readdirSync(outside)).toEqual([]); + expect(evaluate).not.toHaveBeenCalled(); + expect(screenshot).not.toHaveBeenCalled(); + }, + ); +}); diff --git a/packages/cli/src/capture/screenshotCapture.ts b/packages/cli/src/capture/screenshotCapture.ts index 57b36c00f1..bdde074316 100644 --- a/packages/cli/src/capture/screenshotCapture.ts +++ b/packages/cli/src/capture/screenshotCapture.ts @@ -7,9 +7,8 @@ import type { Page } from "puppeteer-core"; import { isDegradableEvaluateTimeoutError } from "./captureTimeout.js"; -import { mkdirSync } from "node:fs"; import { join } from "node:path"; -import { writeCaptureFileSync } from "./captureFile.js"; +import { ensureCaptureDirSync, writeCaptureFileSync } from "./captureFile.js"; /** * Capture viewport screenshots covering the entire page height. @@ -118,7 +117,7 @@ export async function captureScrollScreenshots( budget: { remainingMs?: () => number } = {}, ): Promise { const screenshotsDir = join(outputDir, "screenshots"); - mkdirSync(screenshotsDir, { recursive: true }); + ensureCaptureDirSync(outputDir, screenshotsDir); const MAX_SCREENSHOTS = 20; const filePaths: string[] = []; diff --git a/packages/cli/src/cli.commands.test.ts b/packages/cli/src/cli.commands.test.ts index dc45671e04..db63f8f09b 100644 --- a/packages/cli/src/cli.commands.test.ts +++ b/packages/cli/src/cli.commands.test.ts @@ -2,6 +2,11 @@ import { readFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { describe, expect, it } from "vitest"; +import type { CommandDef } from "citty"; +import { + ACCEPTS_EXTRA_POSITIONALS, + JOINS_EXTRA_POSITIONALS, +} from "./utils/reject-extra-positionals.js"; const cliSource = readFileSync(join(dirname(fileURLToPath(import.meta.url)), "cli.ts"), "utf8"); const helpSource = readFileSync(join(dirname(fileURLToPath(import.meta.url)), "help.ts"), "utf8"); @@ -12,7 +17,32 @@ function commandLoaderBlock(): string { return match![1]!; } +// Vite cannot resolve a template-string import, so each listed top-level command is named here. +const LIST_COMMANDS: Record Promise<{ default: unknown }>> = { + catalog: () => import("./commands/catalog.js"), + compare: () => import("./commands/compare.js"), + figma: () => import("./commands/figma.js"), + skills: () => import("./commands/skills.js"), + timeline: () => import("./commands/timeline.js"), + tts: () => import("./commands/tts.js"), +}; + describe("CLI command registration", () => { + it.each([...ACCEPTS_EXTRA_POSITIONALS, ...JOINS_EXTRA_POSITIONALS])( + "names a real command in the extra-positional lists: %s", + async (path) => { + const [top, ...subs] = path.split(" "); + expect(commandLoaderBlock()).toMatch(new RegExp(`\\b${top}:\\s*\\(\\)\\s*=>`)); + let cmd = (await LIST_COMMANDS[top!]!()).default as CommandDef; + expect(cmd.meta).toMatchObject({ name: top }); + for (const sub of subs) { + const entry = (cmd.subCommands as Record)[sub!]; + cmd = (typeof entry === "function" ? await entry() : entry) as CommandDef; + expect(cmd, `${path} resolves to a subcommand`).toBeTruthy(); + } + }, + ); + it("registers keyframes as the only keyframe inspection command", () => { const loaders = commandLoaderBlock(); diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index f5f61dbee7..3e255afdac 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -168,6 +168,7 @@ const commandLoaders = { browser: () => import("./commands/browser.js").then((m) => m.default), "remove-background": () => import("./commands/remove-background.js").then((m) => m.default), transcribe: () => import("./commands/transcribe.js").then((m) => m.default), + usage: () => import("./commands/usage.js").then((m) => m.default), models: () => import("./commands/models.js").then((m) => m.default), tts: () => import("./commands/tts.js").then((m) => m.default), docs: () => import("./commands/docs.js").then((m) => m.default), @@ -246,7 +247,13 @@ let telemetryReady: Promise = Promise.resolve(); // `events` is a telemetry-internal beacon: it self-tracks + self-flushes, so it // skips the per-command wrapper (no duplicate cli_command, no first-run notice // printed into a skill's captured output). -if (!isHelp && command !== "telemetry" && command !== "events" && command !== "unknown") { +if ( + !isHelp && + command !== "telemetry" && + command !== "events" && + command !== "usage" && + command !== "unknown" +) { telemetryReady = import("./telemetry/index.js").then((mod) => { _flushSync = mod.flushSync; _trackCliError = mod.trackCliError; @@ -273,7 +280,8 @@ if ( command !== "upgrade" && command !== "events" && command !== "telemetry" && - command !== "skills" + command !== "skills" && + command !== "usage" ) { // Report any completed auto-install from the previous run first, before // kicking off the next check — so the user sees "updated to vX" once and diff --git a/packages/cli/src/commands/add.test.ts b/packages/cli/src/commands/add.test.ts index 8618bd2985..4bbd5a49cf 100644 --- a/packages/cli/src/commands/add.test.ts +++ b/packages/cli/src/commands/add.test.ts @@ -1,11 +1,12 @@ import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; +import { runCommand as runCittyCommand, type CommandDef } from "citty"; import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import type { RegistryItem, RegistryManifest } from "@hyperframes/core"; import { lintHyperframeHtml } from "@hyperframes/lint"; import type { RunAddResult } from "./add.js"; -import { +import addCommand, { AddError, buildSnippet, compositionRootId, @@ -16,6 +17,8 @@ import { tagAddJson, } from "./add.js"; import { trackRegistryItemAdded } from "../telemetry/events.js"; +import { CliUsageError } from "../utils/commandResult.js"; +import { trackCommandFailures } from "../utils/command-failure-tracking.js"; // Assert the emitted payload rather than the transport: `shouldTrack()` is // already false under test (dev mode / no PostHog key), so a real call would @@ -522,6 +525,48 @@ describe("variable values in the snippet", () => { }); }); +describe("add command run() — extra positional arguments", () => { + let dir: string; + let errorSpy: ReturnType; + + beforeEach(() => { + dir = tmp(); + errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); + }); + + afterEach(() => { + errorSpy.mockRestore(); + vi.unstubAllGlobals(); + rmSync(dir, { recursive: true, force: true }); + }); + + async function runWrapped(rawArgs: string[]): Promise { + const cmd = await trackCommandFailures(() => Promise.resolve(addCommand as CommandDef))(); + await runCittyCommand(cmd, { rawArgs }); + } + + it("rejects `add a --dir b c` through the CLI wrapper, before any registry call", async () => { + const fetchSpy = vi.fn(); + vi.stubGlobal("fetch", fetchSpy); + + await expect(runWrapped(["a", "--dir", dir, "b", "c"])).rejects.toThrow(CliUsageError); + expect(fetchSpy).not.toHaveBeenCalled(); + expect(errorSpy.mock.calls.flat().join(" ")).toContain( + "Unexpected extra arguments for hyperframes add: b, c", + ); + expect(errorSpy.mock.calls.flat().join(" ")).toContain("Run add once per item"); + }); + + it("does not fire on a normal single-item invocation", async () => { + mockFetch(); + writeRegistryConfig(dir); + + await expect( + runWrapped(["my-block", "--dir", dir, "--no-clipboard", "--json"]), + ).resolves.toBeUndefined(); + }); +}); + describe("describeInstallFailure", () => { it("explains a bare transport failure instead of echoing it", () => { // What the user actually sees after copying a command off the catalog page. diff --git a/packages/cli/src/commands/add.ts b/packages/cli/src/commands/add.ts index a078eaac8e..43b077d97f 100644 --- a/packages/cli/src/commands/add.ts +++ b/packages/cli/src/commands/add.ts @@ -490,6 +490,7 @@ export default defineCommand({ const projectDir = resolve(args.dir ?? process.cwd()); const json = args.json === true; const skipClipboard = args.clipboard === false; + const hasConfigBefore = existsSync(projectConfigPath(projectDir)); // Try single item first. If it fails, check if the name matches a tag. diff --git a/packages/cli/src/commands/browser.ts b/packages/cli/src/commands/browser.ts index 77915b3da3..47bc922582 100644 --- a/packages/cli/src/commands/browser.ts +++ b/packages/cli/src/commands/browser.ts @@ -93,7 +93,7 @@ async function runEnsure(options?: { force?: boolean }): Promise { return; } - s.start("Purging cached download and re-downloading..."); + s.start("Re-downloading the managed browser..."); const downloadSpinner = clack.spinner(); downloadSpinner.start( diff --git a/packages/cli/src/commands/capture/video.test.ts b/packages/cli/src/commands/capture/video.test.ts index 4cfc0f50f5..a3f7c15444 100644 --- a/packages/cli/src/commands/capture/video.test.ts +++ b/packages/cli/src/commands/capture/video.test.ts @@ -1,9 +1,14 @@ -import { describe, expect, it } from "vitest"; +import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it, onTestFinished, vi } from "vitest"; +import { consumeCommandResult } from "../../utils/commandResult.js"; import { MAX_VIDEO_BYTES, VIDEO_CONTENT_TYPE_RE, findFilenameCollision, pickManifestEntry, + runVideoMode, safeFilename, type ManifestEntry, } from "./video.js"; @@ -160,3 +165,44 @@ describe("findFilenameCollision", () => { expect(collisions.every((c) => c.index !== 0)).toBe(true); }); }); + +describe("runVideoMode", () => { + // Creating symlinks needs elevated rights on Windows. + it.skipIf(process.platform === "win32").each([ + { layout: "capture output", manifestDir: "extracted", planted: "assets" }, + { layout: "W2H project", manifestDir: "capture/extracted", planted: "capture" }, + ])( + "refuses to download through a planted $planted symlink in a $layout (#4304)", + async ({ manifestDir, planted }) => { + const root = mkdtempSync(join(tmpdir(), "hf-video-mode-")); + onTestFinished(() => rmSync(root, { recursive: true, force: true })); + const projectDir = join(root, "project"); + const outside = join(root, "outside"); + mkdirSync(projectDir); + mkdirSync(outside); + symlinkSync(outside, join(projectDir, planted)); + mkdirSync(join(projectDir, manifestDir), { recursive: true }); + writeFileSync( + join(projectDir, manifestDir, "video-manifest.json"), + JSON.stringify([ENTRY(0)]), + ); + const fetchMock = vi.fn(async () => { + throw new Error("no network in tests"); + }); + vi.stubGlobal("fetch", fetchMock); + vi.spyOn(console, "log").mockImplementation(() => {}); + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + onTestFinished(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + }); + + await runVideoMode({ project: projectDir, index: "0" }); + + expect(consumeCommandResult().exitCode).toBe(1); + expect(String(error.mock.calls[0]?.[0])).toContain("resolves outside the capture directory"); + expect(fetchMock).not.toHaveBeenCalled(); + expect(existsSync(join(outside, planted === "assets" ? "videos" : "assets"))).toBe(false); + }, + ); +}); diff --git a/packages/cli/src/commands/capture/video.ts b/packages/cli/src/commands/capture/video.ts index a62d0f27a7..ebb0dcf9c9 100644 --- a/packages/cli/src/commands/capture/video.ts +++ b/packages/cli/src/commands/capture/video.ts @@ -1,8 +1,9 @@ import { setCommandExitCode } from "../../utils/commandResult.js"; -import { createWriteStream, existsSync, mkdirSync, readFileSync, unlinkSync } from "node:fs"; +import { createWriteStream, existsSync, readFileSync, unlinkSync } from "node:fs"; import { resolve, join, basename } from "node:path"; import { c } from "../../ui/colors.js"; import { safeFetch } from "../../capture/assetDownloader.js"; +import { ensureCaptureDirSync } from "../../capture/captureFile.js"; import { CAPTURE_USER_AGENT } from "../../capture/userAgent.js"; const MAX_VIDEO_BYTES = 250 * 1024 * 1024; @@ -254,7 +255,13 @@ export async function runVideoMode(args: VideoModeArgs): Promise { const outDir = isW2hLayout ? join(projectDir, "capture", "assets", "videos") : join(projectDir, "assets", "videos"); - mkdirSync(outDir, { recursive: true }); + try { + ensureCaptureDirSync(projectDir, outDir); + } catch (e) { + console.error(`${c.error("✗")} ${(e as Error).message}`); + setCommandExitCode(1); + return; + } const fname = safeFilename(entry.filename || basename(entry.url)); const outPath = join(outDir, fname); const relPath = isW2hLayout ? `capture/assets/videos/${fname}` : `assets/videos/${fname}`; diff --git a/packages/cli/src/commands/check.test.ts b/packages/cli/src/commands/check.test.ts index 914c05af9e..0038703006 100644 --- a/packages/cli/src/commands/check.test.ts +++ b/packages/cli/src/commands/check.test.ts @@ -949,6 +949,7 @@ function reportWithFindings(overrides: Partial = {}): CheckReport { return { ok: true, strict: false, + browserSkipped: false, lint: { ...emptySection(), filesScanned: 0 }, runtime: emptySection(), layout: { @@ -1047,6 +1048,7 @@ describe("check pipeline", () => { const envelope = JSON.parse(output); expect(envelope).toMatchObject({ ok: true, + browserSkipped: false, lint: { ok: true }, runtime: { ok: true }, layout: { ok: true }, @@ -1057,7 +1059,7 @@ describe("check pipeline", () => { }); }); - it("short-circuits on lint errors without launching a browser", async () => { + it("short-circuits on lint errors without launching a browser, and flags the skipped sections", async () => { const lint = lintWith( "error", "root_missing_composition_id", @@ -1069,6 +1071,42 @@ describe("check pipeline", () => { expect(checkExitCode(report)).toBe(1); expect(report.lint.findings).toHaveLength(1); expect(browser).not.toHaveBeenCalled(); + // The browser sections look clean either way; only browserSkipped tells them apart. + expect(report.browserSkipped).toBe(true); + expect(report.runtime).toMatchObject({ ok: true, errorCount: 0, findings: [] }); + expect(report.layout).toMatchObject({ ok: true, errorCount: 0, findings: [], duration: 0 }); + expect(report.motion).toMatchObject({ ok: true, errorCount: 0, findings: [] }); + expect(report.contrast).toMatchObject({ ok: true, errorCount: 0, findings: [] }); + }); + + it("marks browserSkipped true when the linter itself crashes", async () => { + const { deps } = dependencies(fakeDriver()); + deps.lintProject = vi.fn(async () => { + throw new Error("unreadable index.html"); + }); + const report = await runCheckPipeline(PROJECT, DEFAULT_CHECK_OPTIONS, deps); + + expect(report.ok).toBe(false); + expect(report.browserSkipped).toBe(true); + expect(report.runtime.findings[0]?.code).toBe("check_lint_failure"); + }); + + it("marks browserSkipped false once a browser session actually runs", async () => { + const { report } = await runScenario(fakeDriver()); + expect(report.browserSkipped).toBe(false); + }); + + it("marks browserSkipped true when the browser session throws before producing results", async () => { + const { deps } = dependencies(fakeDriver()); + deps.runBrowserCheck = vi.fn(async () => { + throw new Error("Chrome launch failed"); + }); + const report = await runCheckPipeline(PROJECT, DEFAULT_CHECK_OPTIONS, deps); + + expect(report.ok).toBe(false); + expect(report.browserSkipped).toBe(true); + expect(report.runtime.findings).toHaveLength(1); + expect(report.layout).toMatchObject({ ok: true, errorCount: 0, findings: [] }); }); it("gates AA contrast failures and --no-contrast skips the pass", async () => { diff --git a/packages/cli/src/commands/check.ts b/packages/cli/src/commands/check.ts index f90b494398..787b221c5d 100644 --- a/packages/cli/src/commands/check.ts +++ b/packages/cli/src/commands/check.ts @@ -405,6 +405,12 @@ function nonNegativeNumber(value: unknown, fallback: number): number { function printHumanReport(report: CheckReport): void { printSection("Lint", report.lint); + if (report.browserSkipped) { + console.log(); + console.log( + ` ${c.warn("⚠")} Browser session never ran — layout, motion, and contrast below are empty placeholders, not a clean pass.`, + ); + } printSection("Runtime", report.runtime); printLayoutSection("Layout", report.layout); printSection("Motion", report.motion); diff --git a/packages/cli/src/commands/fixtures/usage-transport.mjs b/packages/cli/src/commands/fixtures/usage-transport.mjs new file mode 100644 index 0000000000..6794492c5f --- /dev/null +++ b/packages/cli/src/commands/fixtures/usage-transport.mjs @@ -0,0 +1,28 @@ +import { appendFileSync, writeFileSync } from "node:fs"; + +const env = process.env; +function checkCredentials(headers) { + if (headers.Authorization !== "Bearer fixture-token") throw new Error("wrong credential"); + if (env.HF_USAGE_HARNESS === "codex" && headers["ChatGPT-Account-Id"] !== "fixture-account") + throw new Error("missing account header"); + if (env.HF_USAGE_HARNESS === "grok" && headers["X-XAI-Token-Auth"] !== "xai-grok-cli") + throw new Error("missing Grok header"); +} + +globalThis.fetch = async (url, options) => { + if (env.HF_USAGE_FORBID_REQUESTS === "true") { + writeFileSync(env.HF_USAGE_REQUESTS, "unexpected"); + throw new Error("unexpected network request"); + } + appendFileSync(env.HF_USAGE_REQUESTS, JSON.stringify(String(url)) + "\n"); + const settings = + env.HF_USAGE_HARNESS === "grok" && + String(url) === "https://cli-chat-proxy.grok.com/v1/settings"; + if (String(url) !== env.HF_USAGE_URL && !settings) throw new Error("unexpected network request"); + checkCredentials(options.headers); + if (settings && env.HF_USAGE_SETTINGS_FAIL === "true") + return new Response("unavailable", { status: 503 }); + return new Response( + settings ? JSON.stringify({ subscription_tier_display: "SuperGrok" }) : env.HF_USAGE_RESPONSE, + ); +}; diff --git a/packages/cli/src/commands/init.transcodeToMp4.windowsHide.test.ts b/packages/cli/src/commands/init.transcodeToMp4.windowsHide.test.ts new file mode 100644 index 0000000000..05c11c3229 --- /dev/null +++ b/packages/cli/src/commands/init.transcodeToMp4.windowsHide.test.ts @@ -0,0 +1,26 @@ +import { EventEmitter } from "node:events"; +import { describe, expect, it, vi } from "vitest"; + +const { spawnMock } = vi.hoisted(() => ({ spawnMock: vi.fn() })); + +vi.mock("node:child_process", () => ({ spawn: spawnMock })); +vi.mock("../browser/ffmpeg.js", () => ({ + findFFmpeg: () => "/fake/bin/ffmpeg", + findFFprobe: () => "/fake/bin/ffprobe", + getFFmpegInstallHint: () => "install ffmpeg", +})); + +import { transcodeToMp4 } from "./init.js"; + +describe("transcodeToMp4 child-process options", () => { + it("hides the ffmpeg console window on Windows", async () => { + const proc = new EventEmitter(); + spawnMock.mockReturnValue(proc); + + const result = transcodeToMp4("/fake/in.webm", "/fake/out.mp4"); + proc.emit("close", 0); + await result; + + expect(spawnMock.mock.calls[0]?.[2]).toEqual(expect.objectContaining({ windowsHide: true })); + }); +}); diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts index 22b82baa7d..9fd043e3bd 100644 --- a/packages/cli/src/commands/init.ts +++ b/packages/cli/src/commands/init.ts @@ -185,7 +185,7 @@ function isWebCompatible(codec: string): boolean { // hasFFmpeg is imported from whisper/manager.ts to avoid duplication -function transcodeToMp4(inputPath: string, outputPath: string): Promise { +export function transcodeToMp4(inputPath: string, outputPath: string): Promise { return new Promise((resolvePromise) => { const ffmpegPath = findFFmpeg(); if (!ffmpegPath) { @@ -210,7 +210,7 @@ function transcodeToMp4(inputPath: string, outputPath: string): Promise "-y", outputPath, ], - { stdio: "pipe" }, + { stdio: "pipe", windowsHide: true }, ); child.on("close", (code) => resolvePromise(code === 0)); diff --git a/packages/cli/src/commands/lambda/repoRoot.test.ts b/packages/cli/src/commands/lambda/repoRoot.test.ts new file mode 100644 index 0000000000..9642c69b89 --- /dev/null +++ b/packages/cli/src/commands/lambda/repoRoot.test.ts @@ -0,0 +1,34 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { repoRoot } from "./repoRoot.js"; + +describe("repoRoot", () => { + const dirs: string[] = []; + const tempDir = () => { + const dir = mkdtempSync(join(tmpdir(), "hf-repo-root-")); + dirs.push(dir); + return dir; + }; + + afterEach(() => { + vi.unstubAllEnvs(); + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); + }); + + it("returns HYPERFRAMES_REPO_ROOT when it is a hyperframes checkout", () => { + const root = tempDir(); + mkdirSync(join(root, "packages", "aws-lambda"), { recursive: true }); + writeFileSync(join(root, "packages", "aws-lambda", "package.json"), "{}"); + vi.stubEnv("HYPERFRAMES_REPO_ROOT", root); + expect(repoRoot()).toBe(root); + }); + + it("throws on a HYPERFRAMES_REPO_ROOT that is not a checkout instead of ignoring it", () => { + const root = tempDir(); + vi.stubEnv("HYPERFRAMES_REPO_ROOT", root); + expect(() => repoRoot()).toThrow("HYPERFRAMES_REPO_ROOT is not a hyperframes checkout"); + expect(() => repoRoot()).not.toThrow(root); + }); +}); diff --git a/packages/cli/src/commands/lambda/repoRoot.ts b/packages/cli/src/commands/lambda/repoRoot.ts index b7f6628db0..93268b31d2 100644 --- a/packages/cli/src/commands/lambda/repoRoot.ts +++ b/packages/cli/src/commands/lambda/repoRoot.ts @@ -14,8 +14,12 @@ import { fileURLToPath } from "node:url"; export function repoRoot(): string { const override = process.env.HYPERFRAMES_REPO_ROOT; - if (override && existsSync(resolve(override, "packages", "aws-lambda", "package.json"))) { - return override; + if (override) { + if (existsSync(resolve(override, "packages", "aws-lambda", "package.json"))) return override; + throw new Error( + "[hyperframes lambda] HYPERFRAMES_REPO_ROOT is not a hyperframes checkout " + + "(no packages/aws-lambda/package.json there). Point it at the repo root, or unset it.", + ); } let dir = dirname(fileURLToPath(import.meta.url)); for (let depth = 0; depth < 12; depth++) { diff --git a/packages/cli/src/commands/lambda/sam.test.ts b/packages/cli/src/commands/lambda/sam.test.ts new file mode 100644 index 0000000000..dc2744828c --- /dev/null +++ b/packages/cli/src/commands/lambda/sam.test.ts @@ -0,0 +1,32 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { locateSamTemplate } from "./sam.js"; + +let dir: string | undefined; + +afterEach(() => { + if (dir) rmSync(dir, { recursive: true, force: true }); + dir = undefined; +}); + +describe("locateSamTemplate", () => { + it("returns the template path when it exists under repoRoot", () => { + dir = mkdtempSync(join(tmpdir(), "hf-lambda-sam-")); + const samDir = join(dir, "examples", "aws-lambda"); + mkdirSync(samDir, { recursive: true }); + const templatePath = join(samDir, "template.yaml"); + writeFileSync(templatePath, "AWSTemplateFormatVersion: '2010-09-09'\n"); + + expect(locateSamTemplate(dir)).toBe(templatePath); + }); + + // No --sam-template flag exists; the error must not send users to one. + it("does not point users at the nonexistent --sam-template flag when the template is missing", () => { + dir = mkdtempSync(join(tmpdir(), "hf-lambda-sam-missing-")); + + expect(() => locateSamTemplate(dir!)).toThrow(/HYPERFRAMES_REPO_ROOT/); + expect(() => locateSamTemplate(dir!)).not.toThrow(/--sam-template/); + }); +}); diff --git a/packages/cli/src/commands/lambda/sam.ts b/packages/cli/src/commands/lambda/sam.ts index e2b2af5446..1f52ad4c69 100644 --- a/packages/cli/src/commands/lambda/sam.ts +++ b/packages/cli/src/commands/lambda/sam.ts @@ -60,17 +60,16 @@ export interface DeployOptions { } /** - * Resolve the SAM template path relative to `repoRoot`. We look for the - * `examples/aws-lambda/template.yaml` first (development checkout) and - * fall back to the installed-package layout when running from a globally - * installed `hyperframes` CLI. + * Resolve the SAM template path relative to `repoRoot`. No installed-package fallback: the + * template's `CodeUri` is relative to the monorepo, so it only works inside a checkout. */ export function locateSamTemplate(repoRoot: string): string { const candidate = join(repoRoot, "examples", "aws-lambda", "template.yaml"); if (!existsSync(candidate)) { throw new Error( `[lambda] SAM template not found at ${candidate}. ` + - `If you're running from an installed package, point --sam-template at your local copy of examples/aws-lambda/template.yaml.`, + "`hyperframes lambda deploy` needs a HyperFrames repo checkout: run it from one, " + + "or set HYPERFRAMES_REPO_ROOT to point at one.", ); } return candidate; diff --git a/packages/cli/src/commands/layout-audit.browser.js b/packages/cli/src/commands/layout-audit.browser.js index be2a90de05..99519273b6 100644 --- a/packages/cli/src/commands/layout-audit.browser.js +++ b/packages/cli/src/commands/layout-audit.browser.js @@ -1436,7 +1436,7 @@ ); } - /** Raw `d`-space endpoints (no CTM) — the mapping authors use when they paste screen coords into `d`. */ + // Raw `d`-space endpoints (no CTM), as authors paste screen coords into `d`, plus the path length. function pathUserEndpoints(path) { if (typeof path.getTotalLength !== "function" || typeof path.getPointAtLength !== "function") { return null; @@ -1450,7 +1450,7 @@ if (!Number.isFinite(total) || total <= 0) return null; const start = path.getPointAtLength(0); const end = path.getPointAtLength(total); - return { start: { x: start.x, y: start.y }, end: { x: end.x, y: end.y } }; + return { start: { x: start.x, y: start.y }, end: { x: end.x, y: end.y }, total }; } // Screen endpoints via getScreenCTM (viewBox, preserveAspectRatio, group transforms). @@ -1502,86 +1502,98 @@ return { compact, painted }; } - // Flag only the documented bug: rendered endpoints miss, but user-space-as-screen would attach. - function connectorDetachmentIssues(root, rootRect, time) { - const issues = []; - let anchors = null; - // Attach near-miss tolerance (screen px). Separate from the closed-glyph chord floor. - const threshold = Math.max(32, Math.min(rootRect.width, rootRect.height) * 0.02); - const MIN_CONNECTOR_CHORD_PX = 8; + // Attach near-miss tolerance (screen px) for both connector findings; not the glyph chord floor. + function connectorAttachThreshold(rootRect) { + return Math.max(32, Math.min(rootRect.width, rootRect.height) * 0.02); + } + + // The one connector enumeration for connector_detached and connector_orphan. Skips dash-hidden + // shafts; reports `painted` for callers to gate on, and `chord`, the rendered span in screen px. + function* connectorShafts(root) { for (const svg of Array.from(root.querySelectorAll("svg"))) { if (!isVisibleElement(svg)) continue; for (const path of Array.from(svg.querySelectorAll("path"))) { if (path.closest(CONNECTOR_SKIP_CONTAINERS)) continue; if (!isConnectorPath(svg, path)) continue; const user = pathUserEndpoints(path); + if (!user || shaftDashHidden(path, user.total)) continue; const rendered = pathScreenEndpoints(svg, path, user); - if (!user || !rendered) continue; - // Closed/glyph paths collapse to one point — compare in screen px (not user units). - const renderedChord = Math.hypot( + if (!rendered) continue; + const chord = Math.hypot( rendered.end.x - rendered.start.x, rendered.end.y - rendered.start.y, ); - if (renderedChord < MIN_CONNECTOR_CHORD_PX) continue; - if (anchors === null) anchors = connectorAnchorRects(root, rootRect); - if (anchors.compact.length < 2) return issues; - // Stable DOM identity across painted (inside) and compact (near-miss) tiers. - const attachmentKey = (point) => { - for (const anchor of anchors.painted) { - if (!anchor.element.contains(svg) && distanceToRect(point, anchor.rect) === 0) { - return anchor.element; - } - } - for (const anchor of anchors.compact) { - if (distanceToRect(point, anchor.rect) <= threshold) return anchor.element; - } - return null; - }; - const attached = (point) => attachmentKey(point) !== null; - // Half-attached as drawn is allowed; only full render-miss proceeds. - if (attached(rendered.start) || attached(rendered.end)) continue; - // Paste-into-`d` bug: both raw endpoints land on distinct anchors as screen pixels. - const userStartKey = attachmentKey(user.start); - const userEndKey = attachmentKey(user.end); - const pasteBug = Boolean(userStartKey && userEndKey && userStartKey !== userEndKey); - // Guessed marked shaft: both frames miss. Same-anchor grazes attach in user-space - // and must stay skipped. Name-only decorative flow/arrow paths stay skipped. - // 80px keeps short marker glyphs (chevrons, tips) out. - const markedMiss = - renderedChord >= 80 && - !userStartKey && - !userEndKey && - (path.hasAttribute("marker-start") || path.hasAttribute("marker-end")); - if (!pasteBug && !markedMiss) continue; - const gap = Math.round( - Math.min( - Math.min(...anchors.compact.map((a) => distanceToRect(rendered.start, a.rect))), - Math.min(...anchors.compact.map((a) => distanceToRect(rendered.end, a.rect))), - ), - ); - issues.push({ - code: "connector_detached", - severity: "warning", - time, - selector: selectorFor(path), - containerSelector: selectorFor(svg), - message: pasteBug - ? `Connector path endpoints render ${gap}px from the nearest anchorable element, but the path's user-space coordinates would attach if read as screen pixels — screen/viewport numbers were likely written into SVG \`d\` without inverting the CTM.` - : `Connector path endpoints render ${gap}px from the nearest anchorable element — a marked shaft that meets no node.`, - rect: toRect({ - left: Math.min(rendered.start.x, rendered.end.x), - top: Math.min(rendered.start.y, rendered.end.y), - right: Math.max(rendered.start.x, rendered.end.x), - bottom: Math.max(rendered.start.y, rendered.end.y), - width: Math.abs(rendered.end.x - rendered.start.x), - height: Math.abs(rendered.end.y - rendered.start.y), - }), - fixHint: pasteBug - ? "Convert measured screen coordinates into the SVG's user space (subtract the SVG rect / invert getScreenCTM) before writing path `d`, and keep the SVG a direct child of the stage." - : "Measure the settled node boxes and write `d` in the SVG's user space (invert getScreenCTM), or grow a layout-owned shaft from the source node.", - }); + yield { svg, path, user, rendered, chord, painted: shaftIsPainted(path) }; } } + } + + // Flag only the documented bug: rendered endpoints miss, but user-space-as-screen would attach. + function connectorDetachmentIssues(root, rootRect, time) { + const issues = []; + let anchors = null; + const threshold = connectorAttachThreshold(rootRect); + const MIN_CONNECTOR_CHORD_PX = 8; + for (const { svg, path, user, rendered, chord } of connectorShafts(root)) { + if (chord < MIN_CONNECTOR_CHORD_PX) continue; + if (anchors === null) anchors = connectorAnchorRects(root, rootRect); + if (anchors.compact.length < 2) return issues; + // Stable DOM identity across painted (inside) and compact (near-miss) tiers. + const attachmentKey = (point) => { + for (const anchor of anchors.painted) { + if (!anchor.element.contains(svg) && distanceToRect(point, anchor.rect) === 0) { + return anchor.element; + } + } + for (const anchor of anchors.compact) { + if (distanceToRect(point, anchor.rect) <= threshold) return anchor.element; + } + return null; + }; + const attached = (point) => attachmentKey(point) !== null; + // Half-attached as drawn is allowed; only full render-miss proceeds. + if (attached(rendered.start) || attached(rendered.end)) continue; + // Paste-into-`d` bug: both raw endpoints land on distinct anchors as screen pixels. + const userStartKey = attachmentKey(user.start); + const userEndKey = attachmentKey(user.end); + const pasteBug = Boolean(userStartKey && userEndKey && userStartKey !== userEndKey); + // Guessed marked shaft: both frames miss. Same-anchor grazes attach in user-space + // and must stay skipped. Name-only decorative flow/arrow paths stay skipped. + // 80px keeps short marker glyphs (chevrons, tips) out. + const markedMiss = + chord >= 80 && + !userStartKey && + !userEndKey && + (path.hasAttribute("marker-start") || path.hasAttribute("marker-end")); + if (!pasteBug && !markedMiss) continue; + const gap = Math.round( + Math.min( + Math.min(...anchors.compact.map((a) => distanceToRect(rendered.start, a.rect))), + Math.min(...anchors.compact.map((a) => distanceToRect(rendered.end, a.rect))), + ), + ); + issues.push({ + code: "connector_detached", + severity: "warning", + time, + selector: selectorFor(path), + containerSelector: selectorFor(svg), + message: pasteBug + ? `Connector path endpoints render ${gap}px from the nearest anchorable element, but the path's user-space coordinates would attach if read as screen pixels — screen/viewport numbers were likely written into SVG \`d\` without inverting the CTM.` + : `Connector path endpoints render ${gap}px from the nearest anchorable element — a marked shaft that meets no node.`, + rect: toRect({ + left: Math.min(rendered.start.x, rendered.end.x), + top: Math.min(rendered.start.y, rendered.end.y), + right: Math.max(rendered.start.x, rendered.end.x), + bottom: Math.max(rendered.start.y, rendered.end.y), + width: Math.abs(rendered.end.x - rendered.start.x), + height: Math.abs(rendered.end.y - rendered.start.y), + }), + fixHint: pasteBug + ? "Convert measured screen coordinates into the SVG's user space (subtract the SVG rect / invert getScreenCTM) before writing path `d`, and keep the SVG a direct child of the stage." + : "Measure the settled node boxes and write `d` in the SVG's user space (invert getScreenCTM), or grow a layout-owned shaft from the source node.", + }); + } return issues; } @@ -1598,19 +1610,63 @@ return opacityChain(path) >= 0.2; } - function shaftDashHidden(path) { - if (typeof path.getTotalLength !== "function") return false; - let total; - try { - total = path.getTotalLength(); - } catch { - return false; - } - if (!Number.isFinite(total) || total <= 0) return false; + // True when the visible dash window [offset, offset + length] sits in one gap (an unstarted + // draw-on), allowing 10% overlap. Zero-length dashes paint only with a round or square linecap. + // Distances are in `pathLength` units when set; a `pathLength` resolving to 0 paints solid. + function shaftDashHidden(path, total) { const style = getComputedStyle(path); - const offset = Number.parseFloat(style.strokeDashoffset || "0"); - const dash = Number.parseFloat(String(style.strokeDasharray || "").split(/[\s,]+/)[0] || "0"); - return offset >= total * 0.9 && dash >= total * 0.9; + const dashes = dashArrayLengths(style.strokeDasharray, path); + if (dashes === null) return false; + const authored = path.pathLength?.baseVal; // SVGAnimatedNumber; 0 when unset or unparseable + if (authored === 0 && path.hasAttribute("pathLength")) return false; + const dotsPaint = (style.strokeLinecap || "butt") !== "butt"; + const dashPaints = (index) => index % 2 === 0 && (dashes[index] > 0 || dotsPaint); + if (!dashes.some((_, index) => dashPaints(index))) return true; // only butt-capped dots + const period = dashes.reduce((sum, dash) => sum + dash, 0); + const length = authored > 0 ? authored : total; + const offset = dashLength(style.strokeDashoffset, path); // unparseable reads as 0 + // Wrap into [0, period); adding the period only to negatives keeps `0.9 % 2` exact. + const wrapped = Number.isFinite(offset) ? offset % period : 0; + const start = wrapped < 0 ? wrapped + period : wrapped; + const end = start + length; + let painted = 0; + let segmentStart = 0; + // Two periods cover any window that starts inside the first. + for (let i = 0; i < dashes.length * 2; i++) { + const segmentEnd = segmentStart + dashes[i % dashes.length]; + if (dashPaints(i % dashes.length)) { + if (segmentStart >= start && segmentEnd <= end) return false; + painted += Math.max(0, Math.min(segmentEnd, end) - Math.max(segmentStart, start)); + } + segmentStart = segmentEnd; + } + return painted <= length * 0.1; + } + + // Computed `stroke-dasharray` as an even-length list of user-unit lengths, or null when the + // stroke is solid: `none`, an all-zero list, or any negative/unparseable entry (which the spec + // renders as `none`). Odd lists repeat, per spec. + function dashArrayLengths(value, path) { + const text = String(value || "none").trim(); + if (text === "none") return null; + const lengths = text.split(/[\s,]+/).map((token) => dashLength(token, path)); + if (lengths.some((length) => !Number.isFinite(length) || length < 0)) return null; + if (lengths.every((length) => length === 0)) return null; + return lengths.length % 2 === 0 ? lengths : lengths.concat(lengths); + } + + // One dash length in user units. Computed lengths are already px; a percentage is relative to + // the normalised diagonal of the owning SVG viewport (viewBox when set, else the layout box). + function dashLength(token, path) { + const text = String(token).trim(); + const value = Number.parseFloat(text); + if (!Number.isFinite(value) || !text.endsWith("%")) return value; + const svg = path.ownerSVGElement; + if (!svg) return NaN; + const box = svg.viewBox && svg.viewBox.baseVal; + const { width, height } = + box && box.width > 0 && box.height > 0 ? box : svg.getBoundingClientRect(); + return (value / 100) * (Math.hypot(width, height) / Math.SQRT2); } function connectorEndpointCandidates(root, rootRect) { @@ -1633,57 +1689,45 @@ function connectorOrphanIssues(root, rootRect, time) { const issues = []; let candidates = null; - const threshold = Math.max(32, Math.min(rootRect.width, rootRect.height) * 0.02); - for (const svg of Array.from(root.querySelectorAll("svg"))) { - if (!isVisibleElement(svg)) continue; - for (const path of Array.from(svg.querySelectorAll("path"))) { - if (path.closest(CONNECTOR_SKIP_CONTAINERS)) continue; - if (!isConnectorPath(svg, path)) continue; - if (!shaftIsPainted(path) || shaftDashHidden(path)) continue; - const user = pathUserEndpoints(path); - const rendered = pathScreenEndpoints(svg, path, user); - if (!user || !rendered) continue; - const renderedChord = Math.hypot( - rendered.end.x - rendered.start.x, - rendered.end.y - rendered.start.y, - ); - if (renderedChord < 80) continue; - if (candidates === null) candidates = connectorEndpointCandidates(root, rootRect); - const dark = []; - for (const point of [rendered.start, rendered.end]) { - let best = null; - let attached = false; - for (const candidate of candidates) { - const gap = distanceToRect(point, candidate.rect); - if (gap > threshold) continue; - if (isVisibleElement(candidate.element)) { - attached = true; - break; - } - if (best === null || gap < best.gap) best = { gap, candidate }; + const threshold = connectorAttachThreshold(rootRect); + for (const { svg, path, rendered, chord, painted } of connectorShafts(root)) { + if (!painted) continue; + if (chord < 80) continue; + if (candidates === null) candidates = connectorEndpointCandidates(root, rootRect); + const dark = []; + for (const point of [rendered.start, rendered.end]) { + let best = null; + let attached = false; + for (const candidate of candidates) { + const gap = distanceToRect(point, candidate.rect); + if (gap > threshold) continue; + if (isVisibleElement(candidate.element)) { + attached = true; + break; } - if (!attached && best !== null) dark.push(best.candidate); + if (best === null || gap < best.gap) best = { gap, candidate }; } - if (dark.length === 0) continue; - issues.push({ - code: "connector_orphan", - severity: "warning", - time, - selector: selectorFor(path), - containerSelector: selectorFor(svg), - message: `Connector shaft is visible while ${dark.length === 2 ? "both endpoints are" : `its endpoint ${selectorFor(dark[0].element)} is`} not on stage.`, - rect: toRect({ - left: Math.min(rendered.start.x, rendered.end.x), - top: Math.min(rendered.start.y, rendered.end.y), - right: Math.max(rendered.start.x, rendered.end.x), - bottom: Math.max(rendered.start.y, rendered.end.y), - width: Math.abs(rendered.end.x - rendered.start.x), - height: Math.abs(rendered.end.y - rendered.start.y), - }), - fixHint: - "Show the shaft only after both ends are on, and hide it with the earlier exit. Do not give the line its own clock.", - }); + if (!attached && best !== null) dark.push(best.candidate); } + if (dark.length === 0) continue; + issues.push({ + code: "connector_orphan", + severity: "warning", + time, + selector: selectorFor(path), + containerSelector: selectorFor(svg), + message: `Connector shaft is visible while ${dark.length === 2 ? "both endpoints are" : `its endpoint ${selectorFor(dark[0].element)} is`} not on stage.`, + rect: toRect({ + left: Math.min(rendered.start.x, rendered.end.x), + top: Math.min(rendered.start.y, rendered.end.y), + right: Math.max(rendered.start.x, rendered.end.x), + bottom: Math.max(rendered.start.y, rendered.end.y), + width: Math.abs(rendered.end.x - rendered.start.x), + height: Math.abs(rendered.end.y - rendered.start.y), + }), + fixHint: + "Show the shaft only after both ends are on, and hide it with the earlier exit. Do not give the line its own clock.", + }); } return issues; } @@ -1807,78 +1851,10 @@ return contentOverlapIssues(root, time); }; - // Frozen-sweep guard (#U10, checkPipeline.ts): a compact per-sample - // fingerprint of every visible element's box + opacity, in DOM order. Node - // calls this once per seeked grid point and compares the strings across the - // whole run — if every sample produces the identical string, the seek never - // actually moved anything and the whole audit run is unreliable. Deliberately - // a single opaque string (not a structured array) since Node only ever needs - // equality, not per-element diffing. - // Pixel-only media motion (a 2D/WebGL canvas repainting or a playing video - // without any element moving) is invisible to a geometry+opacity fingerprint - // and false-positives sweep_static. Downsample each visible canvas/video to - // 8x8 and fold its pixels into the fingerprint. Tainted, zero-sized, or - // unreadable media hashes to a constant — no worse than geometry-only - // detection and never a new false negative for DOM-motion compositions. - // Media inside iframes is intentionally outside this fingerprint: it lives - // in a separate document, and cross-origin frames are inaccessible under SOP. - function mediaPixelHash(element) { - try { - const rect = element.getBoundingClientRect(); - const sourceWidth = element.videoWidth || element.width || rect.width; - const sourceHeight = element.videoHeight || element.height || rect.height; - if (!sourceWidth || !sourceHeight) return "x"; - const off = document.createElement("canvas"); - off.width = 8; - off.height = 8; - const ctx = off.getContext("2d"); - if (!ctx) return "x"; - ctx.drawImage(element, 0, 0, 8, 8); - const data = ctx.getImageData(0, 0, 8, 8).data; - let hash = 0; - for (let i = 0; i < data.length; i++) hash = (hash * 31 + data[i]) >>> 0; - return String(hash); - } catch { - return "x"; - } - } - - window.__hyperframesLayoutGeometry = function collectLayoutGeometry() { - const root = - document.querySelector("[data-composition-id][data-width][data-height]") || - document.querySelector("[data-composition-id]") || - document.body; - const elements = Array.from(root.querySelectorAll("*")).filter((element) => - isVisibleElement(element), - ); - const parts = elements.map((element) => { - const rect = toRect(element.getBoundingClientRect()); - const opacity = round(opacityChain(element)); - // Variable-font axis animation (font-variation-settings) is a real, - // visible motion channel that moves no geometry and no opacity, so a - // box+opacity fingerprint reads it as a frozen timeline. Worse in a - // DUPLEXED face (Recursive holds an identical advance width at every - // weight by design), where not even the line width shifts — the whole - // run then false-positives sweep_static. Fold the computed axis string - // in; it is "normal" for every element that does not use it, so this - // adds nothing to the fingerprint of an ordinary composition. - const axes = getComputedStyle(element).fontVariationSettings; - return `${rect.left},${rect.top},${rect.width},${rect.height},${opacity},${ - axes && axes !== "normal" ? axes : "" - }`; - }); - // img shares the same pixel-only-motion blind spot as canvas/video: an - // equal-size, equal-position opaque src/visibility swap moves no - // geometry and no opacity. mediaPixelHash already handles it generically - // (drawImage accepts any CanvasImageSource; width/height fall back to - // rect.width/height same as canvas/video), so only the element selector - // needed widening. - for (const media of root.querySelectorAll("canvas, video, img")) { - if (!isVisibleElement(media)) continue; - parts.push(`p:${mediaPixelHash(media)}`); - } - return parts.join("|"); - }; + // The frozen-sweep fingerprint (window.__hyperframesLayoutGeometry, #U10 in + // checkPipeline.ts) lives in motion-signature.browser.js, the single owner + // of "what counts as motion" shared with motion-sample.browser.js's + // liveness signature. // Rotation-pivot sampling (rotation_pivot_drift). Per sample, report every // rotatable candidate's bbox center, size, and current rotation angle. Node diff --git a/packages/cli/src/commands/layout-audit.browser.test.ts b/packages/cli/src/commands/layout-audit.browser.test.ts index d6427853b7..9c05c7fb34 100644 --- a/packages/cli/src/commands/layout-audit.browser.test.ts +++ b/packages/cli/src/commands/layout-audit.browser.test.ts @@ -31,192 +31,6 @@ describe("layout-audit.browser", () => { clearGeometryCollector(); }); - it("changes the sweep fingerprint when visible video pixels advance", () => { - document.body.innerHTML = ` -
- -
- `; - installGeometry({ - root: rect({ left: 0, top: 0, width: 640, height: 360 }), - footage: rect({ left: 0, top: 0, width: 640, height: 360 }), - }); - - let pixelValue = 20; - const getContextSpy = vi.spyOn(HTMLCanvasElement.prototype, "getContext") as unknown as { - mockReturnValue(value: CanvasRenderingContext2D): void; - }; - getContextSpy.mockReturnValue({ - drawImage() {}, - getImageData() { - return { data: new Uint8ClampedArray(8 * 8 * 4).fill(pixelValue) }; - }, - } as unknown as CanvasRenderingContext2D); - - installAuditScript(); - const collect = (window as unknown as { __hyperframesLayoutGeometry: () => string }) - .__hyperframesLayoutGeometry; - const before = collect(); - pixelValue = 220; - const after = collect(); - - expect(after).not.toBe(before); - }); - - // PRINFRA-666: an equal-size, equal-position opaque src/visibility - // swap (the authoring pattern for a paused-GSAP-cursor-driven "reveal - // frame N of a still sequence" composition) moves no geometry and no - // opacity, so it was invisible to the fingerprint and false-positived - // sweep_static — mediaPixelHash already existed for exactly this pixel-only - // motion class, it just wasn't applied to img. - it("changes the sweep fingerprint when a same-size opaque img is swapped", () => { - document.body.innerHTML = ` -
- -
- `; - installGeometry({ - root: rect({ left: 0, top: 0, width: 640, height: 360 }), - frame: rect({ left: 0, top: 0, width: 640, height: 360 }), - }); - - let pixelValue = 20; - const getContextSpy = vi.spyOn(HTMLCanvasElement.prototype, "getContext") as unknown as { - mockReturnValue(value: CanvasRenderingContext2D): void; - }; - getContextSpy.mockReturnValue({ - drawImage() {}, - getImageData() { - return { data: new Uint8ClampedArray(8 * 8 * 4).fill(pixelValue) }; - }, - } as unknown as CanvasRenderingContext2D); - - installAuditScript(); - const collect = (window as unknown as { __hyperframesLayoutGeometry: () => string }) - .__hyperframesLayoutGeometry; - const before = collect(); - pixelValue = 220; - const after = collect(); - - expect(after).not.toBe(before); - }); - - // Opacity-reveal fixture (CLI feedback digest 2026-07-14): code-typing style - // scenes reveal pre-laid-out characters via opacity only — no geometry ever - // moves. The sweep fingerprint must treat that as motion, both while a glyph - // fades (opacity value changes) and when it crosses the 0.2 visibility floor - // (element enters the signature); otherwise `check` misfires `sweep_static` - // and authors reach for geometry hacks (a slow host y-drift) to pass. - it("changes the sweep fingerprint when text reveals via opacity alone", () => { - document.body.innerHTML = ` -
-
c
-
- `; - - let charOpacity = "0"; - installGeometry( - { - root: rect({ left: 0, top: 0, width: 640, height: 360 }), - code: rect({ left: 40, top: 40, width: 560, height: 48 }), - char: rect({ left: 40, top: 40, width: 18, height: 48 }), - }, - { - char: { - get opacity() { - return charOpacity; - }, - } as Partial, - }, - ); - - installAuditScript(); - const collect = (window as unknown as { __hyperframesLayoutGeometry: () => string }) - .__hyperframesLayoutGeometry; - - const hidden = collect(); // below the 0.2 visibility floor — not in the signature - charOpacity = "0.5"; - const fading = collect(); // mid-fade — present, opacity part of the signature - charOpacity = "1"; - const revealed = collect(); // settled - - expect(fading).not.toBe(hidden); - expect(revealed).not.toBe(fading); - }); - - // Variable-font axis animation (registry block `weight-wave`): a crest of - // weight travels along a headline by rewriting each character's - // font-variation-settings, and NOTHING else changes — no geometry, no - // opacity, no canvas. A duplexed face makes it total: Recursive holds one - // advance width at every weight by design, so not even the line width - // shifts and all six sweep samples hashed identically until the axis string - // joined the fingerprint. `check` then failed a working composition with - // sweep_static, and the documented remedies (spread the reveal, keep an - // element animating) cannot help — the motion is real, the fingerprint was - // just blind to it. - it("changes the sweep fingerprint when only font-variation-settings moves", () => { - document.body.innerHTML = ` -
-
P
-
- `; - - let axes = '"wght" 400, "slnt" 0'; - installGeometry( - { - root: rect({ left: 0, top: 0, width: 640, height: 360 }), - line: rect({ left: 40, top: 40, width: 560, height: 48 }), - char: rect({ left: 40, top: 40, width: 18, height: 48 }), - }, - { - char: { - get fontVariationSettings() { - return axes; - }, - } as Partial, - }, - ); - - installAuditScript(); - const collect = (window as unknown as { __hyperframesLayoutGeometry: () => string }) - .__hyperframesLayoutGeometry; - - const rest = collect(); - axes = '"wght" 1000, "slnt" -12'; // the crest arrives over this character - const crest = collect(); - - expect(crest).not.toBe(rest); - }); - - // The other direction, and it guards the more dangerous failure: a - // fingerprint that varies on its own would make sweep_static unfireable and - // every green layout verdict meaningless. Identical scene, axes included, - // must hash identically. - it("keeps the sweep fingerprint identical when nothing moves, font axes included", () => { - document.body.innerHTML = ` -
-
P
-
- `; - - installGeometry( - { - root: rect({ left: 0, top: 0, width: 640, height: 360 }), - line: rect({ left: 40, top: 40, width: 560, height: 48 }), - char: rect({ left: 40, top: 40, width: 18, height: 48 }), - }, - { - char: { fontVariationSettings: '"wght" 400, "slnt" 0' } as Partial, - }, - ); - - installAuditScript(); - const collect = (window as unknown as { __hyperframesLayoutGeometry: () => string }) - .__hyperframesLayoutGeometry; - - expect(collect()).toBe(collect()); - }); - it("uses authored canvas dimensions when the root bounding rect is degenerate", () => { document.body.innerHTML = `
@@ -1462,8 +1276,7 @@ describe("layout-audit.browser coordinate-frame findings", () => { expect(issues.some((issue) => issue.code === "canvas_overflow")).toBe(true); }); - it("flags connector paths drawn in a foreign frame and passes anchored ones", () => { - document.body.innerHTML = ` + const foreignFrameDom = `
@@ -1474,18 +1287,20 @@ describe("layout-audit.browser coordinate-frame findings", () => {
`; - installGeometry( - { - root: rect({ left: 0, top: 0, width: 1920, height: 1080 }), - n1: rect({ left: 900, top: 500, width: 160, height: 160 }), - n2: rect({ left: 300, top: 200, width: 160, height: 160 }), - "connector-svg": rect({ left: 80, top: 227, width: 1740, height: 830 }), - }, - { - n1: { backgroundColor: "rgb(30, 40, 50)" }, - n2: { backgroundColor: "rgb(30, 40, 50)" }, - }, - ); + const foreignFrameRects = { + root: rect({ left: 0, top: 0, width: 1920, height: 1080 }), + n1: rect({ left: 900, top: 500, width: 160, height: 160 }), + n2: rect({ left: 300, top: 200, width: 160, height: 160 }), + "connector-svg": rect({ left: 80, top: 227, width: 1740, height: 830 }), + }; + const foreignFrameStyles = { + n1: { backgroundColor: "rgb(30, 40, 50)" }, + n2: { backgroundColor: "rgb(30, 40, 50)" }, + }; + + it("flags connector paths drawn in a foreign frame and passes anchored ones", () => { + document.body.innerHTML = foreignFrameDom; + installGeometry(foreignFrameRects, foreignFrameStyles); // Screen CTM translates svg user space by the svg's offset (80, 227): the detached path's // start (980, 580) renders at (1060, 807) — 147px below #n1's box — while the anchored // path's start (900, 353) renders at (980, 580), inside #n1. @@ -1500,6 +1315,67 @@ describe("layout-audit.browser coordinate-frame findings", () => { expect(issues[0]?.fixHint).toContain("invert getScreenCTM"); }); + it("does not flag a paste-bug connector still hidden behind its dash offset", () => { + document.body.innerHTML = foreignFrameDom; + // The fixture above, with #detached fully dash-hidden — draw-on entrance not yet advanced. + installGeometry(foreignFrameRects, { + ...foreignFrameStyles, + detached: { strokeDasharray: "100", strokeDashoffset: "100" }, + }); + installConnectorGeometry({ e: 80, f: 227 }); + installAuditScript(); + + expect(runAudit().filter((issue) => issue.code === "connector_detached")).toEqual([]); + }); + + // Hidden only when the visible window sits in one gap; a zero-length dash paints only with a + // round/square cap. Path length is 100, so `50 100` at offset 40 is the 10% boundary. + it.each([ + { dasharray: "0 4", offset: "0", count: 0 }, + { dasharray: "0 4", offset: "0", linecap: "round", count: 1 }, + { dasharray: "0, 4", offset: "0", linecap: "square", count: 1 }, + { dasharray: "0px, 999999px", offset: "-99.999px", count: 0 }, + { dasharray: "0 400", offset: "0", linecap: "round", count: 1 }, + { dasharray: "0 400", offset: "1", linecap: "round", count: 0 }, + { dasharray: "4 0", offset: "0", count: 1 }, + { dasharray: "0", offset: "0", count: 1 }, + { dasharray: "none", offset: "0", count: 1 }, + { dasharray: "100px", offset: "100px", count: 0 }, + { dasharray: "100", offset: "-100", count: 0 }, + { dasharray: "100", offset: "-150", count: 1 }, + { dasharray: "10%", offset: "10%", count: 0 }, + { dasharray: "50 100", offset: "50", count: 0 }, + { dasharray: "50 100", offset: "40", count: 0 }, + { dasharray: "50 100", offset: "30", count: 1 }, + { dasharray: "2 97", offset: "0.5", count: 0 }, + { dasharray: "1", offset: "1", pathLength: 1, count: 0 }, + { dasharray: "1", offset: "0.9", pathLength: 1, count: 0 }, + { dasharray: "1", offset: "0.5", pathLength: 1, count: 1 }, + { dasharray: "0.1 0.9", offset: "0", pathLength: 1, linecap: "round", count: 1 }, + { dasharray: "100", offset: "100", pathLength: 0, count: 1 }, + { dasharray: "0 4", offset: "0", pathLength: 0, count: 1 }, + ])( + "stroke-dasharray $dasharray, dashoffset $offset, linecap $linecap, pathLength $pathLength → $count connector_detached", + ({ dasharray, offset, linecap, pathLength, count }) => { + document.body.innerHTML = foreignFrameDom; + if (pathLength !== undefined) { + document.getElementById("detached")?.setAttribute("pathLength", String(pathLength)); + } + installGeometry(foreignFrameRects, { + ...foreignFrameStyles, + detached: { + strokeDasharray: dasharray, + strokeDashoffset: offset, + ...(linecap ? { strokeLinecap: linecap } : {}), + }, + }); + installConnectorGeometry({ e: 80, f: 227 }); + installAuditScript(); + + expect(runAudit().filter((issue) => issue.code === "connector_detached")).toHaveLength(count); + }, + ); + it("skips svgs and paths without connector intent", () => { document.body.innerHTML = `
@@ -3423,6 +3299,14 @@ interface CtmTranslate { f: number; } +// `pathLength.baseVal` as the DOM computes it: a finite SVG number, else 0 (unset, `1.`, `Infinity`, hex). +function domPathLength(attr: string | null): number { + if (attr === null) return 0; + const svgNumber = /^\s*[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?(?:\s*,)?\s*$/.test(attr); + const parsed = svgNumber ? Number(attr.replace(",", "")) : 0; + return Number.isFinite(parsed) ? parsed : 0; +} + // happy-dom has no SVG geometry APIs; endpoints come from the path's `d`, the CTM is a pure translate. function installConnectorGeometry(translate: CtmTranslate, root: ParentNode = document): void { const matrix = { a: 1, b: 0, c: 0, d: 1, e: translate.e, f: translate.f }; @@ -3443,6 +3327,11 @@ function installConnectorGeometry(translate: CtmTranslate, root: ParentNode = do const start = { x: numbers[0] ?? 0, y: numbers[1] ?? 0 }; const end = { x: numbers[numbers.length - 2] ?? 0, y: numbers[numbers.length - 1] ?? 0 }; Object.defineProperty(path, "getTotalLength", { ...prop, value: () => 100 }); + // happy-dom has no SVGGeometryElement; mirror the DOM's `pathLength`. + Object.defineProperty(path, "pathLength", { + ...prop, + value: { baseVal: domPathLength(path.getAttribute("pathLength")) }, + }); Object.defineProperty(path, "getPointAtLength", { ...prop, value: (length: number) => (length === 0 ? start : end), diff --git a/packages/cli/src/commands/layout.ts b/packages/cli/src/commands/layout.ts index 64ffa8ccbc..7a03d3b61e 100644 --- a/packages/cli/src/commands/layout.ts +++ b/packages/cli/src/commands/layout.ts @@ -395,6 +395,7 @@ async function runMotionPass( width: window.innerWidth, height: window.innerHeight, })); + await page.addScriptTag({ content: loadBrowserScript("motion-signature.browser.js") }); await page.addScriptTag({ content: loadBrowserScript("motion-sample.browser.js") }); const frames = await collectMotionFrames(page, times, selectors, livenessScopes); return { issues: evaluateMotion(frames, spec.assertions, canvas), sampleCount: frames.length }; diff --git a/packages/cli/src/commands/motion-sample.browser.js b/packages/cli/src/commands/motion-sample.browser.js index 9d3e520d5f..3893e33212 100644 --- a/packages/cli/src/commands/motion-sample.browser.js +++ b/packages/cli/src/commands/motion-sample.browser.js @@ -4,88 +4,32 @@ // scope it returns a bucketed signature of all visible elements, so the Node-side // evaluator can detect frozen windows by comparing signatures across frames. (function () { - const IGNORE_TAGS = new Set(["SCRIPT", "STYLE", "TEMPLATE", "NOSCRIPT", "META", "LINK"]); - - function round(value) { - return Math.round(value * 100) / 100; - } + // Visibility, opacity and the liveness signature come from the shared classifier + // (motion-signature.browser.js), so this sampler and the frozen-sweep guard agree on what moves. + // Resolved at install, checked at call: an install-time throw would only surface as an opaque + // "__hyperframesMotionSample is not a function" from the driver's evaluate. + const shared = window.__hyperframesMotionSignature; function toRect(rect) { return { - left: round(rect.left), - top: round(rect.top), - right: round(rect.right), - bottom: round(rect.bottom), - width: round(rect.width), - height: round(rect.height), + left: shared.round(rect.left), + top: shared.round(rect.top), + right: shared.round(rect.right), + bottom: shared.round(rect.bottom), + width: shared.round(rect.width), + height: shared.round(rect.height), }; } - function opacityChain(element) { - let opacity = 1; - for (let current = element; current; current = current.parentElement) { - const parsed = Number.parseFloat(getComputedStyle(current).opacity || "1"); - if (Number.isFinite(parsed)) opacity *= parsed; - } - return opacity; - } - - // Mirrors layout-audit.browser.js isVisibleElement. - // fallow-ignore-next-line complexity - function isVisibleElement(element) { - if (IGNORE_TAGS.has(element.tagName)) return false; - const style = getComputedStyle(element); - if ( - style.display === "none" || - style.visibility === "hidden" || - style.visibility === "collapse" - ) { - return false; - } - if (opacityChain(element) < 0.2) return false; - const rect = element.getBoundingClientRect(); - return rect.width > 0.5 && rect.height > 0.5; - } - function sampleElement(element) { const rect = element.getBoundingClientRect(); return { rect: toRect(rect), - opacity: round(opacityChain(element)), - visible: isVisibleElement(element), + opacity: shared.round(shared.opacityChain(element)), + visible: shared.isVisibleElement(element), }; } - function compositionRoot() { - return document.querySelector("[data-composition-id]") || document.body; - } - - // ponytail: bucket position to 2px and opacity to 0.08 so the RFC's "moves ≥2px / - // opacity ≥0.08" thresholds fall out of bucketing. Boundary-straddling moves are - // approximate — good enough for liveness; tighten only if false negatives show up. - function elementSignature(element) { - const rect = element.getBoundingClientRect(); - const bx = Math.round(rect.left / 2); - const by = Math.round(rect.top / 2); - const bw = Math.round(rect.width / 2); - const bh = Math.round(rect.height / 2); - const bo = Math.round(opacityChain(element) / 0.08); - return bx + "," + by + "," + bw + "," + bh + "," + bo; - } - - function livenessSignature(root) { - if (!root) return ""; - const parts = []; - // ponytail: O(DOM) × MOTION_MAX_SAMPLES (300) — fine for typical compositions; - // narrow selector (e.g. "[id],[class]") if heavy-DOM compositions slow this down. - const all = root.querySelectorAll("*"); - for (const element of all) { - if (!isVisibleElement(element)) continue; - parts.push(elementSignature(element)); - } - return parts.join("|"); - } - function safeQuery(selector) { try { return document.querySelector(selector); @@ -108,13 +52,22 @@ function sampleLiveness(scopes) { const liveness = {}; for (const scope of scopes) { - const root = scope === "*" ? compositionRoot() : safeQuery(scope); - liveness[scope] = livenessSignature(root); + const root = scope === "*" ? shared.compositionRoot() : safeQuery(scope); + // ponytail: O(DOM) × MOTION_MAX_SAMPLES (300), with three computed-style + // reads (element + ::before/::after) plus an ancestor walk per box-generating + // element — fine for typical compositions; narrow the scope if heavy-DOM + // compositions slow down. + liveness[scope] = shared.compositionSignature(root, { quantize: true }); } return liveness; } window.__hyperframesMotionSample = function motionSample(options) { + if (!shared) { + throw new Error( + "motion-signature.browser.js must be injected before motion-sample.browser.js", + ); + } const { selectors = [], livenessScopes = [] } = options || {}; return { data: sampleSelectors(selectors), liveness: sampleLiveness(livenessScopes) }; }; diff --git a/packages/cli/src/commands/motion-sample.browser.test.ts b/packages/cli/src/commands/motion-sample.browser.test.ts index d8003cf646..1349864946 100644 --- a/packages/cli/src/commands/motion-sample.browser.test.ts +++ b/packages/cli/src/commands/motion-sample.browser.test.ts @@ -6,6 +6,7 @@ import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; const __dirname = dirname(fileURLToPath(import.meta.url)); +const signatureScript = readFileSync(join(__dirname, "motion-signature.browser.js"), "utf-8"); const script = readFileSync(join(__dirname, "motion-sample.browser.js"), "utf-8"); interface Geo { @@ -13,6 +14,8 @@ interface Geo { opacity?: string; display?: string; visibility?: string; + /** `::after` computed `content`; re-read on every call when a getter. */ + afterContent?: string; } interface SampleResult { @@ -24,8 +27,13 @@ interface SampleResult { } function installGeometry(byId: Record): void { - vi.spyOn(window, "getComputedStyle").mockImplementation((element) => { + vi.spyOn(window, "getComputedStyle").mockImplementation((element, pseudoElement) => { const geo = byId[(element as Element).id] ?? {}; + if (pseudoElement) { + return { + content: pseudoElement === "::after" ? (geo.afterContent ?? "none") : "none", + } as unknown as CSSStyleDeclaration; + } return { display: geo.display ?? "block", visibility: geo.visibility ?? "visible", @@ -47,6 +55,9 @@ function installGeometry(byId: Record): void { } function installScript(): void { + // The sampler reads the shared motion classifier at install time. + // eslint-disable-next-line no-new-func + new Function(signatureScript)(); // eslint-disable-next-line no-new-func new Function(script)(); } @@ -62,6 +73,16 @@ describe("motion-sample.browser", () => { vi.restoreAllMocks(); document.body.innerHTML = ""; delete (window as unknown as { __hyperframesMotionSample?: unknown }).__hyperframesMotionSample; + Reflect.deleteProperty(window, "__hyperframesMotionSignature"); + Reflect.deleteProperty(window, "__hyperframesLayoutGeometry"); + }); + + it("installs without the shared motion classifier and names it on the first call", () => { + // Installing must not throw: addScriptTag resolves on load regardless, so + // the driver only ever sees the error from its evaluate call. + // eslint-disable-next-line no-new-func + expect(() => new Function(script)()).not.toThrow(); + expect(() => sample({ livenessScopes: ["*"] })).toThrow(/motion-signature\.browser\.js/); }); it("samples a present, visible selector and returns null for an absent one", () => { @@ -79,6 +100,18 @@ describe("motion-sample.browser", () => { expect(result.data["#missing"]).toBeNull(); }); + it("reports an explicitly asserted data-layout-ignore element as visible", () => { + document.body.innerHTML = ` +
x
+ `; + installGeometry({ glow: { rect: { left: 100, top: 50, width: 300, height: 80 } } }); + installScript(); + + // The layout-audit opt-out excludes the layer from liveness, not from an + // assertion that names it. + expect(sample({ selectors: ["#glow"] }).data["#glow"]?.visible).toBe(true); + }); + it("reflects inherited ancestor opacity", () => { document.body.innerHTML = `
Hi
@@ -114,6 +147,46 @@ describe("motion-sample.browser", () => { expect(moved).not.toBe(before); }); + // Liveness and the frozen-sweep guard share one classifier: a fixed-width + // attr()-backed countdown that the sweep guard accepts as motion must not be + // reported frozen by keepsMoving. + it("changes the liveness signature when attr-backed generated content changes, in step with the sweep fingerprint", () => { + document.body.innerHTML = ` +
+ `; + installGeometry({ + countdown: { + rect: { left: 280, top: 140, width: 80, height: 48 }, + get afterContent() { + return JSON.stringify(document.getElementById("countdown")!.getAttribute("data-txt")); + }, + }, + }); + installScript(); + const sweep = (window as unknown as { __hyperframesLayoutGeometry: () => string }) + .__hyperframesLayoutGeometry; + + const livenessBefore = sample({ livenessScopes: ["*"] }).liveness["*"]; + const sweepBefore = sweep(); + document.getElementById("countdown")!.setAttribute("data-txt", "09"); + + expect(sample({ livenessScopes: ["*"] }).liveness["*"]).not.toBe(livenessBefore); + expect(sweep()).not.toBe(sweepBefore); + }); + + it("signs a leaf withinSelector scope by the scope element itself", () => { + document.body.innerHTML = ` +
+ `; + installGeometry({ logo: { rect: { left: 10, top: 10, width: 50, height: 50 } } }); + installScript(); + + // The scope root is part of its own signature; a leaf scope is never "missing". + expect((sample({ livenessScopes: ["#logo"] }).liveness["#logo"] ?? "").length).toBeGreaterThan( + 0, + ); + }); + it("scopes liveness to a withinSelector and returns empty for a missing scope", () => { document.body.innerHTML = `
x
diff --git a/packages/cli/src/commands/motion-signature.browser.chromium.test.ts b/packages/cli/src/commands/motion-signature.browser.chromium.test.ts new file mode 100644 index 0000000000..c337d00182 --- /dev/null +++ b/packages/cli/src/commands/motion-signature.browser.chromium.test.ts @@ -0,0 +1,636 @@ +// fallow-ignore-file code-duplication +// Real-Chromium pins for motion-signature.browser.js: the happy-dom suite fakes getComputedStyle, this one +// asserts the same branches against Blink, using the exact scripts `hyperframes check` injects. +// Skipped without a local Chrome; opt-in on Windows (HYPERFRAMES_BROWSER_TESTS=1), where its launch timed out. +import { existsSync, readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import type { Browser, Page } from "puppeteer-core"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { findSystemBrowser } from "../browser/manager.js"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const signatureScript = readFileSync(join(__dirname, "motion-signature.browser.js"), "utf-8"); +const motionSampleScript = readFileSync(join(__dirname, "motion-sample.browser.js"), "utf-8"); + +function resolveExecutable(): string | undefined { + for (const name of ["HYPERFRAMES_BROWSER_PATH", "PUPPETEER_EXECUTABLE_PATH"]) { + const candidate = process.env[name]; + if (candidate && existsSync(candidate)) return candidate; + } + return findSystemBrowser()?.executablePath; +} + +const executablePath = resolveExecutable(); +const RUNS_CHROMIUM = + !!executablePath && + (process.platform !== "win32" || process.env.HYPERFRAMES_BROWSER_TESTS === "1"); +// The package hookTimeout is sized for cold module imports, not for launching +// a browser; give the launch its own ceiling. +const BROWSER_LAUNCH_TIMEOUT_MS = 120_000; + +interface Samples { + sweep: string; + liveness: string; +} + +declare global { + interface Window { + __hyperframesLayoutGeometry: () => string; + __hyperframesMotionSample: (options: { selectors?: string[]; livenessScopes?: string[] }) => { + data: Record; + liveness: Record; + }; + } +} + +function composition(css: string, body: string): string { + return ` +
${body}
+ `; +} + +describe.skipIf(!RUNS_CHROMIUM)("motion-signature.browser in Chromium", () => { + let browser: Browser; + let page: Page; + + beforeAll(async () => { + const puppeteer = await import("puppeteer-core"); + browser = await puppeteer.default.launch({ + headless: true, + executablePath, + args: ["--no-sandbox", "--disable-dev-shm-usage", "--disable-gpu"], + }); + page = await browser.newPage(); + await page.setViewport({ width: 640, height: 360 }); + }, BROWSER_LAUNCH_TIMEOUT_MS); + + afterAll(async () => { + await browser?.close(); + }); + + async function load(html: string): Promise { + await page.setContent(html); + await page.addScriptTag({ content: signatureScript }); + await page.addScriptTag({ content: motionSampleScript }); + } + + async function sample(scope = "*"): Promise { + return page.evaluate( + (livenessScope) => ({ + sweep: window.__hyperframesLayoutGeometry(), + liveness: + window.__hyperframesMotionSample({ livenessScopes: [livenessScope] }).liveness[ + livenessScope + ] ?? "", + }), + scope, + ); + } + + async function mutate(script: string): Promise { + await page.evaluate(script); + } + + // motion-sample's per-selector visibility bit (isVisibleElement on an + // explicitly asserted element). + async function visible(selector: string): Promise { + return page.evaluate( + (sel) => window.__hyperframesMotionSample({ selectors: [sel] }).data[sel]?.visible, + selector, + ); + } + + it("treats an attr()-backed fixed-width countdown as motion in both samplers", async () => { + await load( + composition( + "#countdown::after { content: attr(data-txt); }", + '', + ), + ); + const before = await sample(); + await mutate('document.getElementById("countdown").setAttribute("data-txt", "09")'); + const after = await sample(); + + expect(after.sweep).not.toBe(before.sweep); + expect(after.liveness).not.toBe(before.liveness); + }); + + it("keeps both signatures identical when a countdown with every textual channel is frozen", async () => { + await load( + composition( + "body { counter-reset: countdown 10; } #countdown::after { content: attr(data-txt) counter(countdown); }", + '10', + ), + ); + const first = await sample(); + const second = await sample(); + + expect(second).toEqual(first); + }); + + it("ignores a display:none decoy counter owner in a frozen composition", async () => { + await load( + composition( + "#decoy { display: none; counter-reset: countdown 10; } #countdown::after { content: counter(countdown); }", + '
', + ), + ); + const before = await sample(); + await mutate('document.getElementById("decoy").style.counterReset = "countdown 9"'); + const after = await sample(); + + expect(after).toEqual(before); + }); + + it("ignores a decoy counter owner nested inside a display:none subtree", async () => { + await load( + composition( + "#hidden-parent { display: none; } #decoy { display: block; counter-reset: countdown 10; } #countdown::after { content: counter(countdown); }", + '
', + ), + ); + const before = await sample(); + await mutate('document.getElementById("decoy").style.counterReset = "countdown 9"'); + const after = await sample(); + + expect(after).toEqual(before); + }); + + it("ignores counter state when nothing paints a counter", async () => { + await load( + composition( + "#owner { height: 0; counter-reset: countdown 10; }", + '
10', + ), + ); + const before = await sample(); + await mutate('document.getElementById("owner").style.counterReset = "countdown 9"'); + const after = await sample(); + + expect(after).toEqual(before); + }); + + it("ignores a zero-box decoy whose counter name nothing paints even when a list marker exists", async () => { + await load( + composition( + "li { width: 80px; height: 48px; } #decoy { height: 0; counter-reset: decoy 10; }", + '
  • item
', + ), + ); + expect(await page.evaluate(() => getComputedStyle(document.querySelector("li")!).display)).toBe( + "list-item", + ); + const before = await sample(); + await mutate('document.getElementById("decoy").style.counterReset = "decoy 9"'); + const after = await sample(); + + expect(after).toEqual(before); + }); + + it("ignores a counter consumed only by a pseudo-element under a data-layout-ignore layer", async () => { + await load( + composition( + "#owner { height: 0; counter-reset: countdown 10; } #a::after { content: counter(countdown); }", + '
', + ), + ); + const before = await sample(); + await mutate('document.getElementById("owner").style.counterReset = "countdown 9"'); + const after = await sample(); + + expect(after).toEqual(before); + }); + + it("ignores a counter consumed only by a pseudo-element that inherits visibility:hidden", async () => { + await load( + composition( + "#owner { height: 0; counter-reset: countdown 10; } #a { visibility: hidden; } #a::after { content: counter(countdown); }", + '
', + ), + ); + const before = await sample(); + await mutate('document.getElementById("owner").style.counterReset = "countdown 9"'); + const after = await sample(); + + expect(after).toEqual(before); + }); + + it("sees a counter painted by a visible pseudo-element on a visibility:hidden host", async () => { + await load( + composition( + "body { counter-reset: countdown 10; } #a { visibility: hidden; } #a::after { visibility: visible; content: counter(countdown); }", + '', + ), + ); + const before = await sample(); + await mutate('document.body.style.counterReset = "countdown 9"'); + const after = await sample(); + + expect(after.sweep).not.toBe(before.sweep); + }); + + it("sees a counter painted only through a ::marker", async () => { + await load( + composition( + "#owner { height: 0; counter-reset: countdown 10; } li { width: 80px; height: 48px; } li::marker { content: counter(countdown); }", + '
  • item
', + ), + ); + const before = await sample(); + await mutate('document.getElementById("owner").style.counterReset = "countdown 9"'); + const after = await sample(); + + expect(after.sweep).not.toBe(before.sweep); + }); + + it("sees counters(), styled counter(), and counter-set owners", async () => { + await load( + composition( + "#owner { height: 0; counter-reset: outer 1 inner 5; counter-set: styled 10; } #a::after { content: counters(outer, '.') ' ' counter(styled, upper-roman); }", + '
', + ), + ); + const start = await sample(); + await mutate('document.getElementById("owner").style.counterReset = "outer 2 inner 5"'); + const afterCounters = await sample(); + await mutate('document.getElementById("owner").style.counterSet = "styled 9"'); + const afterSet = await sample(); + + expect(afterCounters.sweep).not.toBe(start.sweep); + expect(afterSet.sweep).not.toBe(afterCounters.sweep); + }); + + it("sees a zero-box owner's counter change when a visible pseudo-element paints it", async () => { + await load( + composition( + "#owner { counter-reset: countdown 10; } #countdown::after { content: counter(countdown); }", + '
', + ), + ); + // Blink leaves counter() unsubstituted in computed content, so the only + // signal is the owner's counter state. + expect( + await page.evaluate( + () => getComputedStyle(document.getElementById("countdown")!, "::after").content, + ), + ).toBe("counter(countdown)"); + const before = await sample(); + await mutate('document.getElementById("owner").style.counterReset = "countdown 9"'); + const after = await sample(); + + expect(after.sweep).not.toBe(before.sweep); + expect(after.liveness).not.toBe(before.liveness); + }); + + it("sees a counter painted by a zero-box host's absolutely positioned pseudo-element", async () => { + await load( + composition( + "body { counter-reset: countdown 10; } #host { width: 0; height: 0; } #host::after { position: absolute; left: 100px; top: 100px; content: counter(countdown); }", + '
', + ), + ); + const before = await sample(); + await mutate('document.body.style.counterReset = "countdown 9"'); + const after = await sample(); + + expect(after.sweep).not.toBe(before.sweep); + }); + + it("sees a counter owned above the composition root change", async () => { + await load( + composition( + "body { counter-reset: countdown 10; } #countdown::after { content: counter(countdown); }", + '', + ), + ); + const before = await sample(); + await mutate('document.body.style.counterReset = "countdown 9"'); + const after = await sample(); + + expect(after.sweep).not.toBe(before.sweep); + }); + + it("sees a pseudo-element's own counter-increment change", async () => { + await load( + composition( + "#countdown::after { counter-increment: countdown 10; content: counter(countdown); } #countdown.next::after { counter-increment: countdown 9; }", + '', + ), + ); + const before = await sample(); + await mutate('document.getElementById("countdown").classList.add("next")'); + const after = await sample(); + + expect(after.sweep).not.toBe(before.sweep); + }); + + it("sees a clip-path wipe over a box that never moves", async () => { + await load( + composition( + "#panel { width: 200px; height: 100px; background: #f00; clip-path: inset(0 100% 0 0); }", + '
', + ), + ); + const before = await sample(); + await mutate('document.getElementById("panel").style.clipPath = "inset(0 50% 0 0)"'); + const after = await sample(); + + expect(after.sweep).not.toBe(before.sweep); + expect(after.liveness).not.toBe(before.liveness); + }); + + it("sees textarea value and checkbox indeterminate changes", async () => { + await load( + composition( + "", + '', + ), + ); + const start = await sample(); + await mutate('document.getElementById("note").value = "09"'); + const afterText = await sample(); + await mutate('document.getElementById("toggle").indeterminate = true'); + const afterIndeterminate = await sample(); + + expect(afterText.sweep).not.toBe(start.sweep); + expect(afterIndeterminate.sweep).not.toBe(afterText.sweep); + }); + + it("sees the composition root's own text change", async () => { + await load(composition("", "10")); + const before = await sample(); + await mutate('document.getElementById("root").firstChild.textContent = "09"'); + const after = await sample(); + + expect(after.sweep).not.toBe(before.sweep); + expect(after.liveness).not.toBe(before.liveness); + }); + + it("ignores text mutations inside a display:none descendant", async () => { + await load( + composition( + "#hidden { display: none; }", + '1010', + ), + ); + const before = await sample(); + await mutate('document.getElementById("hidden").textContent = "09"'); + const after = await sample(); + + expect(after).toEqual(before); + }); + + it("ignores motion on a data-layout-ignore layer", async () => { + await load( + composition( + "#glow { position: absolute; width: 100px; height: 100px; background: #0f0; }", + '
10', + ), + ); + const before = await sample(); + await mutate('document.getElementById("glow").style.left = "200px"'); + const after = await sample(); + + expect(after).toEqual(before); + }); + + // A keepsMoving scope names the element explicitly, so the layout-audit + // opt-out on the scope itself does not empty its signature (which the Node + // side would otherwise report as motion_selector_missing for an element that + // exists). Opt-outs INSIDE the scope still apply. + it("measures a keepsMoving scope that is itself data-layout-ignore, but not opted-out layers inside it", async () => { + await load( + composition( + "#scene { position: absolute; width: 300px; height: 200px; } #logo, #glow { position: absolute; width: 50px; height: 50px; background: #00f; }", + '
', + ), + ); + const before = await sample("#scene"); + expect(before.liveness).not.toBe(""); + await mutate('document.getElementById("glow").style.left = "100px"'); + const afterIgnoredMove = await sample("#scene"); + await mutate('document.getElementById("logo").style.left = "100px"'); + const afterMove = await sample("#scene"); + + expect(afterIgnoredMove.liveness).toBe(before.liveness); + expect(afterMove.liveness).not.toBe(before.liveness); + }); + + it("ignores text mutations inside content-visibility:hidden contents", async () => { + await load( + composition( + "#wrap { content-visibility: hidden; }", + '
10
10', + ), + ); + const before = await sample(); + await mutate('document.getElementById("skipped").textContent = "09"'); + const after = await sample(); + + expect(after).toEqual(before); + }); + + it("ignores a decoy counter owner inside content-visibility:hidden contents", async () => { + await load( + composition( + "#wrap { content-visibility: hidden; } #decoy { counter-reset: countdown 10; } #countdown::after { content: counter(countdown); }", + '
', + ), + ); + const before = await sample(); + await mutate('document.getElementById("decoy").style.counterReset = "countdown 9"'); + const after = await sample(); + + expect(after).toEqual(before); + }); + + it("ignores a decoy counter owner inside off-screen content-visibility:auto contents", async () => { + await load( + composition( + "#far { content-visibility: auto; position: absolute; top: 5000px; width: 10px; height: 10px; } #decoy { counter-reset: countdown 10; } #countdown::after { content: counter(countdown); }", + '
', + ), + ); + const before = await sample(); + await mutate('document.getElementById("decoy").style.counterReset = "countdown 9"'); + const after = await sample(); + + expect(after).toEqual(before); + }); + + it("ignores a repaint of a canvas whose contents are skipped by content-visibility:hidden", async () => { + await load( + composition( + "#c { content-visibility: hidden; width: 100px; height: 100px; }", + '', + ), + ); + const before = await sample(); + await mutate( + 'const ctx = document.getElementById("c").getContext("2d"); ctx.fillStyle = "#f00"; ctx.fillRect(0, 0, 100, 100);', + ); + const after = await sample(); + + expect(after).toEqual(before); + }); + + // content-visibility only skips contents where size containment applies; on + // a non-atomic inline host it is a no-op and everything inside still paints. + it("keeps signing text and pseudo content inside an inline content-visibility:hidden host", async () => { + await load( + composition( + "#host { content-visibility: hidden; } #host::after { content: attr(data-txt); }", + '10', + ), + ); + const start = await sample(); + await mutate('document.getElementById("kid").textContent = "09"'); + const afterText = await sample(); + await mutate('document.getElementById("host").setAttribute("data-txt", "09")'); + const afterPseudo = await sample(); + + expect(afterText.sweep).not.toBe(start.sweep); + expect(afterText.liveness).not.toBe(start.liveness); + expect(afterPseudo.sweep).not.toBe(afterText.sweep); + }); + + it("sees a checkbox toggle on a content-visibility:hidden control", async () => { + await load( + composition( + "#toggle { content-visibility: hidden; width: 24px; height: 24px; }", + '', + ), + ); + const before = await sample(); + await mutate('document.getElementById("toggle").checked = true'); + const after = await sample(); + + expect(after.sweep).not.toBe(before.sweep); + }); + + it("ignores a value change on a text input whose contents are skipped by content-visibility:hidden", async () => { + await load( + composition( + "#note { content-visibility: hidden; width: 120px; height: 40px; font: 24px monospace; }", + '', + ), + ); + const before = await sample(); + await mutate('document.getElementById("note").value = "09"'); + const after = await sample(); + + expect(after).toEqual(before); + }); + + it("sees a counter painted only by a display:contents host's pseudo-element", async () => { + await load( + composition( + "body { counter-reset: countdown 10; } #host { display: contents; } #host::after { content: counter(countdown); font: 32px/48px monospace; }", + '
', + ), + ); + const before = await sample(); + await mutate('document.body.style.counterReset = "countdown 9"'); + const after = await sample(); + + expect(after.sweep).not.toBe(before.sweep); + }); + + it("ignores a content-visibility:hidden host's own text and pseudo content but still sees its box move", async () => { + await load( + composition( + "#host { content-visibility: hidden; position: absolute; width: 80px; height: 48px; background: #f00; } #host::after { content: attr(data-txt); }", + '
10
', + ), + ); + const start = await sample(); + await mutate('document.getElementById("host").firstChild.textContent = "09"'); + await mutate('document.getElementById("host").setAttribute("data-txt", "09")'); + const afterContents = await sample(); + await mutate('document.getElementById("host").style.left = "100px"'); + const afterMove = await sample(); + + expect(afterContents).toEqual(start); + expect(afterMove.sweep).not.toBe(start.sweep); + }); + + // A display:contents host has no box of its own, so the platform cannot tell + // it apart from skipped contents; inside a content-visibility:hidden host its + // pseudo-elements paint nothing and must not keep a counter consumed. + it("ignores a counter painted only by a display:contents host's pseudo-element inside skipped contents", async () => { + await load( + composition( + "body { counter-reset: countdown 10; } #wrap { content-visibility: hidden; width: 80px; height: 48px; } #host { display: contents; } #host::after { content: counter(countdown); font: 32px/48px monospace; }", + '
', + ), + ); + const before = await sample(); + await mutate('document.body.style.counterReset = "countdown 9"'); + const after = await sample(); + + expect(after).toEqual(before); + }); + + // Chromium (152) skips the contents of a table-cell host but not of a + // table-caption host; NOT_CONTAINABLE_DISPLAY mirrors the platform here + // rather than css-contain-2's exemption list. This test and the next pin + // both halves. + it("ignores a table-cell content-visibility:hidden host's own text and pseudo content", async () => { + await load( + composition( + "#host { display: table-cell; content-visibility: hidden; width: 80px; height: 48px; font: 32px/48px monospace; } #host::after { content: attr(data-txt); }", + '
10
10', + ), + ); + const before = await sample(); + await mutate('document.getElementById("host").firstChild.textContent = "09"'); + await mutate('document.getElementById("host").setAttribute("data-txt", "09")'); + const after = await sample(); + + expect(after).toEqual(before); + }); + + it("keeps signing a table-caption content-visibility:hidden host's own text and pseudo content", async () => { + await load( + composition( + "#host { content-visibility: hidden; width: 80px; height: 48px; font: 32px/48px monospace; } #host::after { content: attr(data-txt); }", + '
10
', + ), + ); + const start = await sample(); + await mutate('document.getElementById("host").firstChild.textContent = "09"'); + const afterText = await sample(); + await mutate('document.getElementById("host").setAttribute("data-txt", "09")'); + const afterPseudo = await sample(); + + expect(afterText.sweep).not.toBe(start.sweep); + expect(afterText.liveness).not.toBe(start.liveness); + expect(afterPseudo.sweep).not.toBe(afterText.sweep); + }); + + // The only counter consumers are hidden pseudo-elements of a host that skips its contents; `shown` gives + // the host's hidden counter-increment a consumed name. Nothing the host declares or paints may count as motion. + it("ignores a counter reachable only through a skipped host's hidden pseudo-elements", async () => { + await load( + composition( + "html { counter-reset: shown 1; } body { counter-reset: countdown 10; } #host { content-visibility: hidden; display: list-item; list-style-position: inside; width: 80px; height: 48px; } #host::marker { content: counter(countdown); } #host::after { content: counter(countdown); counter-increment: shown 0; } #host.stepped::after { counter-increment: shown 5; } #shown::after { content: counter(shown); }", + '
', + ), + ); + const before = await sample(); + await mutate('document.body.style.counterReset = "countdown 9"'); + const afterOwner = await sample(); + await mutate('document.getElementById("host").classList.add("stepped")'); + const afterHiddenIncrement = await sample(); + + expect(await visible("#kid")).toBe(false); + expect(afterOwner).toEqual(before); + expect(afterHiddenIncrement).toEqual(before); + }); +}); diff --git a/packages/cli/src/commands/motion-signature.browser.js b/packages/cli/src/commands/motion-signature.browser.js new file mode 100644 index 0000000000..9b11c084b0 --- /dev/null +++ b/packages/cli/src/commands/motion-signature.browser.js @@ -0,0 +1,374 @@ +// Shared "what counts as motion" classifier, injected before layout-audit.browser.js and motion-sample.browser.js. +// The frozen-sweep guard (sweep_static) and keepsMoving liveness (motion_frozen) meet in one decision, so both +// must count the same channels as motion; only quantization differs (liveness buckets 2px and 0.08 opacity). +// A channel reader returns a string equal across samples iff it did not visibly change, "" when it does not apply. +(function () { + const IGNORE_TAGS = new Set(["SCRIPT", "STYLE", "TEMPLATE", "NOSCRIPT", "META", "LINK"]); + const MEDIA_TAGS = new Set(["CANVAS", "VIDEO", "IMG"]); + const FNV_OFFSET_BASIS = 2166136261; + const FNV_PRIME = 16777619; + const LIVENESS_POSITION_BUCKET_PX = 2; + const LIVENESS_OPACITY_BUCKET = 0.08; + const IGNORE_SELECTOR = "[data-layout-ignore], [data-layout-check='ignore']"; + // counter(name) / counters(name, sep) in generated content. A list-item box + // whose ::marker content is `normal` paints counter(list-item) implicitly. + const COUNTER_FUNCTION = /counters?\(\s*([^\s,)]+)/g; + const IMPLICIT_MARKER_CONTENT = "counter(list-item)"; + const LIST_ITEM_DISPLAY = /\blist-item\b/; + // Whether an element sits inside skipped contents is not on its computed style; only checkVisibility knows. + // PAINTED_OPTIONS matches layout-audit.browser.js isVisibleElement's opacity-floor path. happy-dom lacks + // checkVisibility, so callers keep a computed-style fallback. + const RENDERED_BOX_OPTIONS = { contentVisibilityAuto: true }; + const PAINTED_OPTIONS = { + opacityProperty: true, + visibilityProperty: true, + contentVisibilityAuto: true, + }; + // Stand-in for the ::before/::after of an element whose contents are skipped: + // no pseudo box exists, so nothing it declares (content, counter-*) paints. + const NO_BOX = Object.freeze({ display: "none" }); + const SKIPPED_PSEUDO = Object.freeze({ before: NO_BOX, after: NO_BOX }); + // content-visibility skips contents only where size containment applies (css-contain-2); hosts matching this + // paint everything. It mirrors Chromium 152 where that differs from the spec: a table-cell host skips, a + // table-caption host does not. Replaced elements (MEDIA_TAGS) are atomic even at display:inline. + const NOT_CONTAINABLE_DISPLAY = + /^(inline( list-item)?|contents|table|inline-table|table-(?!cell$)[a-z-]+|ruby[a-z-]*)$/; + + function skipsContents(element, style) { + if (style.contentVisibility !== "hidden") return false; + return MEDIA_TAGS.has(element.tagName) || !NOT_CONTAINABLE_DISPLAY.test(style.display); + } + + function round(value) { + return Math.round(value * 100) / 100; + } + + function opacityChain(element) { + let opacity = 1; + for (let current = element; current; current = current.parentElement) { + const parsed = Number.parseFloat(getComputedStyle(current).opacity || "1"); + if (Number.isFinite(parsed)) opacity *= parsed; + } + return opacity; + } + + function compositionRoot() { + return ( + document.querySelector("[data-composition-id][data-width][data-height]") || + document.querySelector("[data-composition-id]") || + document.body + ); + } + + function isHiddenStyle(style) { + return ( + style.display === "none" || style.visibility === "hidden" || style.visibility === "collapse" + ); + } + + // Kept local rather than shared with layout-audit, which is installed and tested on its own. The author + // opt-out is not applied: an asserted selector outranks it, and compositionSignature applies it itself. + // clip-path is a channel, not a visibility probe, so a wipe over a static box counts as motion. + // fallow-ignore-next-line complexity + function isVisibleElement(element, style, opacity) { + if (IGNORE_TAGS.has(element.tagName)) return false; + if ( + typeof element.checkVisibility === "function" && + !element.checkVisibility(PAINTED_OPTIONS) + ) { + return false; + } + if (isHiddenStyle(style || getComputedStyle(element))) return false; + if ((opacity === undefined ? opacityChain(element) : opacity) < 0.2) return false; + const rect = element.getBoundingClientRect(); + return rect.width > 0.5 && rect.height > 0.5; + } + + function foldField(hash, value) { + hash ^= value.length; + hash = Math.imul(hash, FNV_PRIME); + for (let i = 0; i < value.length; i++) { + hash ^= value.charCodeAt(i); + hash = Math.imul(hash, FNV_PRIME); + } + return hash; + } + + function hashFields(fields) { + let hash = FNV_OFFSET_BASIS; + for (const field of fields) hash = foldField(hash, field); + return (hash >>> 0).toString(36); + } + + // `none` / `normal` are the computed initial values of content, counter-*, + // clip-path, and font-variation-settings; collapse them so unused channels + // stay "". + function cssValue(value) { + return value === "none" || value === "normal" ? "" : value || ""; + } + + // --- Per-element channels: (element, ctx) => string -------------------------- + + function boxChannel(element, ctx) { + const rect = element.getBoundingClientRect(); + const box = [rect.left, rect.top, rect.width, rect.height]; + if (ctx.quantize) { + return box.map((value) => Math.round(value / LIVENESS_POSITION_BUCKET_PX)).join(","); + } + return box.map(round).join(","); + } + + function opacityChannel(element, ctx) { + return String( + ctx.quantize ? Math.round(ctx.opacity / LIVENESS_OPACITY_BUCKET) : round(ctx.opacity), + ); + } + + // Variable-font axis animation moves no geometry and no opacity; in a + // DUPLEXED face (Recursive holds one advance width at every weight) not even + // the line width shifts, so without this channel the whole run reads frozen. + function fontAxesChannel(element, ctx) { + const axes = cssValue(ctx.style.fontVariationSettings); + return axes ? hashFields([axes]) : ""; + } + + // A clip-path wipe (inset(0 100% 0 0) → inset(0)) reveals a box that never + // moves; the computed clip-path string is the only thing that changes. + function clipPathChannel(element, ctx) { + const clip = cssValue(ctx.style.clipPath); + return clip ? hashFields([clip]) : ""; + } + + // Direct text nodes only: descendants are signed separately, and a hidden + // descendant's text mutation must not masquerade as visible motion. + function textChannel(element) { + const text = Array.from(element.childNodes) + .filter((node) => node.nodeType === 3) + .map((node) => node.textContent) + .join(""); + return text && hashFields([text]); + } + + function flag(value) { + return value ? "1" : "0"; + } + + function selectState(element) { + const fields = [String(element.selectedIndex), element.value || ""]; + for (const option of element.options) fields.push(flag(option.selected)); + return fields; + } + + // A control's value is painted by its inner (shadow) contents, which + // content-visibility: hidden skips; the widget itself (its type, a + // checkbox/radio glyph) is theme paint of the control's own box and still + // shows. Hence two channels. + const CONTROL_VALUE = { + INPUT: (element) => [element.value || ""], + TEXTAREA: (element) => [element.value || ""], + SELECT: selectState, + }; + + function controlValueChannel(element) { + const read = CONTROL_VALUE[element.tagName]; + return read ? hashFields(read(element)) : ""; + } + + function controlWidgetChannel(element) { + if (element.tagName !== "INPUT") return ""; + return hashFields([element.type || "", flag(element.checked), flag(element.indeterminate)]); + } + + // Chromium substitutes attr() in computed pseudo content, so this is the + // platform-owned rendered string rather than a CSS expression to reparse. + // counter() is NOT substituted — that is what the counter channel is for. + function generatedContentChannel(element, ctx) { + const before = cssValue(ctx.pseudo.before.content); + const after = cssValue(ctx.pseudo.after.content); + return before || after ? hashFields([before, after]) : ""; + } + + // Pixel-only media motion (canvas repaint, playing video, same-size swap) is invisible to DOM channels, + // so fold in an 8x8 downsample. Unreadable media hashes to a constant; iframe media is a separate document. + // fallow-ignore-next-line complexity + function mediaPixelChannel(element) { + if (!MEDIA_TAGS.has(element.tagName)) return ""; + try { + const rect = element.getBoundingClientRect(); + const sourceWidth = element.videoWidth || element.width || rect.width; + const sourceHeight = element.videoHeight || element.height || rect.height; + if (!sourceWidth || !sourceHeight) return "x"; + const off = document.createElement("canvas"); + off.width = 8; + off.height = 8; + const ctx2d = off.getContext("2d"); + if (!ctx2d) return "x"; + ctx2d.drawImage(element, 0, 0, 8, 8); + const data = ctx2d.getImageData(0, 0, 8, 8).data; + let hash = 0; + for (let i = 0; i < data.length; i++) hash = (hash * 31 + data[i]) >>> 0; + return String(hash); + } catch { + return "x"; + } + } + + // The element's own box still paints when its contents are skipped + // (content-visibility: hidden) — including a checkbox's check glyph; its + // text, pseudo boxes, control value, and replaced content (a canvas/video/img's + // pixels) do not. + const BOX_CHANNELS = [ + boxChannel, + opacityChannel, + fontAxesChannel, + clipPathChannel, + controlWidgetChannel, + ]; + const CONTENT_CHANNELS = [ + textChannel, + controlValueChannel, + generatedContentChannel, + mediaPixelChannel, + ]; + const ELEMENT_CHANNELS = [...BOX_CHANNELS, ...CONTENT_CHANNELS]; + + // --- Composition-level counter channel ------------------------------------ + // Counter declarations often live on zero-box owners while a pseudo-element elsewhere paints the value, so + // every box-generating element is an owner, but only declarations naming a painted counter fold in. + // The gate is by name, not scope: enough for catching frozen timelines.
    and
  1. are missed. + + // Generated content of one box owner that reaches the screen, including a list-item's ::marker. + // Callers have already excluded opted-out hosts and hosts whose contents are skipped. + function markerContent(element, style) { + if (isHiddenStyle(style) || !LIST_ITEM_DISPLAY.test(style.display)) return ""; + return cssValue(getComputedStyle(element, "::marker").content) || IMPLICIT_MARKER_CONTENT; + } + + function paintedContent(element, style, pseudo, opacity) { + if (opacity < 0.2) return []; + const boxes = [pseudo.before, pseudo.after].filter((box) => !isHiddenStyle(box)); + return [...boxes.map((box) => cssValue(box.content)), markerContent(element, style)]; + } + + // The author opt-out applies to elements INSIDE the measured root, never to + // the root itself or its ancestors: a keepsMoving scope (or the composition + // root) is explicitly asserted, and an assertion naming an element outranks + // a layout-audit opt-out — see isVisibleElement. + function isOptedOut(element, root) { + for (let current = element; current && current !== root; current = current.parentElement) { + if (current.matches(IGNORE_SELECTOR)) return true; + } + return false; + } + + function consumedCounterNames(owners) { + const names = new Set(); + for (const owner of owners) { + for (const content of owner.painted) { + for (const match of content.matchAll(COUNTER_FUNCTION)) names.add(match[1]); + } + } + return names; + } + + // `counter-reset: a 10 b 3` → does any named counter get painted? + function namesConsumedCounter(declaration, consumed) { + return declaration.split(/\s+/).some((token) => consumed.has(token)); + } + + function counterState(style, consumed) { + const fields = [style.counterReset, style.counterIncrement, style.counterSet] + .map(cssValue) + .filter((declaration) => declaration && namesConsumedCounter(declaration, consumed)); + return fields.length > 0 ? "c:" + hashFields(fields) : ""; + } + + function counterParts(root, owners) { + const consumed = consumedCounterNames(owners); + if (consumed.size === 0) return []; + const parts = []; + function push(style) { + const state = counterState(style, consumed); + if (state) parts.push(state); + } + for (let ancestor = root.parentElement; ancestor; ancestor = ancestor.parentElement) { + push(getComputedStyle(ancestor)); + } + for (const owner of owners) { + push(owner.style); + push(owner.pseudo.before); + push(owner.pseudo.after); + } + return parts; + } + + // One signature of everything under `root`, root included, that a viewer could see change between seeks. + // Opted-out elements inside the root may animate off the timeline, so they are neither signed nor counter + // consumers, but stay counter owners; the root itself is always measured. + // fallow-ignore-next-line complexity + function compositionSignature(root, options) { + if (!root) return ""; + const quantize = !!(options && options.quantize); + const parts = []; + const boxOwners = []; + // Unrendered elements paint nothing and feed no counter(). A display:contents child of a skipping host + // paints nothing either, which checkVisibility cannot tell from an ordinary one, so the parent's + // skipsContents verdict decides. A display:contents child of an off-screen `auto` host is missed. + const unrenderedBelow = new Set(); + const skippedHosts = new Set(); + for (const element of [root, ...root.querySelectorAll("*")]) { + if (IGNORE_TAGS.has(element.tagName)) continue; + const style = getComputedStyle(element); + const parent = element.parentElement; + const platformDecides = typeof element.checkVisibility === "function"; + const noBox = platformDecides + ? !element.checkVisibility(RENDERED_BOX_OPTIONS) + : style.display === "none"; + const boxlessOwner = style.display === "contents" && !skippedHosts.has(parent); + if (unrenderedBelow.has(parent) || (noBox && !boxlessOwner)) { + unrenderedBelow.add(element); + continue; + } + // A skipping host paints its box but not its contents. Its counter-* stay in: in Chromium its + // increment and set still reach a sibling's painted counter(). Off-screen `auto` hosts are missed. + const skipped = skipsContents(element, style); + if (skipped) skippedHosts.add(element); + if (skipped && !platformDecides) unrenderedBelow.add(element); + const pseudo = skipped + ? SKIPPED_PSEUDO + : { + before: getComputedStyle(element, "::before"), + after: getComputedStyle(element, "::after"), + }; + const opacity = opacityChain(element); + const optedOut = isOptedOut(element, root); + const paintsContent = !optedOut && !skipped; + boxOwners.push({ + style, + pseudo, + painted: paintsContent ? paintedContent(element, style, pseudo, opacity) : [], + }); + if (optedOut || !isVisibleElement(element, style, opacity)) continue; + const ctx = { style, pseudo, opacity, quantize }; + const channels = skipped ? BOX_CHANNELS : ELEMENT_CHANNELS; + parts.push(channels.map((channel) => channel(element, ctx)).join(",")); + } + parts.push(...counterParts(root, boxOwners)); + return parts.join("|"); + } + + window.__hyperframesMotionSignature = { + compositionRoot, + isVisibleElement, + opacityChain, + round, + compositionSignature, + }; + + // Frozen-sweep guard entry point (checkBrowser.ts collectLayoutGeometry). + // The name predates the textual/media channels and is kept for driver + // compatibility. + window.__hyperframesLayoutGeometry = function collectLayoutGeometry() { + return compositionSignature(compositionRoot(), { quantize: false }); + }; +})(); diff --git a/packages/cli/src/commands/motion-signature.browser.test.ts b/packages/cli/src/commands/motion-signature.browser.test.ts new file mode 100644 index 0000000000..264b5a72a7 --- /dev/null +++ b/packages/cli/src/commands/motion-signature.browser.test.ts @@ -0,0 +1,826 @@ +// @vitest-environment happy-dom +// fallow-ignore-file code-duplication +import { afterEach, describe, expect, it, vi } from "vitest"; +import { readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const script = readFileSync(join(__dirname, "motion-signature.browser.js"), "utf-8"); + +interface RectInput { + left: number; + top: number; + width: number; + height: number; +} + +type StyleOverride = Partial; + +interface Fixture { + /** Bounding rects keyed by element id (or lower-case tag name for id-less elements). */ + rects: Record; + /** Computed-style overrides keyed like `rects`; getters are re-read on every call. */ + styles?: Record; + /** `::before` / `::after` computed-style overrides keyed like `rects`. */ + pseudo?: Record; +} + +const BASE_STYLE: StyleOverride = { + display: "block", + visibility: "visible", + opacity: "1", + fontVariationSettings: "normal", + clipPath: "none", + counterReset: "none", + counterIncrement: "none", + counterSet: "none", +}; + +const BASE_PSEUDO_STYLE: StyleOverride = { + content: "none", + counterReset: "none", + counterIncrement: "none", + counterSet: "none", +}; + +function keyFor(element: Element): string { + return element.id || element.tagName.toLowerCase(); +} + +// A per-element fake getComputedStyle: each element reports only its own declared style, like the platform, +// so ancestor awareness (hidden subtrees, counter owners above the root) must come from the classifier. +function installFixture({ rects, styles = {}, pseudo = {} }: Fixture): void { + vi.spyOn(window, "getComputedStyle").mockImplementation((element, pseudoElement) => { + const key = keyFor(element as Element); + if (pseudoElement === "::before" || pseudoElement === "::after") { + const override = pseudoElement === "::before" ? pseudo[key]?.before : pseudo[key]?.after; + return { ...BASE_PSEUDO_STYLE, ...override } as CSSStyleDeclaration; + } + return { ...BASE_STYLE, ...styles[key] } as CSSStyleDeclaration; + }); + for (const element of Array.from(document.querySelectorAll("*"))) { + const input = rects[keyFor(element)] ?? { left: 0, top: 0, width: 0, height: 0 }; + vi.spyOn(element, "getBoundingClientRect").mockReturnValue(rect(input)); + } +} + +function rect({ left, top, width, height }: RectInput): DOMRect { + return { + left, + top, + right: left + width, + bottom: top + height, + width, + height, + x: left, + y: top, + toJSON() { + return this; + }, + } as DOMRect; +} + +interface SignatureWindow { + __hyperframesLayoutGeometry: () => string; + __hyperframesMotionSignature: { + compositionRoot(): Element; + compositionSignature(root: Element | null, options?: { quantize?: boolean }): string; + }; +} + +function signatureWindow(): SignatureWindow { + return window as unknown as SignatureWindow; +} + +function installScript(): () => string { + window.eval(script); + return signatureWindow().__hyperframesLayoutGeometry; +} + +function mockMediaPixels(read: () => number): void { + const getContextSpy = vi.spyOn(HTMLCanvasElement.prototype, "getContext") as unknown as { + mockReturnValue(value: CanvasRenderingContext2D): void; + }; + getContextSpy.mockReturnValue({ + drawImage() {}, + getImageData() { + return { data: new Uint8ClampedArray(8 * 8 * 4).fill(read()) }; + }, + } as unknown as CanvasRenderingContext2D); +} + +const ROOT = { left: 0, top: 0, width: 640, height: 360 }; +const COUNTDOWN = { left: 280, top: 140, width: 80, height: 48 }; +const ZERO_BOX = { left: 0, top: 0, width: 0, height: 0 }; +const COUNTER_CONSUMER = { after: { content: "counter(countdown)" } }; + +afterEach(() => { + vi.restoreAllMocks(); + document.body.innerHTML = ""; + Reflect.deleteProperty(window, "__hyperframesLayoutGeometry"); + Reflect.deleteProperty(window, "__hyperframesMotionSignature"); +}); + +describe("motion-signature.browser media and geometry channels", () => { + it("changes the sweep fingerprint when visible video pixels advance", () => { + document.body.innerHTML = ` +
    + +
    + `; + installFixture({ rects: { root: ROOT, footage: ROOT } }); + let pixelValue = 20; + mockMediaPixels(() => pixelValue); + + const collect = installScript(); + const before = collect(); + pixelValue = 220; + + expect(collect()).not.toBe(before); + }); + + // An equal-size opaque swap moves no geometry or opacity; only the media pixel channel sees it. + it("changes the sweep fingerprint when a same-size opaque img is swapped", () => { + document.body.innerHTML = ` +
    + +
    + `; + installFixture({ rects: { root: ROOT, frame: ROOT } }); + let pixelValue = 20; + mockMediaPixels(() => pixelValue); + + const collect = installScript(); + const before = collect(); + pixelValue = 220; + + expect(collect()).not.toBe(before); + }); + + // Opacity-only reveals (code-typing scenes) must count as motion both mid-fade and when a glyph crosses + // the 0.2 visibility floor; otherwise `check` misfires sweep_static. + it("changes the sweep fingerprint when text reveals via opacity alone", () => { + document.body.innerHTML = ` +
    +
    c
    +
    + `; + let charOpacity = "0"; + installFixture({ + rects: { + root: ROOT, + code: { left: 40, top: 40, width: 560, height: 48 }, + char: { left: 40, top: 40, width: 18, height: 48 }, + }, + styles: { + char: { + get opacity() { + return charOpacity; + }, + } as StyleOverride, + }, + }); + + const collect = installScript(); + const hidden = collect(); // below the 0.2 visibility floor — not in the signature + charOpacity = "0.5"; + const fading = collect(); // mid-fade — present, opacity part of the signature + charOpacity = "1"; + const revealed = collect(); // settled + + expect(fading).not.toBe(hidden); + expect(revealed).not.toBe(fading); + }); + + // Variable-font axis animation (registry block `weight-wave`): a crest of + // weight travels across a line of text. In a duplexed face nothing moves + // but the axis string — the fingerprint must still see it. + it("changes the sweep fingerprint when only font-variation-settings moves", () => { + document.body.innerHTML = ` +
    +
    P
    +
    + `; + let axes = '"wght" 400, "slnt" 0'; + installFixture({ + rects: { + root: ROOT, + line: { left: 40, top: 40, width: 560, height: 48 }, + char: { left: 40, top: 40, width: 18, height: 48 }, + }, + styles: { + char: { + get fontVariationSettings() { + return axes; + }, + } as StyleOverride, + }, + }); + + const collect = installScript(); + const rest = collect(); + axes = '"wght" 1000, "slnt" -12'; // the crest arrives over this character + + expect(collect()).not.toBe(rest); + }); + + // The other direction, and it guards the more dangerous failure: a + // fingerprint that varies on its own would make sweep_static unfireable and + // every green layout verdict meaningless. Identical scene, axes included, + // must hash identically. + it("keeps the sweep fingerprint identical when nothing moves, font axes included", () => { + document.body.innerHTML = ` +
    +
    P
    +
    + `; + installFixture({ + rects: { + root: ROOT, + line: { left: 40, top: 40, width: 560, height: 48 }, + char: { left: 40, top: 40, width: 18, height: 48 }, + }, + styles: { char: { fontVariationSettings: '"wght" 400, "slnt" 0' } }, + }); + + const collect = installScript(); + + expect(collect()).toBe(collect()); + }); + + it("changes the sweep fingerprint when only clip-path moves", () => { + document.body.innerHTML = ` +
    +
    +
    + `; + let clipPath = "inset(0px 100% 0px 0px)"; + installFixture({ + rects: { root: ROOT, panel: { left: 40, top: 40, width: 200, height: 100 } }, + styles: { + panel: { + get clipPath() { + return clipPath; + }, + } as StyleOverride, + }, + }); + + const collect = installScript(); + const before = collect(); + clipPath = "inset(0px 50% 0px 0px)"; + + expect(collect()).not.toBe(before); + }); + + it("ignores motion on a data-layout-ignore layer", () => { + document.body.innerHTML = ` +
    +
    + 10 +
    + `; + let left = 40; + installFixture({ rects: { root: ROOT, countdown: COUNTDOWN } }); + vi.spyOn(document.getElementById("glow")!, "getBoundingClientRect").mockImplementation(() => + rect({ left, top: 40, width: 100, height: 100 }), + ); + + const collect = installScript(); + const before = collect(); + left = 200; + + expect(collect()).toBe(before); + }); + + it("measures a root that is itself data-layout-ignore while still excluding opted-out layers inside it", () => { + document.body.innerHTML = ` +
    +
    + +
    +
    +
    + `; + let logoLeft = 40; + let glowLeft = 40; + installFixture({ rects: { root: ROOT, scene: { left: 0, top: 0, width: 300, height: 200 } } }); + vi.spyOn(document.getElementById("logo")!, "getBoundingClientRect").mockImplementation(() => + rect({ left: logoLeft, top: 40, width: 50, height: 50 }), + ); + vi.spyOn(document.getElementById("glow")!, "getBoundingClientRect").mockImplementation(() => + rect({ left: glowLeft, top: 40, width: 50, height: 50 }), + ); + installScript(); + const { compositionSignature } = signatureWindow().__hyperframesMotionSignature; + const scene = document.getElementById("scene")!; + + const before = compositionSignature(scene); + expect(before).not.toBe(""); + glowLeft = 200; + expect(compositionSignature(scene)).toBe(before); + logoLeft = 200; + expect(compositionSignature(scene)).not.toBe(before); + }); + + it("buckets sub-threshold moves out of the quantized liveness signature only", () => { + document.body.innerHTML = ` +
    +
    +
    + `; + let left = 100; + installFixture({ rects: { root: ROOT } }); + vi.spyOn(document.getElementById("box")!, "getBoundingClientRect").mockImplementation(() => + rect({ left, top: 100, width: 50, height: 50 }), + ); + installScript(); + const { compositionSignature, compositionRoot } = + signatureWindow().__hyperframesMotionSignature; + const root = compositionRoot(); + + const exactBefore = compositionSignature(root); + const bucketedBefore = compositionSignature(root, { quantize: true }); + left = 100.6; // moves, but stays inside the 2px liveness bucket + + expect(compositionSignature(root)).not.toBe(exactBefore); + expect(compositionSignature(root, { quantize: true })).toBe(bucketedBefore); + }); +}); + +describe("motion-signature.browser textual channels", () => { + it("changes the sweep fingerprint when fixed-width text content changes", () => { + document.body.innerHTML = ` +
    + 10 +
    + `; + installFixture({ rects: { root: ROOT, countdown: COUNTDOWN } }); + + const collect = installScript(); + const before = collect(); + document.getElementById("countdown")!.textContent = "09"; + + expect(collect()).not.toBe(before); + }); + + it("ignores text mutations inside a display:none descendant", () => { + document.body.innerHTML = ` +
    + 1010 +
    + `; + installFixture({ + rects: { root: ROOT, countdown: COUNTDOWN, hidden: COUNTDOWN }, + styles: { hidden: { display: "none" } }, + }); + + const collect = installScript(); + const before = collect(); + document.getElementById("hidden")!.textContent = "09"; + + expect(collect()).toBe(before); + }); + + it("changes the sweep fingerprint when the composition root's own text changes", () => { + document.body.innerHTML = ` +
    10
    + `; + installFixture({ rects: { root: ROOT } }); + + const collect = installScript(); + const before = collect(); + document.getElementById("root")!.textContent = "09"; + + expect(collect()).not.toBe(before); + }); + + it("changes the sweep fingerprint when an attr-backed data value changes", () => { + document.body.innerHTML = ` +
    + +
    + `; + installFixture({ + rects: { root: ROOT, countdown: COUNTDOWN }, + pseudo: { + countdown: { + after: { + // Chromium substitutes attr() in computed pseudo content. + get content() { + return JSON.stringify(document.getElementById("countdown")!.getAttribute("data-txt")); + }, + } as StyleOverride, + }, + }, + }); + + const collect = installScript(); + const before = collect(); + document.getElementById("countdown")!.setAttribute("data-txt", "09"); + + expect(collect()).not.toBe(before); + }); + + it("changes the sweep fingerprint when pseudo-element content changes", () => { + document.body.innerHTML = ` +
    + +
    + `; + let generatedContent = '"10"'; + installFixture({ + rects: { root: ROOT, countdown: COUNTDOWN }, + pseudo: { + countdown: { + after: { + get content() { + return generatedContent; + }, + } as StyleOverride, + }, + }, + }); + + const collect = installScript(); + const before = collect(); + generatedContent = '"09"'; + + expect(collect()).not.toBe(before); + }); + + it("changes the sweep fingerprint when checkbox state changes", () => { + document.body.innerHTML = ` +
    + +
    + `; + installFixture({ + rects: { root: ROOT, toggle: { left: 280, top: 140, width: 24, height: 24 } }, + }); + + const collect = installScript(); + const before = collect(); + (document.getElementById("toggle") as HTMLInputElement).checked = true; + + expect(collect()).not.toBe(before); + }); + + it("changes the sweep fingerprint when a checkbox becomes indeterminate", () => { + document.body.innerHTML = ` +
    + +
    + `; + installFixture({ + rects: { root: ROOT, toggle: { left: 280, top: 140, width: 24, height: 24 } }, + }); + + const collect = installScript(); + const before = collect(); + (document.getElementById("toggle") as HTMLInputElement).indeterminate = true; + + expect(collect()).not.toBe(before); + }); + + it("changes the sweep fingerprint when a secondary select option changes", () => { + document.body.innerHTML = ` +
    + +
    + `; + installFixture({ + rects: { root: ROOT, choices: { left: 280, top: 140, width: 120, height: 48 } }, + }); + + const collect = installScript(); + const before = collect(); + (document.getElementById("choices") as HTMLSelectElement).options[1]!.selected = true; + + expect(collect()).not.toBe(before); + }); + + it("changes the sweep fingerprint when a fixed-width form value changes", () => { + document.body.innerHTML = ` +
    + +
    + `; + installFixture({ rects: { root: ROOT, countdown: COUNTDOWN } }); + + const collect = installScript(); + const before = collect(); + (document.getElementById("countdown") as HTMLInputElement).value = "09"; + + expect(collect()).not.toBe(before); + }); + + it("changes the sweep fingerprint when a textarea value changes", () => { + document.body.innerHTML = ` +
    + +
    + `; + installFixture({ rects: { root: ROOT, countdown: COUNTDOWN } }); + + const collect = installScript(); + const before = collect(); + (document.getElementById("countdown") as HTMLTextAreaElement).value = "09"; + + expect(collect()).not.toBe(before); + }); + + it("keeps textual sweep channels identical when the countdown is truly frozen", () => { + document.body.innerHTML = ` +
    + 10 +
    + `; + installFixture({ + rects: { root: ROOT, countdown: COUNTDOWN }, + styles: { countdown: { counterReset: "countdown 10" } }, + pseudo: { countdown: { after: { content: '"10"' } } }, + }); + + const collect = installScript(); + + expect(collect()).toBe(collect()); + }); +}); + +describe("motion-signature.browser counter channel", () => { + it("changes the sweep fingerprint when a zero-box owner's counter state changes", () => { + document.body.innerHTML = ` +
    +
    +
    + `; + let counterReset = "countdown 10"; + installFixture({ + rects: { root: ROOT, "counter-owner": ZERO_BOX, countdown: COUNTDOWN }, + styles: { + "counter-owner": { + get counterReset() { + return counterReset; + }, + } as StyleOverride, + }, + pseudo: { countdown: COUNTER_CONSUMER }, + }); + + const collect = installScript(); + const before = collect(); + counterReset = "countdown 9"; + + expect(collect()).not.toBe(before); + }); + + it("changes the sweep fingerprint when a counter owned above the composition root changes", () => { + document.body.innerHTML = ` +
    + +
    + `; + let counterReset = "countdown 10"; + installFixture({ + rects: { root: ROOT, countdown: COUNTDOWN }, + styles: { + body: { + get counterReset() { + return counterReset; + }, + } as StyleOverride, + }, + pseudo: { countdown: COUNTER_CONSUMER }, + }); + + const collect = installScript(); + const before = collect(); + counterReset = "countdown 9"; + + expect(collect()).not.toBe(before); + }); + + it("changes the sweep fingerprint when a pseudo-element's own counter-increment changes", () => { + document.body.innerHTML = ` +
    + +
    + `; + let counterIncrement = "countdown 10"; + installFixture({ + rects: { root: ROOT, countdown: COUNTDOWN }, + pseudo: { + countdown: { + after: { + content: "counter(countdown)", + get counterIncrement() { + return counterIncrement; + }, + } as StyleOverride, + }, + }, + }); + + const collect = installScript(); + const before = collect(); + counterIncrement = "countdown 9"; + + expect(collect()).not.toBe(before); + }); + + it("changes the sweep fingerprint when a zero-box host's own pseudo-element paints the counter", () => { + document.body.innerHTML = ` +
    +
    +
    + `; + let counterReset = "countdown 10"; + installFixture({ + rects: { root: ROOT, host: ZERO_BOX }, + styles: { + body: { + get counterReset() { + return counterReset; + }, + } as StyleOverride, + }, + pseudo: { host: COUNTER_CONSUMER }, + }); + + const collect = installScript(); + const before = collect(); + counterReset = "countdown 9"; + + expect(collect()).not.toBe(before); + }); + + it("ignores a zero-box decoy whose counter name nothing paints even when a list marker exists", () => { + document.body.innerHTML = ` +
    +
    • item
    +
    +
    + `; + let counterReset = "decoy 10"; + installFixture({ + rects: { root: ROOT, item: COUNTDOWN, decoy: ZERO_BOX }, + styles: { + item: { display: "list-item" }, + decoy: { + get counterReset() { + return counterReset; + }, + } as StyleOverride, + }, + }); + + const collect = installScript(); + const before = collect(); + counterReset = "decoy 9"; + + expect(collect()).toBe(before); + }); + + it("ignores a counter consumed only under a data-layout-ignore layer", () => { + document.body.innerHTML = ` +
    +
    +
    +
    + `; + let counterReset = "countdown 10"; + installFixture({ + rects: { root: ROOT, "counter-owner": ZERO_BOX, countdown: COUNTDOWN }, + styles: { + "counter-owner": { + get counterReset() { + return counterReset; + }, + } as StyleOverride, + }, + pseudo: { countdown: COUNTER_CONSUMER }, + }); + + const collect = installScript(); + const before = collect(); + counterReset = "countdown 9"; + + expect(collect()).toBe(before); + }); + + it("keeps a visibility:hidden owner whose counter feeds a visible consumer", () => { + document.body.innerHTML = ` +
    +
    +
    + `; + let counterReset = "countdown 10"; + installFixture({ + rects: { root: ROOT, "counter-owner": COUNTDOWN, countdown: COUNTDOWN }, + styles: { + "counter-owner": { + visibility: "hidden", + get counterReset() { + return counterReset; + }, + } as StyleOverride, + }, + pseudo: { countdown: COUNTER_CONSUMER }, + }); + + const collect = installScript(); + const before = collect(); + counterReset = "countdown 9"; + + expect(collect()).not.toBe(before); + }); + + // A display:none element generates no box, so its counters cannot reach any + // painted counter() — a varying counter-reset there must not make a frozen + // composition read as live. + it("ignores a display:none decoy counter owner in a frozen composition", () => { + document.body.innerHTML = ` +
    +
    + +
    + `; + let counterReset = "countdown 10"; + installFixture({ + rects: { root: ROOT, decoy: ZERO_BOX, countdown: COUNTDOWN }, + styles: { + decoy: { + display: "none", + get counterReset() { + return counterReset; + }, + } as StyleOverride, + }, + pseudo: { countdown: COUNTER_CONSUMER }, + }); + + const collect = installScript(); + const before = collect(); + counterReset = "countdown 9"; + + expect(collect()).toBe(before); + }); + + it("ignores a decoy counter owner nested inside a display:none subtree", () => { + document.body.innerHTML = ` +
    +
    + +
    + `; + let counterReset = "countdown 10"; + installFixture({ + rects: { root: ROOT, "hidden-parent": ZERO_BOX, decoy: ZERO_BOX, countdown: COUNTDOWN }, + styles: { + "hidden-parent": { display: "none" }, + // The decoy itself computes display:block — only its ancestry hides it. + decoy: { + display: "block", + get counterReset() { + return counterReset; + }, + } as StyleOverride, + }, + pseudo: { countdown: COUNTER_CONSUMER }, + }); + + const collect = installScript(); + const before = collect(); + counterReset = "countdown 9"; + + expect(collect()).toBe(before); + }); + + it("ignores counter declarations when no visible generated content consumes a counter", () => { + document.body.innerHTML = ` +
    +
    + 10 +
    + `; + let counterReset = "countdown 10"; + installFixture({ + rects: { root: ROOT, "counter-owner": ZERO_BOX, countdown: COUNTDOWN }, + styles: { + "counter-owner": { + get counterReset() { + return counterReset; + }, + } as StyleOverride, + }, + }); + + const collect = installScript(); + const before = collect(); + counterReset = "countdown 9"; + + expect(collect()).toBe(before); + }); +}); diff --git a/packages/cli/src/commands/preview.test.ts b/packages/cli/src/commands/preview.test.ts index 862465622c..51c5a1469e 100644 --- a/packages/cli/src/commands/preview.test.ts +++ b/packages/cli/src/commands/preview.test.ts @@ -1,11 +1,15 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; import * as clack from "@clack/prompts"; import { afterEach, describe, expect, it, vi } from "vitest"; import { runCommand } from "citty"; +import { PreviewServerPortMismatchError } from "../utils/studioSelectionClient.js"; +import { PreviewPortUnavailableError } from "./previewLifecycle.js"; import { default as previewCommand, + backgroundStartFailureCode, foregroundPreviewReadyPayload, prebuildPreview, handlePreviewKillAll, @@ -368,6 +372,14 @@ describe("preview lifecycle JSON failures", () => { expect(error).not.toHaveBeenCalled(); }); + it.each([ + [new PreviewServerPortMismatchError(3500, []), "preview-port-mismatch"], + [new PreviewPortUnavailableError(3500, 3501), "preview-port-unavailable"], + [new Error("spawn failed"), "preview-start-failed"], + ])("maps a background start failure to its JSON code (%#)", (error, code) => { + expect(backgroundStartFailureCode(error)).toBe(code); + }); + it("wraps missing-project start failures without human stderr", async () => { const missing = join(tmpdir(), `hf-preview-missing-start-${process.pid}-${Date.now()}`); const log = vi.spyOn(console, "log").mockImplementation(() => {}); @@ -484,8 +496,21 @@ describe("waitForStudioChildClose", () => { await expect(waitForStudioChildClose(child, signalTarget)).resolves.toBeUndefined(); expect(child.once).not.toHaveBeenCalled(); - expect(signalTarget.once).toHaveBeenCalledTimes(2); - expect(signalTarget.off).toHaveBeenCalledTimes(2); + expect(signalTarget.once).toHaveBeenCalledTimes(3); + expect(signalTarget.off).toHaveBeenCalledTimes(3); + }); + + it("reaps the dev server when the terminal closes (SIGHUP)", async () => { + const signalTarget = { once: vi.fn(), off: vi.fn() }; + const child = { exitCode: 0, signalCode: null, once: vi.fn() } as unknown as Parameters< + typeof waitForStudioChildClose + >[0]; + + await waitForStudioChildClose(child, signalTarget); + + const hupListener = signalTarget.once.mock.calls.find(([event]) => event === "SIGHUP")?.[1]; + expect(hupListener).toBeTypeOf("function"); + expect(signalTarget.off).toHaveBeenCalledWith("SIGHUP", hupListener); }); it("reaps on process exit even when stdio never emits close", async () => { @@ -511,6 +536,68 @@ describe("waitForStudioChildClose", () => { exit?.(); await waiting; expect(resolved).toBe(true); - expect(signalTarget.off).toHaveBeenCalledTimes(2); + expect(signalTarget.off).toHaveBeenCalledTimes(3); + }); +}); + +describe("studio dev-server spawns", () => { + function fakeStudioChild() { + return { + pid: 4321, + exitCode: 0, + signalCode: null, + stdout: { on: vi.fn(), removeListener: vi.fn() }, + stderr: { on: vi.fn(), removeListener: vi.fn() }, + on: vi.fn(), + once: vi.fn(), + }; + } + + // Returns the spawn spy. mkdirSync/existsSync are stubbed too, so + // linkProjectIntoStudioData never touches the real studio data directory. + function mockStudioSpawn() { + const spawn = vi.fn((_command: string, _args: string[], _options: unknown) => + fakeStudioChild(), + ); + vi.doMock("node:child_process", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, spawn }; + }); + vi.doMock("node:fs", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, mkdirSync: () => undefined, existsSync: () => true }; + }); + vi.resetModules(); + return spawn; + } + + afterEach(() => { + vi.doUnmock("node:child_process"); + vi.doUnmock("node:fs"); + vi.resetModules(); + }); + + it("runDevMode passes windowsHide to the studio dev-server spawn", async () => { + const spawn = mockStudioSpawn(); + + const { runDevMode } = await import("./preview.js"); + await runDevMode("/tmp/hf-preview-devmode-test", { json: true }); + + expect(spawn).toHaveBeenCalledOnce(); + expect(spawn.mock.calls[0]?.[2]).toMatchObject({ windowsHide: true }); + }); + + it("runLocalStudioMode passes windowsHide to the local Vite spawn", async () => { + const spawn = mockStudioSpawn(); + + // @hyperframes/studio is resolved for real, so the project dir has to sit + // inside the monorepo's node_modules tree. + const thisFile = fileURLToPath(import.meta.url); + const localStudioProjectDir = resolve(dirname(thisFile), "..", ".."); + const { runLocalStudioMode } = await import("./preview.js"); + await runLocalStudioMode(localStudioProjectDir, { json: true }); + + expect(spawn).toHaveBeenCalledOnce(); + expect(spawn.mock.calls[0]?.[2]).toMatchObject({ windowsHide: true }); }); }); diff --git a/packages/cli/src/commands/preview.ts b/packages/cli/src/commands/preview.ts index c453dec680..a134b2615a 100644 --- a/packages/cli/src/commands/preview.ts +++ b/packages/cli/src/commands/preview.ts @@ -62,7 +62,9 @@ import { killOrphanedProcesses, killProcessTree } from "../utils/orphanCleanup.j import { resolveProject, resolveProjectOrThrow } from "../utils/project.js"; import { resolveAutoProxy } from "../utils/projectConfig.js"; import { studioProxyEnv } from "../utils/studioProxyEnv.js"; +import { PreviewServerPortMismatchError } from "../utils/studioSelectionClient.js"; import { + PreviewPortUnavailableError, listBackgroundPreviewStatuses, readBackgroundPreviewStatus, startBackgroundPreview, @@ -100,9 +102,11 @@ interface EmbeddedStudioOptions extends StudioLaunchOptions { } type StudioChildProcess = ChildProcessByStdio; +const STUDIO_CHILD_SHUTDOWN_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"] as const; +type StudioShutdownSignal = (typeof STUDIO_CHILD_SHUTDOWN_SIGNALS)[number]; interface StudioSignalTarget { - once(event: "SIGINT" | "SIGTERM", listener: () => void): unknown; - off(event: "SIGINT" | "SIGTERM", listener: () => void): unknown; + once(event: StudioShutdownSignal, listener: () => void): unknown; + off(event: StudioShutdownSignal, listener: () => void): unknown; } type ContextField = "server" | "selection" | "lint" | "capabilities"; type CompactSelectionPayload = Pick< @@ -122,6 +126,14 @@ type CompactSelectionPayload = Pick< const DEFAULT_CONTEXT_FIELDS: ContextField[] = ["server", "selection", "lint", "capabilities"]; +const PREVIEW_PORT_MISMATCH_CODE = "preview-port-mismatch"; + +export function backgroundStartFailureCode(error: unknown): string { + if (error instanceof PreviewServerPortMismatchError) return PREVIEW_PORT_MISMATCH_CODE; + if (error instanceof PreviewPortUnavailableError) return "preview-port-unavailable"; + return "preview-start-failed"; +} + export default defineCommand({ meta: { name: "preview", @@ -297,7 +309,7 @@ export default defineCommand({ if (args["browser-gpu"] === true) process.env.PRODUCER_BROWSER_GPU_MODE = "hardware"; if (args["browser-gpu"] === false) process.env.PRODUCER_BROWSER_GPU_MODE = "software"; const startPort = parseInt(args.port ?? "3002", 10); - const preferredContextPort = hasExplicitPreviewPort(process.argv) ? startPort : undefined; + const explicitPort = hasExplicitPreviewPort(process.argv) ? startPort : undefined; if (args.status || args.stop) { try { @@ -386,18 +398,13 @@ export default defineCommand({ json: Boolean(args.json), fields: args["context-fields"] as string | undefined, detail: args["context-detail"] as string | undefined, - ...(preferredContextPort === undefined ? {} : { preferredPort: preferredContextPort }), + preferredPort: explicitPort, }); } if (args.selection) { const project = resolveProject(args.dir); - return printCurrentSelection( - project.dir, - startPort, - Boolean(args.json), - preferredContextPort, - ); + return printCurrentSelection(project.dir, startPort, Boolean(args.json), explicitPort); } const rawArg = args.dir; @@ -500,11 +507,14 @@ export default defineCommand({ // the existing managed server resolved earlier. Only an explicit // --browser-gpu/--no-browser-gpu request authorizes replacement. browserGpuMode: args["browser-gpu"] === undefined ? undefined : browserGpuMode, + preferredPort: explicitPort, }); } catch (error) { const message = errorMessage(error); if (args.json) { - writeLifecycleJson(lifecycleFailurePayload("start", "preview-start-failed", message)); + writeLifecycleJson( + lifecycleFailurePayload("start", backgroundStartFailureCode(error), message), + ); } else { clack.log.error(message); } @@ -921,7 +931,7 @@ async function printCurrentSelection( return; } if (err instanceof PreviewServerPortMismatchError) { - printSelectionFailure("preview-port-mismatch", err.message, json); + printSelectionFailure(PREVIEW_PORT_MISMATCH_CODE, err.message, json); return; } throw err; @@ -1043,7 +1053,7 @@ async function printCurrentContext( return; } if (err instanceof PreviewServerPortMismatchError) { - printSelectionFailure("preview-port-mismatch", err.message, options.json); + printSelectionFailure(PREVIEW_PORT_MISMATCH_CODE, err.message, options.json); return; } throw err; @@ -1337,8 +1347,7 @@ export function waitForStudioChildClose( const shutdown = (): void => { if (child.pid) killProcessTree(child.pid); }; - signalTarget.once("SIGINT", shutdown); - signalTarget.once("SIGTERM", shutdown); + for (const signal of STUDIO_CHILD_SHUTDOWN_SIGNALS) signalTarget.once(signal, shutdown); // A short-lived Vite child can exit before launch setup reaches this point. // ChildProcess does not replay lifecycle events to listeners attached later, @@ -1355,8 +1364,7 @@ export function waitForStudioChildClose( return closed.finally(() => { // Signal listeners keep Bun's event loop alive even after Vite exits. Leaving // them registered makes `preview --stop` close the port but leak the wrapper. - signalTarget.off("SIGINT", shutdown); - signalTarget.off("SIGTERM", shutdown); + for (const signal of STUDIO_CHILD_SHUTDOWN_SIGNALS) signalTarget.off(signal, shutdown); }); } @@ -1422,7 +1430,7 @@ export function reportPreviewShutdown(json: boolean): void { /** * Dev mode: spawn the studio dev server from the monorepo. */ -async function runDevMode(dir: string, options?: StudioLaunchOptions): Promise { +export async function runDevMode(dir: string, options?: StudioLaunchOptions): Promise { // Find monorepo root by navigating from packages/cli/src/commands/ const thisFile = fileURLToPath(import.meta.url); const repoRoot = resolve(dirname(thisFile), "..", "..", "..", ".."); @@ -1442,6 +1450,7 @@ async function runDevMode(dir: string, options?: StudioLaunchOptions): Promise { +export async function runLocalStudioMode( + dir: string, + options?: StudioLaunchOptions, +): Promise { const req = createRequire(join(dir, "package.json")); const studioPkgPath = dirname(req.resolve("@hyperframes/studio/package.json")); const pName = options?.projectName ?? basename(dir); @@ -1504,6 +1516,7 @@ async function runLocalStudioMode(dir: string, options?: StudioLaunchOptions): P const child = spawn(viteCommand.command, viteCommand.args, { cwd: studioPkgPath, stdio: ["ignore", "pipe", "pipe"], + windowsHide: true, env: studioProxyEnv(options?.autoProxy ?? true, process.env, { projectDir: dir, projectName: pName, diff --git a/packages/cli/src/commands/previewLifecycle.test.ts b/packages/cli/src/commands/previewLifecycle.test.ts index fe737754e7..57b1ebfc71 100644 --- a/packages/cli/src/commands/previewLifecycle.test.ts +++ b/packages/cli/src/commands/previewLifecycle.test.ts @@ -3,7 +3,9 @@ import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { describe, expect, it, onTestFinished, vi } from "vitest"; import type { ActiveServer } from "../server/portUtils.js"; +import { PreviewServerPortMismatchError } from "../utils/studioSelectionClient.js"; import { + PreviewPortUnavailableError, buildBackgroundPreviewArgs, listBackgroundPreviewStatuses, previewSessionPath, @@ -35,6 +37,26 @@ function savePreviewSession(stateHome: string): void { ); } +/** Launch deps whose wrapper (PID 4321) brings up `server` (PID 9876) on spawn and takes it down on kill. */ +function reachableChildDependencies(stateHome: string, { immortal = false } = {}) { + let spawned = false; + let killed = false; + const liveServer = { ...server, pid: "9876" }; + return { + scan: async () => (spawned && (immortal || !killed) ? [liveServer] : []), + spawn: () => { + spawned = true; + return { pid: 4321, unref: vi.fn() }; + }, + sleep: async () => {}, + kill: vi.fn(() => { + killed = true; + }), + isDescendant: (child: number, ancestor: number) => child === 9876 && ancestor === 4321, + stateHome, + }; +} + async function expectStaleSessionRemoved(stateHome: string): Promise { const status = await readBackgroundPreviewStatus(projectDir, 3002, { scan: async () => [], @@ -65,7 +87,21 @@ describe("background preview lifecycle", () => { "--open", "--json", ]), - ).toEqual(["/opt/hyperframes/cli.js", "preview", projectDir, "--foreground", "--no-open"]); + ).toEqual([ + "/opt/hyperframes/cli.js", + "preview", + projectDir, + "--foreground", + "--no-open", + "--force-new", + ]); + }); + + it("makes the detached child start its own server, never reuse a sibling launch's", () => { + const args = buildBackgroundPreviewArgs(["cli.js", "preview", projectDir, "--force-new"]); + + expect(args.filter((arg) => arg === "--force-new")).toHaveLength(1); + expect(args.at(-1)).toBe("--force-new"); }); it("reuses an already-running server for the same project", async () => { @@ -105,6 +141,36 @@ describe("background preview lifecycle", () => { expect(spawn).not.toHaveBeenCalled(); }); + it("throws a port-mismatch error when the caller explicitly requests a port the reused server isn't on", async () => { + const spawn = vi.fn(); + const scan = vi.fn(async () => [server]); + + await expect( + startBackgroundPreview(projectDir, 3002, { + scan, + spawn, + stateHome: mkdtempSync(join(tmpdir(), "hf-preview-state-")), + preferredPort: server.port + 1, + }), + ).rejects.toThrow(PreviewServerPortMismatchError); + expect(spawn).not.toHaveBeenCalled(); + }); + + it("reuses normally when the caller's explicit port matches the reused server", async () => { + const spawn = vi.fn(); + const scan = vi.fn(async () => [server]); + + const result = await startBackgroundPreview(projectDir, 3002, { + scan, + spawn, + stateHome: mkdtempSync(join(tmpdir(), "hf-preview-state-")), + preferredPort: server.port, + }); + + expect(result).toMatchObject({ type: "reused", port: server.port }); + expect(spawn).not.toHaveBeenCalled(); + }); + it("discovers managed previews outside the default port scan and removes stale records", async () => { const stateHome = tempDir("hf-preview-state-"); const otherProjectDir = resolve("/tmp/hyperframes-preview-managed-custom-port"); @@ -376,6 +442,7 @@ describe("background preview lifecycle", () => { spawned = true; return { pid: 4321, unref: vi.fn() }; }, + isDescendant: (child, ancestor) => child === 9876 && ancestor === 4321, stateHome, }); @@ -385,6 +452,236 @@ describe("background preview lifecycle", () => { ).toMatchObject({ pid: 4321 }); }); + it("reports the explicitly requested port when the detached child binds it", async () => { + const stateHome = mkdtempSync(join(tmpdir(), "hf-preview-state-")); + const dependencies = reachableChildDependencies(stateHome); + + const result = await startBackgroundPreview(projectDir, server.port, { + ...dependencies, + preferredPort: server.port, + }); + + expect(result).toMatchObject({ type: "started", port: server.port, pid: 9876 }); + expect(dependencies.kill).not.toHaveBeenCalled(); + expect(existsSync(previewSessionPath(projectDir, stateHome))).toBe(true); + }); + + it("reaps a detached child that could not bind the explicitly requested port", async () => { + // The child scans upward from --port and lands on the next free port. + const requestedPort = server.port - 1; + const stateHome = mkdtempSync(join(tmpdir(), "hf-preview-state-")); + const dependencies = reachableChildDependencies(stateHome); + + const launch = startBackgroundPreview(projectDir, requestedPort, { + ...dependencies, + preferredPort: requestedPort, + }); + + await expect(launch).rejects.toThrow(PreviewPortUnavailableError); + await expect(launch).rejects.toMatchObject({ requestedPort, boundPort: server.port }); + // The wrapper PID is reaped, not the server's self-reported PID. + expect(dependencies.kill).toHaveBeenCalledExactlyOnceWith(4321); + expect(existsSync(previewSessionPath(projectDir, stateHome))).toBe(false); + }); + + it("fails loudly when the reaped child keeps serving the substitute port", async () => { + const requestedPort = server.port - 1; + const stateHome = mkdtempSync(join(tmpdir(), "hf-preview-state-")); + const dependencies = reachableChildDependencies(stateHome, { immortal: true }); + + await expect( + startBackgroundPreview(projectDir, requestedPort, { + ...dependencies, + preferredPort: requestedPort, + }), + ).rejects.toThrow(/did not stop after failing to bind port/); + expect(dependencies.kill).toHaveBeenCalledExactlyOnceWith(4321); + expect(existsSync(previewSessionPath(projectDir, stateHome))).toBe(false); + }); + + it("two launches at once each keep the server their own child started", async () => { + const stateHome = mkdtempSync(join(tmpdir(), "hf-preview-state-")); + // A's server (3002) answers only after B's (3003) has appeared, and after A's pre-launch snapshot. + const children: Record = { + 4321: { ...server, port: 3002, pid: "9876", after: 3 }, + 5555: { ...server, port: 3003, pid: "7777", after: 0 }, + }; + const parent: Record = { 9876: 4321, 7777: 5555 }; + const spawnedAt = new Map(); + let scans = 0; + let secondSpawned!: () => void; + const secondUp = new Promise((done) => (secondSpawned = done)); + const scan = async () => { + scans++; + return [...spawnedAt] + .filter(([wrapper, at]) => scans - at > children[wrapper]!.after) + .map(([wrapper]) => children[wrapper]!); + }; + const launch = (wrapper: number, sleep: () => Promise, preferredPort?: number) => + startBackgroundPreview(projectDir, 3002, { + scan, + spawn: () => { + spawnedAt.set(wrapper, scans); + if (wrapper === 5555) secondSpawned(); + return { pid: wrapper, unref: vi.fn() }; + }, + sleep, + kill: vi.fn(), + isDescendant: (child: number, ancestor: number) => parent[child] === ancestor, + stateHome, + preferredPort, + }); + + const first = launch(4321, () => secondUp, 3002); + await vi.waitFor(() => expect(spawnedAt.has(4321)).toBe(true)); + const second = launch(5555, async () => {}); + + await expect(first).resolves.toMatchObject({ type: "started", port: 3002, pid: 9876 }); + await expect(second).resolves.toMatchObject({ type: "started", port: 3003, pid: 7777 }); + }); + + it("keeps the next free port when no explicit port was requested", async () => { + const stateHome = mkdtempSync(join(tmpdir(), "hf-preview-state-")); + const dependencies = reachableChildDependencies(stateHome); + + const result = await startBackgroundPreview(projectDir, server.port - 1, dependencies); + + expect(result).toMatchObject({ type: "started", port: server.port }); + expect(dependencies.kill).not.toHaveBeenCalled(); + }); + + it("reuses the same-project server on the explicit port when several are running", async () => { + const sibling = { ...server, port: server.port + 1, pid: "5555" }; + const spawn = vi.fn(); + + const result = await startBackgroundPreview(projectDir, 3002, { + scan: async () => [server, sibling], + spawn, + stateHome: mkdtempSync(join(tmpdir(), "hf-preview-state-")), + preferredPort: sibling.port, + }); + + expect(result).toMatchObject({ type: "reused", port: sibling.port, pid: 5555 }); + expect(spawn).not.toHaveBeenCalled(); + }); + + it("reuses the unmanaged sibling on the explicit port instead of rejecting against the owned server", async () => { + const stateHome = mkdtempSync(join(tmpdir(), "hf-preview-state-")); + const owned = { ...server, port: 3002 }; + const sibling = { ...server, port: 3003, pid: "5555" }; + writePreviewSession( + { pid: 4321, port: owned.port, projectDir, logPath: "/tmp/preview.log" }, + stateHome, + ); + const spawn = vi.fn(); + const kill = vi.fn(); + + const result = await startBackgroundPreview(projectDir, 3002, { + kill, + scan: async () => [owned, sibling], + spawn, + stateHome, + preferredPort: sibling.port, + }); + + expect(result).toMatchObject({ type: "reused", port: sibling.port, pid: 5555 }); + expect(spawn).not.toHaveBeenCalled(); + expect(kill).not.toHaveBeenCalled(); + }); + + it("lists every same-project server in the port-mismatch error, not just the reuse candidate", async () => { + const stateHome = mkdtempSync(join(tmpdir(), "hf-preview-state-")); + const owned = { ...server, port: 3002 }; + const sibling = { ...server, port: 3003, pid: "5555" }; + const foreign = { + ...server, + port: 3004, + projectDir: resolve("/tmp/hyperframes-preview-lifecycle-other"), + pid: "7777", + }; + writePreviewSession( + { pid: 4321, port: owned.port, projectDir, logPath: "/tmp/preview.log" }, + stateHome, + ); + const spawn = vi.fn(); + + const failure = await startBackgroundPreview(projectDir, 3002, { + scan: async () => [owned, sibling, foreign], + spawn, + stateHome, + preferredPort: 3004, + }).then( + () => null, + (error: unknown) => error, + ); + + expect(failure).toBeInstanceOf(PreviewServerPortMismatchError); + expect(failure).toMatchObject({ requestedPort: 3004, ports: [3002, 3003] }); + expect((failure as Error).message).toContain("add --force-new or run --stop first"); + expect(spawn).not.toHaveBeenCalled(); + }); + + it("reuses a same-project server on an explicit port outside the saved port's scan window", async () => { + const stateHome = mkdtempSync(join(tmpdir(), "hf-preview-state-")); + const owned = { ...server, port: 3002 }; + const farSibling = { ...server, port: 3500, pid: "5555" }; + writePreviewSession( + { pid: 4321, port: owned.port, projectDir, logPath: "/tmp/preview.log" }, + stateHome, + ); + const spawn = vi.fn(); + const probe = vi.fn(async (port: number) => (port === farSibling.port ? farSibling : null)); + + const result = await startBackgroundPreview(projectDir, farSibling.port, { + scan: async () => [owned], + probe, + spawn, + stateHome, + preferredPort: farSibling.port, + }); + + expect(result).toMatchObject({ type: "reused", port: farSibling.port, pid: 5555 }); + expect(probe).toHaveBeenCalledExactlyOnceWith(farSibling.port); + expect(spawn).not.toHaveBeenCalled(); + }); + + it("replaces the owned server on the explicit port when the GPU policy changes", async () => { + const stateHome = mkdtempSync(join(tmpdir(), "hf-preview-state-")); + const owned = { ...server, port: 3002, browserGpuMode: "hardware" as const }; + const replacement = { ...server, port: 3002, pid: "5432", browserGpuMode: "software" as const }; + writePreviewSession( + { pid: 4321, port: owned.port, projectDir, logPath: "/tmp/preview.log" }, + stateHome, + ); + let ownedRunning = true; + let replacementRunning = false; + const scan = vi.fn(async () => [ + ...(ownedRunning ? [owned] : []), + ...(replacementRunning ? [replacement] : []), + ]); + const kill = vi.fn((pid: number) => { + if (pid === 4321) ownedRunning = false; + }); + const spawn = vi.fn(() => { + replacementRunning = true; + return { pid: 5432, unref: vi.fn() }; + }); + + const result = await startBackgroundPreview(projectDir, 3002, { + browserGpuMode: "software", + kill, + scan, + sleep: async () => {}, + spawn, + stateHome, + preferredPort: 3002, + }); + + expect(kill).toHaveBeenCalledWith(4321); + expect(spawn).toHaveBeenCalledOnce(); + expect(result).toMatchObject({ type: "started", port: 3002, pid: 5432 }); + }); + it("reaps a detached child that never becomes reachable without recording ownership", async () => { const stateHome = tempDir("hf-preview-state-"); const kill = vi.fn(); diff --git a/packages/cli/src/commands/previewLifecycle.ts b/packages/cli/src/commands/previewLifecycle.ts index 57bb8b311f..9e88cb81a9 100644 --- a/packages/cli/src/commands/previewLifecycle.ts +++ b/packages/cli/src/commands/previewLifecycle.ts @@ -13,10 +13,30 @@ import { } from "node:fs"; import { homedir } from "node:os"; import { dirname, join, resolve } from "node:path"; -import { scanActiveServers, type ActiveServer } from "../server/portUtils.js"; +import { + activeServerOnPort, + MAX_PORT_SCAN, + scanActiveServers, + type ActiveServer, +} from "../server/portUtils.js"; import type { BrowserGpuMode } from "../browser/gpuPolicy.js"; import { isProcessDescendant, processIdentity } from "../utils/orphanCleanup.js"; import { terminateProcessTree } from "../utils/processTree.js"; +import { PreviewServerPortMismatchError } from "../utils/studioSelectionClient.js"; + +export class PreviewPortUnavailableError extends Error { + readonly requestedPort: number; + readonly boundPort: number; + + constructor(requestedPort: number, boundPort: number) { + super( + `Port ${requestedPort} is already in use; the background preview would have started on port ${boundPort} instead. Free port ${requestedPort}, pick another --port, or omit --port to accept the next free port.`, + ); + this.name = "PreviewPortUnavailableError"; + this.requestedPort = requestedPort; + this.boundPort = boundPort; + } +} export interface PreviewSession { pid: number; @@ -47,9 +67,12 @@ interface LifecycleDependencies { isDescendant?: (childPid: number, ancestorPid: number) => boolean; identity?: (pid: number) => string | null; isSignalable?: (pid: number) => boolean; + probe?: (port: number) => Promise; stateHome?: string; forceNew?: boolean; browserGpuMode?: BrowserGpuMode; + /** Set only when the caller explicitly passed --port, not the CLI default. */ + preferredPort?: number; } function defaultStateHome(): string { @@ -160,12 +183,16 @@ function matchingServer( projectDir: string, browserGpuMode?: BrowserGpuMode, ): ActiveServer | null { - return ( - servers.find( - (server) => - normalized(server.projectDir) === normalized(projectDir) && - (browserGpuMode === undefined || server.browserGpuMode === browserGpuMode), - ) ?? null + return policyMatchingServers(servers, projectDir, browserGpuMode)[0] ?? null; +} + +function policyMatchingServers( + servers: ActiveServer[], + projectDir: string, + browserGpuMode?: BrowserGpuMode, +): ActiveServer[] { + return sameProjectServers(servers, projectDir).filter( + (server) => browserGpuMode === undefined || server.browserGpuMode === browserGpuMode, ); } @@ -180,13 +207,13 @@ function matchingServerAtPort( ); } -function sameProjectPorts(servers: ActiveServer[], projectDir: string): Set { +function sameProjectServers(servers: ActiveServer[], projectDir: string): ActiveServer[] { const project = normalized(projectDir); - return new Set( - servers - .filter((server) => normalized(server.projectDir) === project) - .map((server) => server.port), - ); + return servers.filter((server) => normalized(server.projectDir) === project); +} + +function sameProjectPorts(servers: ActiveServer[], projectDir: string): Set { + return new Set(sameProjectServers(servers, projectDir).map((server) => server.port)); } async function stopProcess(pid: number): Promise { @@ -231,10 +258,16 @@ function startedServer( servers: ActiveServer[], projectDir: string, preLaunchPorts: Set, - browserGpuMode?: BrowserGpuMode, + launchedPid: number, + dependencies: LifecycleDependencies, ): ActiveServer | null { - const candidates = servers.filter((server) => !preLaunchPorts.has(server.port)); - return matchingServer(candidates, projectDir, browserGpuMode); + const isDescendant = dependencies.isDescendant ?? isProcessDescendant; + const ours = (server: ActiveServer) => { + const pid = Number(server.pid); + return pid === launchedPid || isDescendant(pid, launchedPid); + }; + const candidates = servers.filter((server) => !preLaunchPorts.has(server.port) && ours(server)); + return matchingServer(candidates, projectDir, dependencies.browserGpuMode); } export function buildBackgroundPreviewArgs(argv: string[]): string[] { @@ -246,9 +279,10 @@ export function buildBackgroundPreviewArgs(argv: string[]): string[] { !arg.startsWith("--foreground=") && arg !== "--open" && arg !== "--no-open" && + arg !== "--force-new" && arg !== "--json", ); - return [...filtered, "--foreground", "--no-open"]; + return [...filtered, "--foreground", "--no-open", "--force-new"]; } export async function readBackgroundPreviewStatus( @@ -433,39 +467,80 @@ async function readPreviewLifecycleState( return { scan, stateHome, saved, scanStart, scanned }; } +function unmetPreferredPort(port: number, preferredPort: number | undefined): number | undefined { + return preferredPort !== undefined && port !== preferredPort ? preferredPort : undefined; +} + +type BackgroundPreviewResult = + | { type: "reused"; port: number; pid: number | null; logPath: string | null } + | { type: "started"; port: number; pid: number; logPath: string }; + +function reuseExistingPreview( + reusableExisting: ActiveServer | null, + candidates: ActiveServer[], + dependencies: LifecycleDependencies, +): Extract | null { + if (!reusableExisting || dependencies.forceNew) return null; + const unmet = unmetPreferredPort(reusableExisting.port, dependencies.preferredPort); + if (unmet !== undefined) { + throw new PreviewServerPortMismatchError( + unmet, + candidates, + ` To start one on port ${unmet} instead, add --force-new or run --stop first.`, + ); + } + return { + type: "reused", + port: reusableExisting.port, + pid: reusableExisting.pid ? Number(reusableExisting.pid) : null, + logPath: null, + }; +} + +// The scan only covers scanStart..+MAX_PORT_SCAN-1; an explicit --port outside it is probed directly. +async function addPreferredPortServer( + scanned: ActiveServer[], + scanStart: number, + dependencies: LifecycleDependencies, +): Promise { + const preferred = dependencies.preferredPort; + if (preferred === undefined) return; + if (preferred >= scanStart && preferred < scanStart + MAX_PORT_SCAN) return; + const server = await (dependencies.probe ?? activeServerOnPort)(preferred); + if (server) scanned.push(server); +} + export async function startBackgroundPreview( projectDir: string, startPort: number, dependencies: LifecycleDependencies = {}, -): Promise< - | { type: "reused"; port: number; pid: number | null; logPath: string | null } - | { type: "started"; port: number; pid: number; logPath: string } -> { - const { scan, stateHome, saved, scanned } = await readPreviewLifecycleState( +): Promise { + const { scan, stateHome, saved, scanStart, scanned } = await readPreviewLifecycleState( projectDir, startPort, dependencies, ); + await addPreferredPortServer(scanned, scanStart, dependencies); // Always inspect a saved custom port first. `--force-new --port ` must // replace that owned server before recording the replacement, otherwise the // single per-project ownership record would orphan the old listener. - const requestedExisting = matchingServer(scanned, projectDir, dependencies.browserGpuMode); + const candidates = policyMatchingServers(scanned, projectDir, dependencies.browserGpuMode); + // A policy-matching server on the explicit --port satisfies it even when it is not the owned one, + // so `--port 3003` reuses the 3003 sibling instead of reporting a mismatch against the owned 3002. + const onPreferredPort = + candidates.find((server) => server.port === dependencies.preferredPort) ?? null; + const requestedExisting = candidates[0] ?? null; const ownedExisting = savedOwnedPreview(scanned, saved, projectDir); - // A saved managed preview is the authoritative same-project instance. An - // explicit GPU-policy change replaces it; it must not silently adopt an - // unmanaged sibling that happens to match the new policy. + // Otherwise a saved managed preview is the authoritative same-project + // instance. An explicit GPU-policy change replaces it; it must not silently + // adopt an unmanaged sibling that happens to match the new policy. const reusableOwned = ownedExisting ? matchingServer([ownedExisting], projectDir, dependencies.browserGpuMode) : null; - const reusableExisting = reusableOwned ?? (ownedExisting ? null : requestedExisting); - if (reusableExisting && !dependencies.forceNew) { - return { - type: "reused", - port: reusableExisting.port, - pid: reusableExisting.pid ? Number(reusableExisting.pid) : null, - logPath: null, - }; - } + const reusableExisting = + onPreferredPort ?? reusableOwned ?? (ownedExisting ? null : requestedExisting); + const reused = reuseExistingPreview(reusableExisting, candidates, dependencies); + if (reused) return reused; await stopOwnedPreviewBeforeReplacement(ownedExisting, projectDir, dependencies); // Snapshot every same-project listener in the prospective launch range only // after the owned listener is gone. Readiness must identify a newly appeared @@ -478,35 +553,61 @@ export async function startBackgroundPreview( dependencies, ); + const kill = dependencies.kill ?? stopProcess; + const server = await awaitStartedServer(projectDir, startPort, preLaunchPorts, pid, dependencies); + if (!server) { + await kill(pid); + throw new Error(`background preview did not become ready; see ${logPath}`); + } + // The child scans upward from --port; one that missed an explicit --port is reaped, never recorded. + const unmet = unmetPreferredPort(server.port, dependencies.preferredPort); + if (unmet !== undefined) { + // Wait until it stops answering so a concurrent launch or --status cannot adopt a dying server. + await kill(pid); + if (!(await awaitServerGone(projectDir, startPort, server.port, dependencies))) { + throw new Error( + `background preview on port ${server.port} did not stop after failing to bind port ${unmet}; see ${logPath}`, + ); + } + throw new PreviewPortUnavailableError(unmet, server.port); + } + const ready = readyPreviewSession( + server, + pid, + wrapperIdentity, + projectDir, + logPath, + dependencies, + ); + writePreviewSession(ready.session, stateHome); + return { + type: "started", + ...ready.session, + pid: ready.publicPid, + }; +} + +async function awaitStartedServer( + projectDir: string, + startPort: number, + preLaunchPorts: Set, + launchedPid: number, + dependencies: LifecycleDependencies, +): Promise { + const scan = dependencies.scan ?? scanActiveServers; const sleep = dependencies.sleep ?? delay; for (let attempt = 0; attempt < 50; attempt++) { const server = startedServer( await scan(startPort), projectDir, preLaunchPorts, - dependencies.browserGpuMode, + launchedPid, + dependencies, ); - if (server) { - const ready = readyPreviewSession( - server, - pid, - wrapperIdentity, - projectDir, - logPath, - dependencies, - ); - writePreviewSession(ready.session, stateHome); - return { - type: "started", - ...ready.session, - pid: ready.publicPid, - }; - } + if (server) return server; await sleep(200); } - - await (dependencies.kill ?? stopProcess)(pid); - throw new Error(`background preview did not become ready; see ${logPath}`); + return null; } export async function stopBackgroundPreview( @@ -514,7 +615,7 @@ export async function stopBackgroundPreview( startPort: number, dependencies: LifecycleDependencies = {}, ): Promise { - const { scan, stateHome, saved, scanStart, scanned } = await readPreviewLifecycleState( + const { stateHome, saved, scanStart, scanned } = await readPreviewLifecycleState( projectDir, startPort, dependencies, @@ -537,13 +638,24 @@ export async function stopBackgroundPreview( const kill = dependencies.kill ?? stopProcess; await kill(ownedStopTargetPid(saved, pid, dependencies)); + if (!(await awaitServerGone(projectDir, scanStart, server.port, dependencies))) { + throw new Error(`background preview did not stop for ${resolve(projectDir)}`); + } + removePreviewSession(projectDir, stateHome); + return true; +} + +async function awaitServerGone( + projectDir: string, + scanStart: number, + port: number, + dependencies: LifecycleDependencies, +): Promise { + const scan = dependencies.scan ?? scanActiveServers; const sleep = dependencies.sleep ?? delay; for (let attempt = 0; attempt < 25; attempt++) { - if (!matchingServerAtPort(await scan(scanStart), projectDir, server.port)) { - removePreviewSession(projectDir, stateHome); - return true; - } + if (!matchingServerAtPort(await scan(scanStart), projectDir, port)) return true; await sleep(100); } - throw new Error(`background preview did not stop for ${resolve(projectDir)}`); + return false; } diff --git a/packages/cli/src/commands/snapshot.test.ts b/packages/cli/src/commands/snapshot.test.ts index 7fd4db398c..4b6789648f 100644 --- a/packages/cli/src/commands/snapshot.test.ts +++ b/packages/cli/src/commands/snapshot.test.ts @@ -4,19 +4,23 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "nod import { dirname, join } from "node:path"; import { tmpdir } from "node:os"; import { execFileSync } from "node:child_process"; -import { findFFmpeg } from "../browser/ffmpeg.js"; +import { findFFmpeg, findFFprobe } from "../browser/ffmpeg.js"; import { sourceTimeAt } from "@hyperframes/core"; const snapshotState = vi.hoisted(() => ({ - openSettledPage: vi.fn(async () => { + openSettledPage: vi.fn(async (): Promise => { throw new Error("browser capture reached"); }), + seek: vi.fn(async (_page: unknown, _time: number, _options?: unknown): Promise => { + throw new Error("seek reached"); + }), closeServer: vi.fn(async () => undefined), })); vi.mock("../capture/captureCompositionFrame.js", async (importOriginal) => ({ ...(await importOriginal()), openSettledCompositionPage: snapshotState.openSettledPage, + seekCompositionTimeline: snapshotState.seek, })); vi.mock("../utils/staticProjectServer.js", () => ({ @@ -28,9 +32,11 @@ vi.mock("../utils/staticProjectServer.js", () => ({ import snapshotCommand, { extractVideoFrameToBuffer, + containingSourceFrameIndex, computeSnapshotTimes, formatSnapshotTimestamp, parseZoomScale, + recaptureSnapshotComposite, requireSnapshotFfmpeg, resolveSnapshotVideoClipStart, resolveSnapshotVideoFrameTime, @@ -85,12 +91,8 @@ describe("transparent snapshot capture", () => { it("pairs every frame with the frame-exact reference frame under --against", () => { const source = readFileSync(new URL("./snapshot.ts", import.meta.url), "utf8"); expect(source).toContain("against: {"); - expect(source).toContain("extractVideoFrameToBuffer(opts.against, time, false, true)"); + expect(source).toContain("extractVideoFrameToBuffer(opts.against, time)"); expect(source).toContain('labels: ["render", "reference"]'); - // accurate seek = `-ss` after `-i`, never the keyframe-snap fast path - expect(source).toContain( - 'accurateSeek ? ["-i", videoPath, ...seek] : [...seek, "-i", videoPath]', - ); }); it("resolves and forwards the shared local browser GPU policy", () => { @@ -150,6 +152,44 @@ describe("snapshot lint preflight", () => { }); }); +describe("snapshot --at seeks", () => { + it("asks the runtime for the exact requested instant, not its 30fps grid", async () => { + const project = mkdtempSync(join(tmpdir(), "hf-snapshot-exact-at-")); + writeFileSync( + join(project, "index.html"), + `
    Visible
    `, + ); + const evaluate = vi + .fn() + .mockResolvedValueOnce({ loaded: [], errored: [], unused: [] }) + .mockResolvedValueOnce(20) + .mockResolvedValueOnce(true); + const close = vi.fn(async () => undefined); + snapshotState.openSettledPage.mockResolvedValueOnce({ + browser: { close }, + page: { evaluate }, + renderReadyTimedOut: false, + }); + snapshotState.seek.mockClear(); + const log = vi.spyOn(console, "log").mockImplementation(() => undefined); + + try { + await expect( + snapshotCommand.run?.({ + args: { dir: project, at: "19.019018", end: false, output: join(project, "out") }, + } as never), + ).rejects.toBeDefined(); + expect(snapshotState.seek).toHaveBeenCalledWith(expect.anything(), 19.019018, { + exactTime: true, + }); + expect(close).toHaveBeenCalled(); + } finally { + log.mockRestore(); + rmSync(project, { recursive: true, force: true }); + } + }); +}); + describe("resolveSnapshotVideoFrameTime", () => { it("holds a clip ending with the composition on its last decodable frame", () => { expect( @@ -304,10 +344,383 @@ describe("resolveSnapshotVideoFrameTime", () => { }); }); +describe("containingSourceFrameIndex", () => { + it.each([ + [0.4, 9], + [22 / 30, 17], + [10 / 30, 8], + [4.1, 98], + ])("selects frame %s on the source presentation grid", (time, expected) => { + expect( + containingSourceFrameIndex( + Array.from({ length: 120 }, (_, n) => n / 24), + time, + ), + ).toBe(expected); + }); + it("keeps exact boundaries despite floating-point round-off", () => { + expect(containingSourceFrameIndex([0, 4.1], 4.1 - 4 * Number.EPSILON)).toBe(1); + expect(containingSourceFrameIndex([0, 4.1], 4.1 - 0.00001)).toBe(0); + }); + it("uses irregular presentation intervals", () => { + expect(containingSourceFrameIndex([0, 0.02, 0.08, 0.15], 0.07)).toBe(1); + expect(containingSourceFrameIndex([0, 0.02, 0.08, 0.15], 0.08)).toBe(2); + }); +}); + describe("extractVideoFrameToBuffer", () => { const ffmpeg = findFFmpeg(); + const ffprobe = findFFprobe(); + const noProbe = !ffmpeg || !ffprobe; - it.skipIf(!ffmpeg)( + it.skipIf(noProbe)("selects containing frames for snapshots and reference pairs", async () => { + const dir = mkdtempSync(join(tmpdir(), "hf-snapshot-containing-")); + try { + const clip = join(dir, "clip.mp4"); + execFileSync(ffmpeg!, [ + "-hide_banner", + "-loglevel", + "error", + "-f", + "lavfi", + "-i", + "testsrc=d=2:r=24:s=160x90", + "-pix_fmt", + "yuv420p", + clip, + ]); + for (const [time, index] of [ + [0.4, 9], + [22 / 30, 17], + [10 / 30, 8], + [9 / 24, 9], + ] as const) { + const expected = join(dir, `frame-${index}.png`); + execFileSync(ffmpeg!, [ + "-hide_banner", + "-loglevel", + "error", + "-i", + clip, + "-vf", + `select=eq(n\\,${index})`, + "-frames:v", + "1", + "-y", + expected, + ]); + const actual = await extractVideoFrameToBuffer(clip, time); + expect(actual?.equals(readFileSync(expected))).toBe(true); + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it.skipIf(noProbe)("selects a variable-frame-rate presentation interval", async () => { + const dir = mkdtempSync(join(tmpdir(), "hf-snapshot-vfr-")); + try { + const clip = join(dir, "clip.mp4"); + execFileSync(ffmpeg!, [ + "-hide_banner", + "-loglevel", + "error", + "-f", + "lavfi", + "-i", + "testsrc=d=1:r=10:s=160x90", + "-vf", + "select=eq(n\\,0)+eq(n\\,1)+eq(n\\,4)+eq(n\\,8)", + "-fps_mode", + "vfr", + "-pix_fmt", + "yuv420p", + clip, + ]); + const expected = join(dir, "frame.png"); + execFileSync(ffmpeg!, [ + "-hide_banner", + "-loglevel", + "error", + "-i", + clip, + "-vf", + "select=eq(n\\,1)", + "-frames:v", + "1", + "-y", + expected, + ]); + expect((await extractVideoFrameToBuffer(clip, 0.3))?.equals(readFileSync(expected))).toBe( + true, + ); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it.skipIf(noProbe).each([ + ["fragmented MP4", "clip.mp4", ["-movflags", "frag_keyframe+empty_moov"]], + ["MPEG-TS", "clip.ts", []], + ["MP4", "clip.mp4", []], + ["open-GOP MPEG-TS", "clip.ts", ["-x264-params", "open-gop=1"]], + ])("matches a full decode past keyframes in %s with B-frames", async (_, name, muxArgs) => { + const dir = mkdtempSync(join(tmpdir(), "hf-snapshot-gop-")); + try { + const clip = join(dir, name); + const quiet = ["-hide_banner", "-loglevel", "error"]; + execFileSync(ffmpeg!, [ + ...quiet, + ...["-f", "lavfi", "-i", "testsrc2=d=3:r=30:s=160x90", "-pix_fmt", "yuv420p"], + ...["-c:v", "libx264", "-bf", "3", "-g", "30", "-keyint_min", "30", "-sc_threshold", "0"], + ...muxArgs, + clip, + ]); + // Frames 29 and 59 sit just before a keyframe; 47 and 80 decode from a later keyframe. + for (const index of [29, 47, 59, 80]) { + const expected = join(dir, `frame-${index}.png`); + execFileSync(ffmpeg!, [ + ...quiet, + ...["-i", clip, "-vf", `select=eq(n\\,${index})`, "-frames:v", "1", "-y", expected], + ]); + const actual = await extractVideoFrameToBuffer(clip, (index + 0.5) / 30); + expect(actual?.equals(readFileSync(expected)), `frame ${index}`).toBe(true); + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it.skipIf(noProbe)( + "leaves an unreadable video blank instead of failing the snapshot", + async () => { + const dir = mkdtempSync(join(tmpdir(), "hf-snapshot-unreadable-")); + try { + const garbage = join(dir, "garbage.mp4"); + writeFileSync(garbage, "not a video"); + expect(await extractVideoFrameToBuffer(join(dir, "missing.mp4"), 1)).toBeNull(); + expect(await extractVideoFrameToBuffer(garbage, 1)).toBeNull(); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }, + ); + + it.skipIf(noProbe)( + "selects exact frame times in a fragmented MP4 whose start rounds down", + async () => { + const dir = mkdtempSync(join(tmpdir(), "hf-snapshot-start-")); + try { + // B-frames start this clip at 1024/12288 s, which ffprobe prints as 0.083333. + const clip = join(dir, "clip.mp4"); + const quiet = ["-hide_banner", "-loglevel", "error"]; + execFileSync(ffmpeg!, [ + ...quiet, + ...["-f", "lavfi", "-i", "testsrc2=d=2:r=24:s=160x90", "-pix_fmt", "yuv420p"], + ...["-c:v", "libx264", "-bf", "3", "-movflags", "frag_keyframe+empty_moov", clip], + ]); + for (const index of [0, 1, 12, 47]) { + const expected = join(dir, `frame-${index}.png`); + execFileSync(ffmpeg!, [ + ...quiet, + ...["-i", clip, "-vf", `select=eq(n\\,${index})`, "-frames:v", "1", "-y", expected], + ]); + const actual = await extractVideoFrameToBuffer(clip, index / 24); + expect(actual?.equals(readFileSync(expected)), `frame ${index}`).toBe(true); + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }, + ); + + it.skipIf(noProbe)( + "selects frames in a stream-copy trim whose preroll starts before the video", + async () => { + const dir = mkdtempSync(join(tmpdir(), "hf-snapshot-editlist-")); + try { + // The trim keeps 1.3 s of preroll packets before the first visible frame (an MP4 edit list). + const source = join(dir, "source.mp4"); + const clip = join(dir, "clip.mp4"); + const quiet = ["-hide_banner", "-loglevel", "error"]; + execFileSync(ffmpeg!, [ + ...quiet, + ...["-f", "lavfi", "-i", "testsrc2=d=4:r=24:s=160x90", "-pix_fmt", "yuv420p"], + ...["-c:v", "libx264", "-bf", "2", source], + ]); + execFileSync(ffmpeg!, [...quiet, "-ss", "1.3", "-i", source, "-c", "copy", clip]); + for (const index of [1, 3, 10, 30]) { + const expected = join(dir, `frame-${index}.png`); + execFileSync(ffmpeg!, [ + ...quiet, + ...["-i", clip, "-vf", `select=eq(n\\,${index})`, "-frames:v", "1", "-y", expected], + ]); + const actual = await extractVideoFrameToBuffer(clip, index / 24); + expect(actual?.equals(readFileSync(expected)), `frame ${index}`).toBe(true); + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }, + ); + + it.skipIf(noProbe).each([ + // Audio leads video by 23 ms in a TS mux: frame n sits at 0.0232 + n/30 on the file's clock. + [ + "MPEG-TS with leading audio", + "clip.ts", + [], + [ + [0, 0], + [0.01, 0], + [0.05, 0], + [0.1, 2], + [1, 29], + ], + ], + // Video starts 0.5 s after the audio, so earlier times hold the first frame. + [ + "MP4 with late video", + "clip.mp4", + ["-vf", "setpts=PTS+0.5/TB", "-fps_mode", "passthrough"], + [ + [0, 0], + [0.1, 0], + [0.55, 1], + [1, 15], + ], + ], + ] as const)("measures frame times on the file clock in %s", async (_, name, videoArgs, cases) => { + const dir = mkdtempSync(join(tmpdir(), "hf-snapshot-av-")); + try { + const clip = join(dir, name); + const quiet = ["-hide_banner", "-loglevel", "error"]; + execFileSync(ffmpeg!, [ + ...quiet, + ...["-f", "lavfi", "-i", "testsrc2=d=2:r=30:s=160x90", "-f", "lavfi", "-i", "sine=d=3"], + ...videoArgs, + ...["-c:v", "libx264", "-bf", "3", "-pix_fmt", "yuv420p", "-c:a", "aac", clip], + ]); + for (const [time, index] of cases) { + const expected = join(dir, `frame-${index}.png`); + execFileSync(ffmpeg!, [ + ...quiet, + ...["-i", clip, "-map", "0:v:0", "-vf", `select=eq(n\\,${index})`], + ...["-frames:v", "1", "-y", expected], + ]); + const actual = await extractVideoFrameToBuffer(clip, time); + expect(actual?.equals(readFileSync(expected)), `t=${time}`).toBe(true); + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it.skipIf(noProbe)("selects frames in a TS whose timestamps start below zero", async () => { + const dir = mkdtempSync(join(tmpdir(), "hf-snapshot-negative-")); + try { + const clip = join(dir, "clip.ts"); + const quiet = ["-hide_banner", "-loglevel", "error"]; + execFileSync(ffmpeg!, [ + ...quiet, + ...["-f", "lavfi", "-i", "testsrc2=d=3:r=30:s=160x90", "-c:v", "libx264", "-g", "1"], + ...[ + "-output_ts_offset", + "-2", + "-avoid_negative_ts", + "disabled", + "-mpegts_copyts", + "1", + clip, + ], + ]); + const frameAt = async (time: number, index: number) => { + const expected = join(dir, `frame-${index}.png`); + execFileSync(ffmpeg!, [ + ...quiet, + ...["-i", clip, "-vf", `select=eq(n\\,${index})`, "-frames:v", "1", "-y", expected], + ]); + const actual = await extractVideoFrameToBuffer(clip, time); + expect(actual?.equals(readFileSync(expected)), `t=${time}`).toBe(true); + }; + for (const [time, index] of [ + [0, 0], + [0.05, 1], + [0.1, 3], + [1, 30], + [2.5, 75], + ] as const) { + await frameAt(time, index); + } + // Without ffprobe, the plain seek keeps main's first-frame-at-or-after behaviour. + vi.stubEnv("HYPERFRAMES_FFPROBE_PATH", join(dir, "missing-ffprobe")); + for (const [time, index] of [ + [0, 0], + [0.05, 2], + [1, 30], + ] as const) + await frameAt(time, index); + } finally { + vi.unstubAllEnvs(); + rmSync(dir, { recursive: true, force: true }); + } + }); + + it.skipIf(noProbe)("selects frames in a TS with frequent open-GOP keyframes", async () => { + const dir = mkdtempSync(join(tmpdir(), "hf-snapshot-open-gop-")); + try { + // A seek to 0.5 s lands on the keyframe at 1 s here, so the frames between are never decoded. + const clip = join(dir, "clip.ts"); + const quiet = ["-hide_banner", "-loglevel", "error"]; + execFileSync(ffmpeg!, [ + ...quiet, + ...["-f", "lavfi", "-i", "testsrc2=d=3:r=30:s=160x90", "-c:v", "libx264", "-g", "15"], + ...["-bf", "3", "-x264-params", "open-gop=1:scenecut=0", clip], + ]); + for (const [time, index] of [ + [0.5, 15], + [0.51, 15], + [0.99, 29], + [1.5, 45], + [1.99, 59], + ] as const) { + const expected = join(dir, `frame-${index}.png`); + execFileSync(ffmpeg!, [ + ...quiet, + ...["-i", clip, "-vf", `select=eq(n\\,${index})`, "-frames:v", "1", "-y", expected], + ]); + const actual = await extractVideoFrameToBuffer(clip, time); + expect(actual?.equals(readFileSync(expected)), `t=${time}`).toBe(true); + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it.skipIf(!ffmpeg)("extracts without ffprobe, as before frame selection needed it", async () => { + const dir = mkdtempSync(join(tmpdir(), "hf-snapshot-no-ffprobe-")); + vi.stubEnv("HYPERFRAMES_FFPROBE_PATH", join(dir, "missing-ffprobe")); + try { + const clip = join(dir, "clip.mp4"); + execFileSync(ffmpeg!, [ + ...["-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "testsrc=d=1:r=24:s=160x90"], + ...["-pix_fmt", "yuv420p", clip], + ]); + const expected = join(dir, "frame.png"); + execFileSync(ffmpeg!, [ + ...["-hide_banner", "-loglevel", "error", "-i", clip, "-vf", "select=eq(n\\,12)"], + ...["-frames:v", "1", "-y", expected], + ]); + expect((await extractVideoFrameToBuffer(clip, 0.5))?.equals(readFileSync(expected))).toBe( + true, + ); + } finally { + vi.unstubAllEnvs(); + rmSync(dir, { recursive: true, force: true }); + } + }); + + it.skipIf(noProbe)( "gives a 24 fps clip's real last frame for a held tail that lands past it", async () => { const dir = mkdtempSync(join(tmpdir(), "hf-snapshot-tail-")); @@ -316,10 +729,10 @@ describe("extractVideoFrameToBuffer", () => { const source = ["-f", "lavfi", "-i", "testsrc=d=1:r=24:s=160x90", "-pix_fmt", "yuv420p"]; execFileSync(ffmpeg!, ["-hide_banner", "-loglevel", "error", ...source, clip]); - const held = await extractVideoFrameToBuffer(clip, 1 - 1 / 30, false, false, true); - const lastFrame = await extractVideoFrameToBuffer(clip, 23 / 24, false, true); + const held = await extractVideoFrameToBuffer(clip, 1 - 1 / 30, false, true); + const lastFrame = await extractVideoFrameToBuffer(clip, 23 / 24); - expect(await extractVideoFrameToBuffer(clip, 1 - 1 / 30)).toBeNull(); + expect((await extractVideoFrameToBuffer(clip, 1 - 1 / 30))?.equals(lastFrame!)).toBe(true); expect(lastFrame).not.toBeNull(); expect(held?.equals(lastFrame!)).toBe(true); } finally { @@ -475,3 +888,56 @@ describe("requireSnapshotFfmpeg", () => { expect(requireSnapshotFfmpeg("C:\\tools\\ffmpeg.exe")).toBe("C:\\tools\\ffmpeg.exe"); }); }); + +describe("snapshot composite recapture", () => { + it.each([false, true])("recaptures only when a resolver exists: %s", async (hasResolver) => { + const order: string[] = []; + const runtimeWindow = { + __hf_page_composite_prepare: vi.fn(async () => { + order.push("prepare"); + return true; + }), + __hf_page_composite_resolve: hasResolver + ? vi.fn(() => { + order.push("resolve"); + return true; + }) + : undefined, + }; + vi.stubGlobal("window", runtimeWindow); + try { + await recaptureSnapshotComposite({ + async evaluate(callback: () => T): Promise> { + return await callback(); + }, + async screenshot(options) { + expect(options).toEqual({ + type: "jpeg", + quality: 1, + clip: { x: 0, y: 0, width: 1, height: 1 }, + }); + order.push("paint"); + return new Uint8Array(); + }, + }); + expect(order).toEqual(hasResolver ? ["prepare", "paint", "resolve"] : []); + } finally { + vi.unstubAllGlobals(); + } + }); + + it("places recapture after frame injection and visibility sync, before final capture", () => { + const source = readFileSync(new URL("./snapshot.ts", import.meta.url), "utf8"); + const injection = source.indexOf("await injectVideoFramesBatch(page, updates)"); + const visibility = source.indexOf("await syncVideoFrameVisibility(", injection); + const recapture = source.indexOf("await recaptureSnapshotComposite(page)", visibility); + const finalCapture = source.indexOf( + 'page.screenshot({ path: framePath, type: "png"', + recapture, + ); + expect(injection).toBeGreaterThan(-1); + expect(visibility).toBeGreaterThan(injection); + expect(recapture).toBeGreaterThan(visibility); + expect(finalCapture).toBeGreaterThan(recapture); + }); +}); diff --git a/packages/cli/src/commands/snapshot.ts b/packages/cli/src/commands/snapshot.ts index b091b3c6c1..db733a5c0b 100644 --- a/packages/cli/src/commands/snapshot.ts +++ b/packages/cli/src/commands/snapshot.ts @@ -32,7 +32,8 @@ import { formatLintFindings } from "../utils/lintFormat.js"; import { normalizeErrorMessage } from "../utils/errorMessage.js"; import { serveStaticProjectHtml } from "../utils/staticProjectServer.js"; import { c } from "../ui/colors.js"; -import { findFFmpeg, getFFmpegInstallHint } from "../browser/ffmpeg.js"; +import { runCancellableProcess } from "../utils/cancellableProcess.js"; +import { findFFmpeg, findFFprobe, getFFmpegInstallHint } from "../browser/ffmpeg.js"; import { parseAngle, type Camera } from "./motionShotLayout.js"; import type { Example } from "./_examples.js"; import { loadOptionalPackage } from "../utils/optionalPackages.js"; @@ -139,51 +140,204 @@ export function requireSnapshotFfmpeg(ffmpegPath: string | undefined): string { ); } -/** - * Extract a single frame from a video file at `timeSeconds` via FFmpeg. - * Used to work around Chrome-headless's inability to reliably seek - *
); -} +}); diff --git a/packages/studio/src/components/StudioRightPanels.tsx b/packages/studio/src/components/StudioRightPanels.tsx index 1461f42257..f4446a3f33 100644 --- a/packages/studio/src/components/StudioRightPanels.tsx +++ b/packages/studio/src/components/StudioRightPanels.tsx @@ -1,4 +1,4 @@ -import { useCallback } from "react"; +import { memo, useCallback } from "react"; import type { StudioRightPanelsProps } from "./StudioRightPanels.types"; import { PropertyPanel } from "./editor/PropertyPanel"; @@ -29,7 +29,9 @@ import { useRemoveBackground } from "../hooks/useRemoveBackground"; import { useApplyColorGradingScope } from "../hooks/useApplyColorGradingScope"; // fallow-ignore-next-line complexity -export function StudioRightPanels({ +const seekToTime = (t: number) => usePlayerStore.getState().requestSeek(t); + +export const StudioRightPanels = memo(function StudioRightPanels({ activeBlockParams, onCloseBlockParams, onDismissBlockParams, @@ -166,7 +168,7 @@ export function StudioRightPanels({ handleDomAttributeLiveCommit(attr, value, undefined, { previewOnly: true }), [handleDomAttributeLiveCommit], ); - const handleHideAllSelected = () => { + const handleHideAllSelected = useCallback(() => { // Audio has no visual to hide, and `data-hidden` on an audio element is what // MUTES it — preview silences it and the render drops it from the mix. The // timeline withholds the eye on an audio track for that reason @@ -181,7 +183,12 @@ export function StudioRightPanels({ const { elements } = usePlayerStore.getState(); const keys = timelineKeysForSelections(domEditGroupSelections, elements, activeCompPath); if (keys.length > 0) void onToggleElementHidden?.(keys, true); - }; + }, [domEditGroupSelections, showToast, activeCompPath, onToggleElementHidden]); + const convertToKeyframes = useCallback( + (animId: string, duration?: number) => + handleGsapConvertToKeyframes(animId, undefined, duration), + [handleGsapConvertToKeyframes], + ); const propertyPanel = ( 1 ? null : domEditSelection} @@ -246,10 +253,8 @@ export function StudioRightPanels({ onCommitAnimatedProperties={commitAnimatedProperties} onAddKeyframe={handleGsapAddKeyframe} onRemoveKeyframe={handleGsapRemoveKeyframe} - onConvertToKeyframes={(animId, duration) => - handleGsapConvertToKeyframes(animId, undefined, duration) - } - onSeekToTime={(t) => usePlayerStore.getState().requestSeek(t)} + onConvertToKeyframes={convertToKeyframes} + onSeekToTime={seekToTime} onSetArcPath={handleSetArcPath} onUpdateArcSegment={handleUpdateArcSegment} onUnroll={handleUnroll} @@ -307,4 +312,4 @@ export function StudioRightPanels({ ); -} +}); diff --git a/packages/studio/src/components/StudioToast.tsx b/packages/studio/src/components/StudioToast.tsx index b6c678b767..a00fb1b08a 100644 --- a/packages/studio/src/components/StudioToast.tsx +++ b/packages/studio/src/components/StudioToast.tsx @@ -46,5 +46,5 @@ export function StudioToast({ message, tone, leaving, onDismiss }: StudioToastPr } export function toastSurface(isError: boolean): string { - return `border shadow-popover backdrop-blur-md ${isError ? "border-danger/40 bg-raised" : "border-border bg-raised/95"}`; + return `border shadow-popover bg-raised ${isError ? "border-danger/40" : "border-border"}`; } diff --git a/packages/studio/src/components/TimelineToolbar.tsx b/packages/studio/src/components/TimelineToolbar.tsx index 7f0da96b33..dfa9dbe937 100644 --- a/packages/studio/src/components/TimelineToolbar.tsx +++ b/packages/studio/src/components/TimelineToolbar.tsx @@ -1,4 +1,4 @@ -import { useEffect, useRef } from "react"; +import { memo, useEffect, useRef } from "react"; import { ArrowsOutLineHorizontal, Image, @@ -141,7 +141,7 @@ function useKeyframeToggle(session?: DomEditSessionSlice) { } // fallow-ignore-next-line complexity -export function TimelineToolbar({ +export const TimelineToolbar = memo(function TimelineToolbar({ domEditSession, onSplitElement, history, @@ -558,4 +558,4 @@ export function TimelineToolbar({
); -} +}); diff --git a/packages/studio/src/components/editor/DomEditCropHandles.test.tsx b/packages/studio/src/components/editor/DomEditCropHandles.test.tsx index 0357a5b5b1..f574f821ef 100644 --- a/packages/studio/src/components/editor/DomEditCropHandles.test.tsx +++ b/packages/studio/src/components/editor/DomEditCropHandles.test.tsx @@ -345,3 +345,30 @@ describe("DomEditCropHandles preset bar", () => { expect(useCropPresetBarStore.getState().openFor).toBeNull(); }); }); + +vi.mock("../../utils/studioTelemetry", () => ({ trackStudioEvent: vi.fn() })); +import { trackStudioEvent } from "../../utils/studioTelemetry"; +describe("crop usage", () => { + it.each([true, false])( + "counts a crop drag only after a changed writer result (%s)", + async (changed) => { + vi.mocked(trackStudioEvent).mockClear(); + const saved = vi.fn(async () => ({ ok: true, changed })); + const { root } = render(makeEl("private-target", "inset(10px)"), saved); + const handle = document.querySelector('[aria-label="Crop right"]')!; + dragCropRight(handle, 1, [ + [200, 1], + [180, 1], + [160, 1], + ]); + await act(async () => { + await Promise.resolve(); + }); + expect(saved).toHaveBeenCalledTimes(1); + expect(vi.mocked(trackStudioEvent).mock.calls).toEqual( + changed ? [["feature_used", { feature: "crop", surface: "preview", method: "drag" }]] : [], + ); + act(() => root.unmount()); + }, + ); +}); diff --git a/packages/studio/src/components/editor/DomEditCropHandles.tsx b/packages/studio/src/components/editor/DomEditCropHandles.tsx index 6ec3d5a322..3a7f07456e 100644 --- a/packages/studio/src/components/editor/DomEditCropHandles.tsx +++ b/packages/studio/src/components/editor/DomEditCropHandles.tsx @@ -1,3 +1,4 @@ +import { trackPreviewEditResult, type PreviewMethod } from "../../utils/previewFeatureUsage"; import { useEffect, useRef, useState, type PointerEvent as ReactPointerEvent } from "react"; import type { DomEditSelection } from "./domEditing"; import { type OverlayRect, RESIZE_HANDLE_HIT_PX } from "./domEditOverlayGeometry"; @@ -229,19 +230,21 @@ export function DomEditCropHandles({ // the lift keeps it hidden while selected. A drag that ends where it started saves nothing. const value = buildInsetClipPathSides(gesture.insets, gesture.radius); if (value === buildInsetClipPathSides(gesture.startInsets, gesture.radius)) return; - commitClipPath(value); + commitClipPath(value, "drag"); }; - const commitClipPath = (value: string) => { + const commitClipPath = (value: string, method: PreviewMethod) => { const commit = onStyleCommit?.("clip-path", value); - void Promise.resolve(commit).catch(() => undefined); + void Promise.resolve(commit) + .then((result) => trackPreviewEditResult("crop", method, result)) + .catch(() => undefined); }; const applyPresetInsets = (insets: ClipPathInsetSides | null) => { const next = insets ?? { top: 0, right: 0, bottom: 0, left: 0 }; setState((prev) => ({ ...prev, insets: next })); const radius = readCropFollowingResize(selection.element)?.radius ?? 0; - commitClipPath(insets === null ? "" : buildInsetClipPathSides(next, radius)); + commitClipPath(insets === null ? "" : buildInsetClipPathSides(next, radius), "button"); }; const cancelCropGesture = (event: ReactPointerEvent) => { diff --git a/packages/studio/src/components/editor/DomEditOverlay.tsx b/packages/studio/src/components/editor/DomEditOverlay.tsx index 4a1976d4bf..95636a4fec 100644 --- a/packages/studio/src/components/editor/DomEditOverlay.tsx +++ b/packages/studio/src/components/editor/DomEditOverlay.tsx @@ -1,3 +1,4 @@ +import type { DomSelectionResult } from "../../hooks/useDomSelectionTypes"; import type { RotationCommit } from "./rotationDraft"; import { memo, useEffect, useMemo, useRef, type RefObject } from "react"; import { type DomEditSelection } from "./domEditing"; @@ -98,7 +99,10 @@ export interface DomEditOverlayProps { onStyleCommit?: (property: string, value: string) => Promise | void; recordingState?: GestureRecordingState; onToggleRecording?: () => void; - onMarqueeSelect?: (selections: DomEditSelection[], additive: boolean) => void; + onMarqueeSelect?: ( + selections: DomEditSelection[], + additive: boolean, + ) => DomSelectionResult | void; /** * Delete the selected canvas element. * Wire to handleDomEditElementDelete from useDomEditActionsContext — diff --git a/packages/studio/src/components/editor/InlineTextToolbar.tsx b/packages/studio/src/components/editor/InlineTextToolbar.tsx index cc8f895490..7b633a599d 100644 --- a/packages/studio/src/components/editor/InlineTextToolbar.tsx +++ b/packages/studio/src/components/editor/InlineTextToolbar.tsx @@ -1,8 +1,12 @@ import { useCallback, useEffect, useState } from "react"; import { createPortal } from "react-dom"; import { applyInlineStyle } from "./inlineTextStyleRange"; -import { readInlineStyle, readInlineStyleSpread } from "./inlineTextStyleRead"; -import { parseCssColor, toHexColor } from "./colorValue"; +import { + readFirstPaintedElement, + readInlineStyle, + readInlineStyleSpread, +} from "./inlineTextStyleRead"; +import { resolvePickerColor } from "./colorValue"; import type { InlineTextEditSession } from "../../hooks/useInlineTextEdit"; /** @@ -248,7 +252,11 @@ function placeOverSelection( placeBelow, styles, colours, - pickerColour: toPickerColour(styles.color ?? colours[0], doc), + pickerColour: resolvePickerColor( + styles.color ?? colours[0], + readFirstPaintedElement(range, "color"), + DEFAULT_COLOR, + ), }; } @@ -257,27 +265,3 @@ function isBold(weight: string | undefined): boolean { if (weight === "bold" || weight === "bolder") return true; return Number.parseInt(weight, 10) >= 600; } - -/** A colour input accepts only `#rrggbb`; normalise any valid CSS colour to it. */ -function toPickerColour(value: string | undefined, doc: Document): string { - if (!value) return DEFAULT_COLOR; - const parsed = parseCssColor(value); - if (parsed) return toHexColor(parsed); - - // Canvas delegates the full CSS colour grammar to the browser, including - // named colours that the small serialisation parser intentionally omits. - // DOM-only test environments can lack a canvas implementation, in which - // case the picker degrades to its explicit default while the swatch remains - // truthful because CSS still paints the original value. - try { - const context = doc.createElement("canvas").getContext("2d"); - if (!context) return DEFAULT_COLOR; - context.fillStyle = DEFAULT_COLOR; - context.fillStyle = value; - const normalised = - typeof context.fillStyle === "string" ? parseCssColor(context.fillStyle) : null; - return normalised ? toHexColor(normalised) : DEFAULT_COLOR; - } catch { - return DEFAULT_COLOR; - } -} diff --git a/packages/studio/src/components/editor/MotionPathOverlay.tsx b/packages/studio/src/components/editor/MotionPathOverlay.tsx index eeaa18824b..b66c1361ba 100644 --- a/packages/studio/src/components/editor/MotionPathOverlay.tsx +++ b/packages/studio/src/components/editor/MotionPathOverlay.tsx @@ -1,3 +1,5 @@ +import { observeGsapGesture } from "../../hooks/gsapGestureOutcome"; +import { trackPreviewEditResult } from "../../utils/previewFeatureUsage"; import { scopedElementKey } from "../../hooks/gsapKeyframeCacheHelpers"; import { memo, useEffect, useRef, useState, type RefObject } from "react"; import type { DomEditSelection } from "./domEditing"; @@ -382,15 +384,18 @@ export const MotionPathOverlay = memo(function MotionPathOverlay({ selection && !usePlayerStore.getState().autoKeyframeEnabled ) { + const writes = observeGsapGesture((_sel, mutation, options) => + commitMutation(mutation, options), + ); void commitWholePropertyOffset( selection, anim, { x, y }, d.ref.pct, iframeRef.current, - { commitMutation: (_sel, mutation, options) => commitMutation(mutation, options) }, + { commitMutation: writes.commit! }, "Move animation path", - ); + ).then(() => trackPreviewEditResult("motion_path", "drag", writes.finish())); } else { void commitNode(d.ref, x, y, animId, commitMutation); } diff --git a/packages/studio/src/components/editor/PropertyPanelEmptyState.tsx b/packages/studio/src/components/editor/PropertyPanelEmptyState.tsx index 4890b7deb6..dbbb45f864 100644 --- a/packages/studio/src/components/editor/PropertyPanelEmptyState.tsx +++ b/packages/studio/src/components/editor/PropertyPanelEmptyState.tsx @@ -1,6 +1,7 @@ import { Eye, Layers } from "../../icons/SystemIcons"; import type { DomEditSelection } from "./domEditingTypes"; import { canHideSelections } from "../../utils/timelineInspector"; +import { useTrackDesignInput } from "../../contexts/DesignPanelInputContext"; function FlatEmptyState() { return ( @@ -71,6 +72,7 @@ function FlatMultiSelectState({ // One predicate for both actions and for the handler's own refusal, so the // button and the refusal cannot disagree about what audio is. const hasAudio = !canHideSelections(multiSelectedElements); + const trackInput = useTrackDesignInput(); return (
@@ -141,7 +143,11 @@ function FlatMultiSelectState({ @@ -250,7 +255,10 @@ export function FxCarveModule({ value={carve.strength} disabled={disabled || carve.sources.length === 0} onChange={(_k, v) => onCarvePreview({ ...carve, strength: Number(v) })} - onCommit={(_k, v) => onCarveChange({ ...carve, strength: Number(v) })} + onCommit={(_k, v) => { + onCarveChange({ ...carve, strength: Number(v) }); + trackInput("slider", "carve-strength"); + }} />
{/* What the analysis made of all that. Divided rather than boxed: these @@ -334,6 +342,7 @@ function CarveSourceRow({ disabled?: boolean; onCarveChange(carve: HfCarveSettings): void; }) { + const trackInput = useTrackDesignInput(); return (
{/* Wraps like every other name in this column (see FxParamRow) — one @@ -366,14 +375,15 @@ function CarveSourceRow({ data-carve-source={o.id} checked={carve.sources.includes(o.id)} disabled={disabled} - onChange={(e) => + onChange={(e) => { onCarveChange({ ...carve, sources: e.target.checked ? [...carve.sources, o.id] : carve.sources.filter((id) => id !== o.id), - }) - } + }); + trackInput("toggle", "carve-source"); + }} /> {o.label} diff --git a/packages/studio/src/components/editor/propertyPanelFxNodeOpenBody.tsx b/packages/studio/src/components/editor/propertyPanelFxNodeOpenBody.tsx index 6a5183212c..c35189af45 100644 --- a/packages/studio/src/components/editor/propertyPanelFxNodeOpenBody.tsx +++ b/packages/studio/src/components/editor/propertyPanelFxNodeOpenBody.tsx @@ -1,3 +1,4 @@ +import { useTrackDesignInput } from "../../contexts/DesignPanelInputContext"; /** * An effect row's open face: the derived or primary one-knob control, and * Details underneath it. @@ -54,6 +55,7 @@ function FxNodeDerivedKnob({ onUpdate(index: number, patch: Partial): void; trackKind?: string; }) { + const trackInput = useTrackDesignInput(); if (!derived) return null; return ( <> @@ -66,6 +68,7 @@ function FxNodeDerivedKnob({ onCommit={(_k, v) => { trackProfileCommitted(node.type, Number(v), { trackKind }); onUpdate(index, { params: applyAudioFxProfile(node.type, Number(v), params) }); + trackInput("slider", "profile-strength"); }} />
diff --git a/packages/studio/src/components/editor/propertyPanelFxNodeParams.tsx b/packages/studio/src/components/editor/propertyPanelFxNodeParams.tsx index 4e73130e3f..014257718e 100644 --- a/packages/studio/src/components/editor/propertyPanelFxNodeParams.tsx +++ b/packages/studio/src/components/editor/propertyPanelFxNodeParams.tsx @@ -1,3 +1,4 @@ +import { useTrackDesignInput } from "../../contexts/DesignPanelInputContext"; /** * An open effect's knobs, with whatever automation surface applies to them. * @@ -69,6 +70,7 @@ export function FxNodeParams({ index: number; disabled: boolean; }) { + const trackInput = useTrackDesignInput(); const nodeId = node.id; // Lanes address a node by id; the controls know their own parameter keys. This // is the one place that translation belongs. @@ -97,14 +99,25 @@ export function FxNodeParams({ if (before[key] === value) continue; if (typeof value !== "number" && typeof value !== "string") continue; trackParamCommitted(node.type, key, value, "details", { trackKind }); + trackInput(typeof value === "number" ? "slider" : "select", key); } onUpdate(index, { params: next }); }} automatedKeys={automatedKeysOf(node, def.params, automatedTargets)} - onAutomate={nodeId && onAutomateParam ? (key) => onAutomateParam(nodeId, key) : undefined} + onAutomate={ + nodeId && onAutomateParam + ? (key) => { + onAutomateParam(nodeId, key); + trackInput("button", "automate-param"); + } + : undefined + } onRemoveAutomation={ nodeId && onRemoveParamAutomation - ? (key) => onRemoveParamAutomation(nodeId, key) + ? (key) => { + onRemoveParamAutomation(nodeId, key); + trackInput("button", "remove-param-automation"); + } : undefined } /> diff --git a/packages/studio/src/components/editor/propertyPanelFxNodeRow.tsx b/packages/studio/src/components/editor/propertyPanelFxNodeRow.tsx index 567b71f23d..7d5a960dd2 100644 --- a/packages/studio/src/components/editor/propertyPanelFxNodeRow.tsx +++ b/packages/studio/src/components/editor/propertyPanelFxNodeRow.tsx @@ -1,3 +1,4 @@ +import { useTrackDesignInput } from "../../contexts/DesignPanelInputContext"; /** * One effect in the FX rack: its header controls, and its knobs when open. * @@ -246,6 +247,7 @@ export function FxNodeRow({ onPreview, trackKind, }: FxNodeRowProps) { + const trackInput = useTrackDesignInput(); const registryDef = getAudioFxDef(node.type); const def = useMemo(() => (registryDef ? plainDef(registryDef) : null), [registryDef]); const primary = registryDef ? primaryParamOf(registryDef) : null; @@ -306,6 +308,7 @@ export function FxNodeRow({ onToggleBypass={() => { trackNodeBypassed(node.type, !bypassed, { trackKind }); onUpdate(index, { enabled: bypassed }); + trackInput("toggle", "effect-bypass"); }} onMove={(delta) => onMove(index, delta)} onRemove={() => onRemove(index)} diff --git a/packages/studio/src/components/editor/propertyPanelFxPresetRun.tsx b/packages/studio/src/components/editor/propertyPanelFxPresetRun.tsx index eb92a90455..deddff5b2a 100644 --- a/packages/studio/src/components/editor/propertyPanelFxPresetRun.tsx +++ b/packages/studio/src/components/editor/propertyPanelFxPresetRun.tsx @@ -1,3 +1,4 @@ +import { useTrackDesignInput } from "../../contexts/DesignPanelInputContext"; /** * One preset's bracket in the rack: its own header, on/off switch, amount lane * and the rows it wraps — or, for a run with no preset, just the rows. @@ -93,6 +94,7 @@ export function FxPresetRun({ onAutomate, onRemoveAutomation, }: FxPresetRunProps) { + const trackInput = useTrackDesignInput(); const rows = run.items.map(({ node, i }) => ( onSetAmount(runOn ? 0 : 1)} + onClick={() => { + onSetAmount(runOn ? 0 : 1); + trackInput("toggle", "preset-amount"); + }} > {runOn ? "On" : "Off"} @@ -205,7 +210,10 @@ export function FxPresetRun({ disabled={disabled || automated} automated={automated} onChange={(_k, v) => onSetAmount(Number(v), false)} - onCommit={(_k, v) => onSetAmount(Number(v))} + onCommit={(_k, v) => { + onSetAmount(Number(v)); + trackInput("slider", "preset-amount"); + }} onAutomate={onAutomate} onRemoveAutomation={onRemoveAutomation} /> diff --git a/packages/studio/src/components/editor/propertyPanelFxSection.test.tsx b/packages/studio/src/components/editor/propertyPanelFxSection.test.tsx index ee27e3b699..ee2452d431 100644 --- a/packages/studio/src/components/editor/propertyPanelFxSection.test.tsx +++ b/packages/studio/src/components/editor/propertyPanelFxSection.test.tsx @@ -1787,3 +1787,59 @@ describe("voiceover carve visibility", () => { expect(carveBlock(host)).toBeTruthy(); }); }); + +vi.mock("../../utils/studioTelemetry", () => ({ trackStudioEvent: vi.fn() })); +import { trackStudioEvent } from "../../utils/studioTelemetry"; +import { __resetDesignInputThrottle } from "../../utils/designInputTracking"; +import { DesignPanelInputProvider } from "../../contexts/DesignPanelInputContext"; +function renderTrackedFx(props: Partial[0]> = {}) { + vi.mocked(trackStudioEvent).mockClear(); + __resetDesignInputThrottle(); + return renderInto( + + + , + ); +} + +describe("custom FX inspector input usage", () => { + it.each([ + [".hf-fx-bypass", "toggle", "effect-bypass"], + ['.hf-fx-move[title="Move down"]', "button", "move-effect"], + [".hf-fx-remove", "button", "remove-effect"], + ])("tracks %s through design_input once", (selector, control, name) => { + const onChainChange = vi.fn(); + const { host, root } = renderTrackedFx({ onChainChange }); + click(host.querySelector(selector)); + expect(onChainChange).toHaveBeenCalledTimes(1); + expect( + vi.mocked(trackStudioEvent).mock.calls.filter(([event]) => event === "design_input"), + ).toEqual([["design_input", { ui: "flat", section: "media", control, name }]]); + expect(vi.mocked(trackStudioEvent).mock.calls.some(([event]) => event === "feature_used")).toBe( + false, + ); + act(() => root.unmount()); + }); + it.each([false, true])("tracks a levelling button once (already levelled: %s)", (levelled) => { + const action = vi.fn(); + const { host, root } = renderTrackedFx({ levelled, onLevel: action, onRemoveLevel: action }); + click(byText(host, "button", "+ effect")); + vi.mocked(trackStudioEvent).mockClear(); + click(byText(host, "button", levelled ? "Remove levelling" : "Even Out Levels")); + expect(action).toHaveBeenCalledTimes(1); + expect(trackStudioEvent).toHaveBeenCalledExactlyOnceWith("design_input", { + ui: "flat", + section: "media", + control: "button", + name: levelled ? "remove-levelling" : "add-levelling", + }); + act(() => root.unmount()); + }); +}); diff --git a/packages/studio/src/components/editor/propertyPanelFxSection.tsx b/packages/studio/src/components/editor/propertyPanelFxSection.tsx index 90312e700a..94412b210e 100644 --- a/packages/studio/src/components/editor/propertyPanelFxSection.tsx +++ b/packages/studio/src/components/editor/propertyPanelFxSection.tsx @@ -1,3 +1,4 @@ +import { useTrackDesignInput } from "../../contexts/DesignPanelInputContext"; /** * The FX section for an audio element: the chain, plus the voiceover carve. * @@ -120,13 +121,17 @@ export function FxSection({ // could only name a source it must not. const showCarve = !carvedAgainstBy && (sourceOptions.length > 0 || carve !== null); + const trackInput = useTrackDesignInput(); const [adding, setAdding] = useState(false); const [picking, setPicking] = useState(false); const [openNode, setOpenNode] = useState(0); const mutate = useCallback( - (nodes: HfAudioFxNode[]) => onChainChange({ ...chain, nodes }), - [chain, onChainChange], + (nodes: HfAudioFxNode[], input?: string, control = "button") => { + onChainChange({ ...chain, nodes }); + if (input) trackInput(control, input); + }, + [chain, onChainChange, trackInput], ); // Dragging a knob previews without persisting; releasing it commits once. @@ -156,7 +161,7 @@ export function FxSection({ // old chain back over the write that just landed is a race the author // hears as the preset arriving and then leaving again. clearAudition(); - mutate(next.nodes); + mutate(next.nodes, "apply-preset"); // Land on the first node the preset wrote, so the author can hear what // arrived and immediately see what it is made of. setOpenNode(next.nodes.findIndex((n) => n.fromPreset === id)); @@ -169,7 +174,7 @@ export function FxSection({ (job: HfAudioFxJob) => { clearAudition(); trackNodeAdded(job.type, "job", job.id, { trackKind }); - mutate(withJob(chain, job).nodes); + mutate(withJob(chain, job).nodes, "add-job"); setOpenNode(chain.nodes.length); setAdding(false); }, @@ -180,7 +185,7 @@ export function FxSection({ (type: string) => { clearAudition(); trackNodeAdded(type, "effect", null, { trackKind }); - mutate(withEffect(chain, type).nodes); + mutate(withEffect(chain, type).nodes, "add-effect"); setOpenNode(chain.nodes.length); setAdding(false); }, @@ -218,26 +223,18 @@ export function FxSection({ [chain, mutate, onChainPreview], ); - /** - * Take a preset back out whole, lanes and all. - * - * Same contract as removing one node — an orphaned lane keeps driving a - * parameter that is no longer in the graph, and with ids minted lowest-free - * the next effect added inherits it. - */ + // Remove the run and its lanes together so new nodes cannot inherit orphaned automation. const removeRun = useCallback( (items: { node: HfAudioFxNode; i: number }[], presetId?: string) => { - // One call, not a loop: every write is computed from the same snapshot and - // replaces the whole attribute, so a loop kept only its last write and left - // the other nodes' lanes behind as orphans. The preset id goes with it — - // the `fx.preset.` amount lane belongs to the preset, not to any node, - // so nothing else would ever collect it, and re-applying the preset later - // resurrected the old ramp. + // Remove node and preset automation together before replacing the chain. const ids = items.map(({ node }) => node.id).filter((id): id is string => Boolean(id)); if (ids.length > 0 || presetId) onRemoveNodesAutomation?.(ids, presetId); if (presetId) trackPresetRemoved(presetId, { trackKind }); const slots = new Set(items.map((item) => item.i)); - mutate(chain.nodes.filter((_, i) => !slots.has(i))); + mutate( + chain.nodes.filter((_, i) => !slots.has(i)), + "remove-preset", + ); setOpenNode(null); }, [chain.nodes, mutate, onRemoveNodesAutomation, trackKind], @@ -254,7 +251,10 @@ export function FxSection({ const removedId = removed?.id; if (removedId) onRemoveNodeAutomation?.(removedId); if (removed) trackNodeRemoved(removed.type, nodeOrigin(removed), { trackKind }); - mutate(chain.nodes.filter((_, i) => i !== index)); + mutate( + chain.nodes.filter((_, i) => i !== index), + "remove-effect", + ); setOpenNode(null); }, [chain.nodes, mutate, onRemoveNodeAutomation, trackKind], @@ -372,7 +372,7 @@ export function FxSection({ clearAudition(); const { chain: next, eqId } = addAudioEq(chain); trackNodeAdded("eq", "eq", null, { trackKind }); - mutate(next.nodes); + mutate(next.nodes, "add-eq"); setOpenEq(eqId); setAdding(false); }, [chain, mutate, clearAudition, trackKind]); @@ -386,20 +386,18 @@ export function FxSection({ ); const commitEqBand = useCallback( (eqId: string, band: string, gain: number) => - mutate(setAudioEqBandGain(chain, eqId, band, gain).nodes), + mutate(setAudioEqBandGain(chain, eqId, band, gain).nodes, "eq-gain", "slider"), [chain, mutate], ); const removeEq = useCallback( (eqId: string) => { - // Batched for the same reason as `removeRun` — this loop had the identical - // last-write-wins bug and was only unreachable because an EQ band row - // offers no automation toggle today. + // Remove the EQ automation in one write. const ids = chain.nodes .filter((node) => node.fromEq === eqId) .map((node) => node.id) .filter((id): id is string => Boolean(id)); if (ids.length > 0) onRemoveNodesAutomation?.(ids); - mutate(removeAudioEq(chain, eqId).nodes); + mutate(removeAudioEq(chain, eqId).nodes, "remove-eq"); }, [chain, mutate, onRemoveNodesAutomation], ); @@ -412,7 +410,7 @@ export function FxSection({ const [moved] = next.splice(index, 1); next.splice(target, 0, moved!); if (moved) trackNodeMoved(moved.type, delta < 0 ? "up" : "down", { trackKind }); - mutate(next); + mutate(next, "move-effect"); setOpenNode(target); }, [chain.nodes, mutate, trackKind], @@ -448,6 +446,7 @@ export function FxSection({ return () => { trackPresetAutomated(presetId, true, { trackKind }); onAutomatePreset(presetId, amount); + trackInput("button", "automate-preset"); }; }; @@ -456,7 +455,10 @@ export function FxSection({ presetId: string | undefined, ): (() => void) | undefined => { if (!presetId || !onRemovePresetAutomation || !presetAutomated.has(presetId)) return undefined; - return () => onRemovePresetAutomation(presetId); + return () => { + onRemovePresetAutomation(presetId); + trackInput("button", "remove-preset-automation"); + }; }; return ( diff --git a/packages/studio/src/components/editor/propertyPanelTypes.ts b/packages/studio/src/components/editor/propertyPanelTypes.ts index 3b58a02ebc..7dab3a8180 100644 --- a/packages/studio/src/components/editor/propertyPanelTypes.ts +++ b/packages/studio/src/components/editor/propertyPanelTypes.ts @@ -82,12 +82,15 @@ export interface PropertyPanelProps { element: DomEditSelection, next: { x: number; y: number }, route?: { plainTranslate: boolean }, - ) => void | Promise; + ) => void | Promise; onSetManualSize: ( element: DomEditSelection, next: { width: number; height: number }, - ) => void | Promise; - onSetManualRotation: (element: DomEditSelection, next: { angle: number }) => void | Promise; + ) => void | Promise; + onSetManualRotation: ( + element: DomEditSelection, + next: { angle: number }, + ) => void | Promise; onSetText: (value: string, fieldKey?: string) => void; onSetTextFieldStyle: (fieldKey: string, property: string, value: string) => void; onPreviewTextFieldStyle?: (fieldKey: string, property: string, value: string) => void; diff --git a/packages/studio/src/components/editor/reapplyPositionEditsAfterSeek.test.ts b/packages/studio/src/components/editor/reapplyPositionEditsAfterSeek.test.ts index 839aadd344..b40b9bb810 100644 --- a/packages/studio/src/components/editor/reapplyPositionEditsAfterSeek.test.ts +++ b/packages/studio/src/components/editor/reapplyPositionEditsAfterSeek.test.ts @@ -2,6 +2,8 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { reapplyPositionEditsAfterSeek } from "./manualEditsSeekReapply"; import { + STUDIO_OFFSET_X_PROP, + STUDIO_OFFSET_Y_PROP, STUDIO_PATH_OFFSET_ATTR, STUDIO_ROTATION_ATTR, STUDIO_ROTATION_PROP, @@ -14,6 +16,29 @@ describe("reapplyPositionEditsAfterSeek", () => { vi.restoreAllMocks(); }); + it("keeps an old offset off an element GSAP moves by object-of-arrays keyframes, not off its neighbour", () => { + const offset = `${STUDIO_OFFSET_X_PROP}: 300px; ${STUDIO_OFFSET_Y_PROP}: 100px; translate: none`; + document.body.innerHTML = ["moved", "still"] + .map((id) => `
`) + .join(""); + const moved = document.getElementById("moved") as HTMLElement; + const tween = { targets: () => [moved], vars: { keyframes: { x: [0, 200] } } }; + const win = window as unknown as { __timelines?: unknown; gsap?: unknown }; + const gsap = { set: vi.fn(), getProperty: () => 0 }; + Object.assign(win, { __timelines: { main: { getChildren: () => [tween] } }, gsap }); + try { + reapplyPositionEditsAfterSeek(document); + } finally { + delete win.__timelines; + delete win.gsap; + } + + expect(moved.style.getPropertyValue("translate")).toBe("none"); + expect(gsap.set).not.toHaveBeenCalled(); + const still = document.getElementById("still") as HTMLElement; + expect(still.style.getPropertyValue("translate")).toContain(STUDIO_OFFSET_X_PROP); + }); + it("does no per-edit work on a film Studio never edited", () => { document.body.innerHTML = '
'; const queryAll = vi.spyOn(document, "querySelectorAll"); diff --git a/packages/studio/src/components/editor/useDomEditNudge.test.tsx b/packages/studio/src/components/editor/useDomEditNudge.test.tsx index 01dc955732..af77cdcbfd 100644 --- a/packages/studio/src/components/editor/useDomEditNudge.test.tsx +++ b/packages/studio/src/components/editor/useDomEditNudge.test.tsx @@ -1,3 +1,4 @@ +import { trackStudioEvent } from "../../utils/studioTelemetry"; // @vitest-environment happy-dom import React, { act } from "react"; import { createRoot } from "react-dom/client"; @@ -423,3 +424,39 @@ describe("useDomEditNudge — a commit that throws", () => { act(() => root.unmount()); }); }); + +vi.mock("../../utils/studioTelemetry", () => ({ trackStudioEvent: vi.fn() })); +describe("nudge usage", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.useFakeTimers(); + __resetForTests(); + }); + afterEach(() => vi.useRealTimers()); + it.each([true, false])( + "counts a whole key burst only when the writer changed source (%s)", + async (changed) => { + const root = createRoot(document.body.appendChild(document.createElement("div"))); + const element = document.body.appendChild(document.createElement("div")); + const commit = vi.fn().mockResolvedValue({ ok: true, changed }); + act(() => + root.render( + , + ), + ); + act(() => { + dispatchArrowRight(); + dispatchArrowRight(); + }); + await act(async () => vi.advanceTimersByTimeAsync(CANVAS_NUDGE_COMMIT_DEBOUNCE_MS + 10)); + expect(commit).toHaveBeenCalledTimes(1); + expect(vi.mocked(trackStudioEvent).mock.calls).toEqual( + changed + ? [["feature_used", { feature: "nudge", surface: "preview", method: "keyboard" }]] + : [], + ); + act(() => root.unmount()); + element.remove(); + }, + ); +}); diff --git a/packages/studio/src/components/editor/useDomEditNudge.ts b/packages/studio/src/components/editor/useDomEditNudge.ts index 49129d5fc5..b1dae8ffb1 100644 --- a/packages/studio/src/components/editor/useDomEditNudge.ts +++ b/packages/studio/src/components/editor/useDomEditNudge.ts @@ -1,3 +1,4 @@ +import { trackPreviewEditResult } from "../../utils/previewFeatureUsage"; /** * Canvas arrow-key nudge for DomEditOverlay: arrows move the selected * element(s) 1 composition px, Shift = 10. Each keypress previews through the @@ -173,6 +174,7 @@ export function useDomEditNudge(params: UseDomEditNudgeParams): { flushNudge: () for (const member of session.members) restoreStudioPathOffset(member.element, member.initialPathOffset); saved = Promise.resolve(commit) + .then((result) => trackPreviewEditResult("nudge", "keyboard", result)) .catch(() => { for (const member of session.members) { if (isStudioManualEditGestureCurrent(member.element, member.gestureToken)) { diff --git a/packages/studio/src/components/editor/useDomEditOverlayGestures.ts b/packages/studio/src/components/editor/useDomEditOverlayGestures.ts index 4cc806e9ae..bd792ae38a 100644 --- a/packages/studio/src/components/editor/useDomEditOverlayGestures.ts +++ b/packages/studio/src/components/editor/useDomEditOverlayGestures.ts @@ -1,3 +1,4 @@ +import { trackPreviewEditResult } from "../../utils/previewFeatureUsage"; // fallow-ignore-file code-duplication /** * Gesture handling for DomEditOverlay. @@ -353,6 +354,7 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu const groupSaved = Promise.resolve( groupEdit.adopt(() => opts.onGroupPathOffsetCommitRef.current(updates)), ) + .then((result) => trackPreviewEditResult("move", "drag", result)) .catch(() => { for (const member of groupG.members) { if ( @@ -442,6 +444,7 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu applyRotationDraft(sel.element, finalRotation.angle, g.plainRotation); const commit = g.plainRotation ? { ...finalRotation, plain: g.plainRotation } : finalRotation; void Promise.resolve(opts.onRotationCommitRef.current(sel, commit)) + .then((result) => trackPreviewEditResult("rotate", "drag", result)) .catch((error) => { logGestureCommitFailure("rotate commit failed", error); if ( @@ -488,6 +491,7 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu }), ), ) + .then((result) => trackPreviewEditResult("move", "drag", result)) .catch(() => { if ( g.pathOffsetMember?.gestureToken && @@ -534,6 +538,7 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu void Promise.resolve( opts.onBoxSizeCommitRef.current(sel, finalSize, finalOffset ?? undefined, restore), ) + .then((result) => trackPreviewEditResult("resize", "drag", result)) .catch((error) => { logGestureCommitFailure("resize commit failed", error); }) diff --git a/packages/studio/src/components/editor/useDomEditZOrder.ts b/packages/studio/src/components/editor/useDomEditZOrder.ts index e504327741..037777abeb 100644 --- a/packages/studio/src/components/editor/useDomEditZOrder.ts +++ b/packages/studio/src/components/editor/useDomEditZOrder.ts @@ -1,3 +1,4 @@ +import { trackPreviewFeatureUsed } from "../../utils/previewFeatureUsage"; import { useCallback, useMemo } from "react"; import { useDomEditActionsContext } from "../../contexts/DomEditContext"; import { readHfId, type DomEditSelection } from "./domEditing"; @@ -156,8 +157,13 @@ export function useDomEditZOrder(): DomEditZOrder { // One serialized z→lane transaction: the mirror runs only AFTER a durable z commit and // no second gesture interleaves (see runZLaneGesture). A failed z commit has already // toasted and rolled back, so the catch only keeps its rejection from going unhandled. + let changed = false; runZLaneGesture({ - commitZ: () => handleDomZIndexReorderCommit(entries, coalesceKey, action), + commitZ: async () => { + const result = await handleDomZIndexReorderCommit(entries, coalesceKey, action); + changed = result?.durable === true && result.changed; + return result; + }, mirror: () => mirrorZOrderToTimeline({ selectionKey: entries.find((e) => e.element === sel.element)?.key, @@ -166,7 +172,11 @@ export function useDomEditZOrder(): DomEditZOrder { sourceFile: sel.sourceFile, coalesceKey, }), - }).catch(() => undefined); + }) + .then(() => { + if (changed) trackPreviewFeatureUsed("z_order", "button"); + }) + .catch(() => undefined); return true; }, [activeCompPath, handleDomZIndexReorderCommit, mirrorZOrderToTimeline, readOnly], diff --git a/packages/studio/src/components/nle/useCanvasZOrderTimelineMirror.ts b/packages/studio/src/components/nle/useCanvasZOrderTimelineMirror.ts index eb8b87831d..7d104ba9e3 100644 --- a/packages/studio/src/components/nle/useCanvasZOrderTimelineMirror.ts +++ b/packages/studio/src/components/nle/useCanvasZOrderTimelineMirror.ts @@ -2,13 +2,13 @@ import { useCallback, useRef } from "react"; import { usePlayerStore } from "../../player"; import { useTimelineEditContextOptional } from "../../contexts/TimelineEditContext"; import { - displayTrackOrder, resolveRepositionLaneMove, resolveZMirrorLaneMove, type ZMirrorAction, type ZMirrorLaneMove, } from "../../player/components/timelineZMirror"; import type { TimelineElement } from "../../player/store/playerStore"; +import { timelineTrackOrder } from "../../player/components/timelineTrackDisplay"; import { commitZMirrorLaneMove } from "../../player/components/timelineClipDragCommit"; import { deriveTimelineStoreKey } from "../../player/lib/timelineElementHelpers"; import { buildStableSelector, getSelectorIndex } from "../editor/domEditingDom"; @@ -156,7 +156,7 @@ function useMirrorLaneMoveCommit(): ( move, { elements: els, - trackOrder: displayTrackOrder(els), + trackOrder: timelineTrackOrder(els), updateElement: (key, updates) => usePlayerStore.getState().updateElement(key, updates), onMoveElements, // NO readZIndex / onStackingPatches: see the hook doc — the lane→z diff --git a/packages/studio/src/components/nle/useTimelineEditCallbacks.test.tsx b/packages/studio/src/components/nle/useTimelineEditCallbacks.test.tsx index 06e599ea0c..53a6a64270 100644 --- a/packages/studio/src/components/nle/useTimelineEditCallbacks.test.tsx +++ b/packages/studio/src/components/nle/useTimelineEditCallbacks.test.tsx @@ -409,6 +409,7 @@ describe("useTimelineEditCallbacks — flat tween keyframe lanes", () => { expect(mocks.actions.handleGsapRemoveAllKeyframes).toHaveBeenCalledWith( scaleAnimation.id, circleSelection, + false, ); view.unmount(); }); diff --git a/packages/studio/src/components/nle/useTimelineEditCallbacks.ts b/packages/studio/src/components/nle/useTimelineEditCallbacks.ts index 8f66485f15..a1adfe2b2d 100644 --- a/packages/studio/src/components/nle/useTimelineEditCallbacks.ts +++ b/packages/studio/src/components/nle/useTimelineEditCallbacks.ts @@ -1,4 +1,5 @@ import type { TimelineEditOutcome } from "../../hooks/timelineEditPermission"; +import { trackKeyframeUsage } from "../../utils/keyframeUsage"; import { useCallback, useMemo } from "react"; import type { GsapAnimation } from "@hyperframes/core/gsap-parser"; import type { TimelineElement } from "../../player"; @@ -259,7 +260,12 @@ export function useTimelineEditCallbacks({ if (!selection) return; // Serial: each removal rewrites the same source file, so dispatching // them together would have the later writes read a pre-edit document. - for (const anim of anims) await handleGsapRemoveAllKeyframes(anim.id, selection); + let changed = false; + for (const anim of anims) { + const result = await handleGsapRemoveAllKeyframes(anim.id, selection, false); + changed = result || changed; + } + if (changed) trackKeyframeUsage("remove_all"); }); }, onDeleteKeyframe: (elId, keyframe) => { diff --git a/packages/studio/src/contexts/DomEditContext.tsx b/packages/studio/src/contexts/DomEditContext.tsx index 7673ddb3ea..40b2b74285 100644 --- a/packages/studio/src/contexts/DomEditContext.tsx +++ b/packages/studio/src/contexts/DomEditContext.tsx @@ -253,7 +253,7 @@ export function DomEditProvider({ commitMutationRef.current = commitMutation; const stableCommitMutation = useCallback( - (mutation, options) => commitMutationRef.current(mutation, options), + (mutation, options, selection) => commitMutationRef.current(mutation, options, selection), [], ); diff --git a/packages/studio/src/domEditExports.test.tsx b/packages/studio/src/domEditExports.test.tsx index f67a900730..a9bb7d2184 100644 --- a/packages/studio/src/domEditExports.test.tsx +++ b/packages/studio/src/domEditExports.test.tsx @@ -79,7 +79,7 @@ describe("DOM editing package exports", () => { front.id = "front"; parent.append(back, front); document.body.append(parent); - const commitZ = vi.fn(() => Promise.resolve()); + const commitZ = vi.fn(async () => ({ durable: true, changed: true })); const session = { handleDomZIndexReorderCommit: commitZ, } as unknown as Parameters[0]["value"]; @@ -107,6 +107,11 @@ describe("DOM editing package exports", () => { await act(async () => { expect(zOrder?.apply(sel, toFront)).toBe(true); }); + expect(trackStudioEvent).toHaveBeenCalledWith("feature_used", { + feature: "z_order", + surface: "preview", + method: "button", + }); expect(commitZ).toHaveBeenCalledTimes(1); expect(commitZ).toHaveBeenCalledWith( expect.arrayContaining([expect.objectContaining({ element: back, id: "back" })]), @@ -159,3 +164,6 @@ describe("DOM editing package exports", () => { await act(async () => root.unmount()); }); }); + +vi.mock("./utils/studioTelemetry", () => ({ trackStudioEvent: vi.fn() })); +import { trackStudioEvent } from "./utils/studioTelemetry"; diff --git a/packages/studio/src/hooks/domEditCommitRunner.ts b/packages/studio/src/hooks/domEditCommitRunner.ts index 623e25d079..e16f26def4 100644 --- a/packages/studio/src/hooks/domEditCommitRunner.ts +++ b/packages/studio/src/hooks/domEditCommitRunner.ts @@ -94,7 +94,7 @@ export type DomEditCommitDeclineReason = | "persist-failed"; export type DomEditCommitOutcome = - | { ok: true; persistence?: DomEditPersistOutcome } + | { ok: true; persistence?: DomEditPersistOutcome; changed?: boolean } | { ok: false; reason: DomEditCommitDeclineReason }; export function domEditCommitDeclined(reason: DomEditCommitDeclineReason): DomEditCommitOutcome { diff --git a/packages/studio/src/hooks/elementOffsetStager.ts b/packages/studio/src/hooks/elementOffsetStager.ts index f87db4f919..9ea191ce45 100644 --- a/packages/studio/src/hooks/elementOffsetStager.ts +++ b/packages/studio/src/hooks/elementOffsetStager.ts @@ -1,3 +1,4 @@ +import type { DomEditPersistOutcome } from "./domEditCommitTypes"; import { getDomEditTargetKey, type DomEditSelection } from "../components/editor/domEditing"; import { applyElementPositionOffset, @@ -23,7 +24,7 @@ export interface ElementOffsetStagerDeps { selection: DomEditSelection, patches: PatchOperation[], options: { label: string; coalesceKey: string; coalesceMs?: number }, - ) => Promise; + ) => Promise; showToast: (message: string, tone?: "error" | "info") => void; readOnlyPreview?: boolean; } @@ -59,7 +60,7 @@ function stagePlainTranslate( selection: DomEditSelection, next: { x: number; y: number }, coalesceKey?: string, -): { save: () => Promise; rollback: () => void } { +): { save: () => Promise; rollback: () => void } { const el = selection.element; const before = captureStudioPathOffset(el); const patches = writePlainMove(el, next); @@ -85,9 +86,9 @@ export function stageElementOffset( next: { x: number; y: number }, plainTranslate: boolean, coalesceKey?: string, -): { save: () => Promise; rollback: () => void } { +): { save: () => Promise; rollback: () => void } { const el = selection.element; - if (readOnlyPreview) return { save: () => Promise.resolve(), rollback: () => undefined }; + if (readOnlyPreview) return { save: () => Promise.resolve(undefined), rollback: () => undefined }; if (plainTranslate) { refuseGsapTakeover(el, showToast); return stagePlainTranslate(commitPositionPatchToHtml, selection, next, coalesceKey); diff --git a/packages/studio/src/hooks/gsapDragCommit.ts b/packages/studio/src/hooks/gsapDragCommit.ts index ef406a14a6..a542dbafb1 100644 --- a/packages/studio/src/hooks/gsapDragCommit.ts +++ b/packages/studio/src/hooks/gsapDragCommit.ts @@ -9,7 +9,7 @@ import { resolveTweenStart, resolveTweenDuration } from "../utils/globalTimeComp import { roundTo3, roundToLayoutPx } from "../utils/rounding"; import { computeElementPercentage, keyframeEases, writeTargetSelector } from "./gsapShared"; import { computeDraggedGsapPosition } from "./draggedGsapPosition"; -import type { RuntimeTweenChange } from "./gsapRuntimePatch"; +import type { CommitMutation } from "./gsapScriptCommitTypes"; import { isGestureTransactionCommit, runGestureTransaction } from "./gestureTransaction"; import { setPatchFromUpdateProperty } from "./gsapDragStaticSetHelpers"; import { GsapEditBlockedError } from "./gsapEditOutcome"; @@ -19,25 +19,7 @@ export { findSizeSetAnimation, } from "./gsapDragStaticSetHelpers"; export interface GsapDragCommitCallbacks { - commitMutation: ( - selection: DomEditSelection, - mutation: Record, - options: { - label: string; - coalesceKey?: string; - coalesceMs?: number; - softReload?: boolean; - skipReload?: boolean; - beforeReload?: () => void; - /** - * Value-only fast path: when set, `runCommit` patches the changed tween in - * the preview runtime in place (instant, no re-run) and only falls back to - * the soft reload if the patch can't be safely applied. Attached only to - * value-only `set` commits; structural/keyframe commits omit it. - */ - instantPatch?: { selector: string; change: RuntimeTweenChange }; - }, - ) => Promise; + commitMutation: CommitMutation; fetchAnimations?: () => Promise; } diff --git a/packages/studio/src/hooks/gsapGestureOutcome.test.ts b/packages/studio/src/hooks/gsapGestureOutcome.test.ts new file mode 100644 index 0000000000..7440eae90c --- /dev/null +++ b/packages/studio/src/hooks/gsapGestureOutcome.test.ts @@ -0,0 +1,161 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { trackKeyframeCommit } from "../utils/keyframeUsage"; +import { observeGsapGesture } from "./gsapGestureOutcome"; +import type { CommitMutation, MutationResult } from "./gsapScriptCommitTypes"; +import { trackStudioEvent } from "../utils/studioTelemetry"; + +vi.mock("../utils/studioTelemetry", () => ({ trackStudioEvent: vi.fn() })); +beforeEach(() => vi.clearAllMocks()); +const selection = {} as Parameters[0]; +const mutation = { + type: "add-keyframe", + animationId: "private-target", + properties: { text: "private-content" }, +}; +function writer(result?: MutationResult): CommitMutation { + const commit: CommitMutation = async (_selection, _mutation, options) => { + if (result) options.onResult?.(result); + }; + commit.batch = async (_calls, options) => { + if (result) options.onResult?.(result); + }; + return commit; +} + +describe("GSAP gesture usage", () => { + it("counts a multi-write add gesture once from successful writer results", async () => { + const observed = observeGsapGesture( + writer({ ok: true, changed: true, mutationChanges: [true] }), + ); + const onResult = vi.fn(); + await observed.commit!( + selection, + { type: "convert-to-keyframes" }, + { label: "Convert", onResult }, + ); + await observed.commit!(selection, mutation, { label: "Add" }); + expect(trackStudioEvent).not.toHaveBeenCalled(); + expect(observed.finish()).toEqual({ ok: true, changed: true }); + expect(onResult).toHaveBeenCalledWith({ ok: true, changed: true, mutationChanges: [true] }); + expect(trackStudioEvent).toHaveBeenCalledExactlyOnceWith("keyframe", { action: "add" }); + }); + + it("counts a batched insertion once", async () => { + const observed = observeGsapGesture( + writer({ ok: true, changed: true, mutationChanges: [true, true] }), + ); + await observed.commit!.batch!( + [ + { selection, mutation, options: { label: "Add" } }, + { selection, mutation, options: { label: "Add" } }, + ], + { label: "Add together" }, + ); + expect(observed.finish().changed).toBe(true); + expect(trackStudioEvent).toHaveBeenCalledExactlyOnceWith("keyframe", { action: "add" }); + }); + + it("retains insertion metadata from an earlier member of a mixed batch", async () => { + const observed = observeGsapGesture( + writer({ ok: true, changed: true, mutationChanges: [true, true] }), + ); + await observed.commit!.batch!( + [ + { + selection, + mutation: { type: "replace-with-keyframes" }, + options: { label: "Extend", keyframeAction: "add" }, + }, + { selection, mutation: { type: "update-keyframe" }, options: { label: "Update" } }, + ], + { label: "Update" }, + ); + observed.finish(); + expect(trackStudioEvent).toHaveBeenCalledExactlyOnceWith("keyframe", { action: "add" }); + }); + + it("uses semantic insertion metadata for a replacement", async () => { + const observed = observeGsapGesture( + writer({ ok: true, changed: true, mutationChanges: [true] }), + ); + await observed.commit!( + selection, + { type: "replace-with-keyframes" }, + { label: "Replace", keyframeAction: "add" }, + ); + observed.finish(); + expect(trackStudioEvent).toHaveBeenCalledExactlyOnceWith("keyframe", { action: "add" }); + }); + + it.each([undefined, { ok: true }, { ok: true, changed: false }, { ok: false, changed: true }])( + "does not count resolution without a changed successful write (%j)", + async (result) => { + const observed = observeGsapGesture(writer(result)); + await observed.commit!(selection, mutation, { label: "Add" }); + expect(observed.finish()).toEqual({ ok: true, changed: false }); + expect(trackStudioEvent).not.toHaveBeenCalled(); + }, + ); + + it("does not count missing writers or an unfinished group", async () => { + expect(observeGsapGesture(null).finish()).toEqual({ ok: true, changed: false }); + const observed = observeGsapGesture(writer()); + await observed.commit!(selection, mutation, { label: "Add" }); + expect(observed.finish(true).changed).toBe(false); + expect(trackStudioEvent).not.toHaveBeenCalled(); + }); + + it("reports a successful plain DOM gesture without inventing keyframes", () => { + expect(observeGsapGesture(null).finish(true).changed).toBe(true); + expect(trackStudioEvent).not.toHaveBeenCalled(); + }); +}); + +it.each([ + [[false, true], 0], + [[true, false], 1], + [undefined, 0], +] as const)( + "attributes mixed batches only to changed members (%j)", + async (mutationChanges, count) => { + const result = { + ok: true, + changed: true, + mutationChanges: mutationChanges && [...mutationChanges], + }; + const observed = observeGsapGesture(writer(result)); + const mutations = [mutation, { type: "update-property" }]; + await observed.commit!.batch!( + mutations.map((mutation) => ({ selection, mutation, options: { label: "Edit" } })), + { label: "Edit" }, + ); + expect(observed.finish()).toEqual({ ok: true, changed: true }); + expect(trackStudioEvent).toHaveBeenCalledTimes(count); + if (count) expect(trackStudioEvent).toHaveBeenCalledWith("keyframe", { action: "add" }); + vi.mocked(trackStudioEvent).mockClear(); + trackKeyframeCommit(mutations, result, { label: "Edit" }); + expect(trackStudioEvent).toHaveBeenCalledTimes(count); + }, +); + +it("excludes a suppressed preparation from mixed-batch attribution", async () => { + const result = { ok: true, changed: true, mutationChanges: [true, false] }; + const calls = [ + { + selection, + mutation: { type: "convert-to-keyframes" }, + options: { label: "Prepare", keyframeTelemetry: false }, + }, + { selection, mutation, options: { label: "Add" } }, + ]; + const observed = observeGsapGesture(writer(result)); + await observed.commit!.batch!(calls, { label: "Add" }); + expect(observed.finish()).toEqual({ ok: true, changed: true }); + trackKeyframeCommit( + calls.map((call) => call.mutation), + result, + { label: "Add" }, + calls.map((call) => call.options), + ); + expect(trackStudioEvent).not.toHaveBeenCalled(); +}); diff --git a/packages/studio/src/hooks/gsapGestureOutcome.ts b/packages/studio/src/hooks/gsapGestureOutcome.ts new file mode 100644 index 0000000000..9016e10434 --- /dev/null +++ b/packages/studio/src/hooks/gsapGestureOutcome.ts @@ -0,0 +1,64 @@ +import type { + CommitMutationCall, + CommitMutation, + CommitMutationOptions, + MutationResult, +} from "./gsapScriptCommitTypes"; +import { + keyframeUsageActions, + changedMutationIndices, + primaryKeyframeAction, + trackKeyframeUsage, + type KeyframeUsageAction, +} from "../utils/keyframeUsage"; +import type { GeometryCommitResult } from "../utils/previewFeatureUsage"; + +export function observeGsapGesture(writer: CommitMutation | null) { + let changed = false; + let pendingResults = 0; + const actions = new Set(); + const observe = (calls: CommitMutationCall[], options: CommitMutationOptions) => { + pendingResults += 1; + return { + ...options, + keyframeTelemetry: false, + onResult: (result: MutationResult) => { + pendingResults -= 1; + options.onResult?.(result); + if (!result.ok || result.changed !== true) return; + changed = true; + const members = changedMutationIndices( + result, + calls.length, + calls.map((call) => call.options), + ).map((index) => calls[index]!); + for (const action of keyframeUsageActions( + members.map((call) => call.mutation), + members.map((call) => call.options.keyframeAction), + )) + actions.add(action); + }, + }; + }; + let commit: CommitMutation | null = null; + if (writer) { + commit = (selection, mutation, options) => + writer(selection, mutation, observe([{ selection, mutation, options }], options)); + if (writer.batch) { + const batch = writer.batch; + commit.batch = (calls, options) => batch(calls, observe(calls, options)); + } + } + return { + commit, + recordDomResult: (result: { changed: boolean } | undefined) => { + changed ||= result?.changed === true; + }, + finish: (domChanged = false): GeometryCommitResult => { + if (pendingResults !== 0) return { ok: true, changed: false }; + const action = primaryKeyframeAction(actions); + if (action) trackKeyframeUsage(action); + return { ok: true, changed: changed || domChanged }; + }, + }; +} diff --git a/packages/studio/src/hooks/gsapKeyframeCommit.ts b/packages/studio/src/hooks/gsapKeyframeCommit.ts index ed3ecc498e..974368c435 100644 --- a/packages/studio/src/hooks/gsapKeyframeCommit.ts +++ b/packages/studio/src/hooks/gsapKeyframeCommit.ts @@ -4,23 +4,14 @@ import { absoluteToPercentageForAnimation, findTweenAtTime } from "../utils/glob import { PROPERTY_DEFAULTS, selectorFromSelection, writeTargetSelector } from "./gsapShared"; import { roundToCenti } from "../utils/rounding"; -type CommitFn = ( - selection: DomEditSelection, - mutation: Record, - options: { - label: string; - coalesceKey?: string; - softReload?: boolean; - skipReload?: boolean; - }, -) => Promise; +import type { CommitMutation } from "./gsapScriptCommitTypes"; export async function commitKeyframeAtTimeImpl( selection: DomEditSelection, absoluteTime: number, animations: GsapAnimation[], properties: Record, - commitMutation: CommitFn, + commitMutation: CommitMutation, ): Promise { // Matching an authored tween is a string compare against what the author // wrote, so it keeps using the selection's own selector; the NEW tween below @@ -38,7 +29,7 @@ export async function commitKeyframeAtTimeImpl( await commitMutation( selection, { type: "convert-to-keyframes", animationId: tween.id }, - { label: "Convert to keyframes", skipReload: true }, + { label: "Convert to keyframes", keyframeTelemetry: false, skipReload: true }, ); } diff --git a/packages/studio/src/hooks/gsapResizeIntercept.test.ts b/packages/studio/src/hooks/gsapResizeIntercept.test.ts index f2fc173a3f..1fb7afe9f9 100644 --- a/packages/studio/src/hooks/gsapResizeIntercept.test.ts +++ b/packages/studio/src/hooks/gsapResizeIntercept.test.ts @@ -3,11 +3,17 @@ import { afterEach, expect, it, vi } from "vitest"; import type { GsapAnimation } from "@hyperframes/core/gsap-parser"; import type { DomEditSelection } from "../components/editor/domEditingTypes"; import { usePlayerStore } from "../player/store/playerStore"; +import { observeGsapGesture } from "./gsapGestureOutcome"; +import { trackStudioEvent } from "../utils/studioTelemetry"; +import type { CommitMutation } from "./gsapScriptCommitTypes"; import { computeCurrentPercentage } from "./gsapDragCommit"; import { commitSizeAtPlayhead, tryGsapResizeIntercept } from "./gsapResizeIntercept"; import { liveTween, previewWith, tween } from "./gsapParsedTween.test-helpers"; +vi.mock("../utils/studioTelemetry", () => ({ trackStudioEvent: vi.fn() })); + afterEach(() => { + vi.clearAllMocks(); vi.restoreAllMocks(); usePlayerStore.setState({ currentTime: 0, activeKeyframePct: null }); // One #clip per test: leftovers would make every tween on it look shared. @@ -605,3 +611,30 @@ it.each([ expect(mutation.keyframes[0].properties).toEqual(written); }, ); + +it.each([ + [5, 1], + [0.5, 1], + [0.2, 0], +])("counts scale resize insertion at %ss", async (time, count) => { + const el = makeGradedElement(); + const iframe = fakeIframe(el, { scale: 1, scaleX: 1, scaleY: 1 }); + usePlayerStore.setState({ currentTime: time, activeKeyframePct: null }); + const writer: CommitMutation = async (_selection, _mutation, options) => { + options.onResult?.({ ok: true, changed: true }); + }; + const outcome = observeGsapGesture(writer); + const result = await tryGsapResizeIntercept( + { id: "clip", selector: "#clip", element: el } as DomEditSelection, + { width: 700, height: 400 }, + [keyframedScaleFixture()], + iframe, + outcome.commit!, + ); + expect(result.status).toBe("persisted"); + outcome.finish(); + expect(trackStudioEvent).toHaveBeenCalledTimes(count); + if (count) expect(trackStudioEvent).toHaveBeenCalledWith("keyframe", { action: "add" }); + el.remove(); + document.querySelector("#__hf_color_grading_clip")?.remove(); +}); diff --git a/packages/studio/src/hooks/gsapRuntimeKeyframes.ts b/packages/studio/src/hooks/gsapRuntimeKeyframes.ts index 038578768d..53e721ab1c 100644 --- a/packages/studio/src/hooks/gsapRuntimeKeyframes.ts +++ b/packages/studio/src/hooks/gsapRuntimeKeyframes.ts @@ -428,7 +428,7 @@ export const GSAP_TRANSFORM_KEYS = new Set( ); /** Whether a live timeline tween or hold writes any of `channels` on `el`. Sync, no fetch. */ -function gsapWritesChannels(el: Element, channels: string[]): boolean { +export function gsapWritesChannels(el: Element, channels: string[]): boolean { const win = el.ownerDocument.defaultView as { __timelines?: Record }; return Object.values(win?.__timelines ?? {}).some((tl) => (tl?.getChildren?.(true) ?? []).some( diff --git a/packages/studio/src/hooks/gsapRuntimeReaders.test.ts b/packages/studio/src/hooks/gsapRuntimeReaders.test.ts index b65f59237e..4e2f5485ea 100644 --- a/packages/studio/src/hooks/gsapRuntimeReaders.test.ts +++ b/packages/studio/src/hooks/gsapRuntimeReaders.test.ts @@ -1,5 +1,6 @@ // @vitest-environment jsdom import { afterEach, describe, expect, it } from "vitest"; +import { gsap } from "gsap"; import type { GsapAnimation } from "@hyperframes/core/gsap-parser"; import { COLOR_GRADING_SOURCE_HIDDEN_ATTR, @@ -109,3 +110,50 @@ describe("color-grading opacity truth", () => { expect(readGsapProperty(iframe, "#clip", "opacity")).toBe(0.3); }); }); + +describe("readAllAnimatedProperties with a sibling tween", () => { + it("leaves a sibling tween's rotation to that tween after an opacity keyframe edit", () => { + const el = document.createElement("div"); + el.id = "clip"; + document.body.appendChild(el); + const build = (keyframes: Record>) => { + const tl = gsap.timeline({ paused: true }); + tl.to(el, { duration: 4, ease: "none", keyframes }, 0); + tl.to(el, { rotation: 90, duration: 3 }, 0); + return tl; + }; + const live = build({ "0%": { opacity: 0 }, "100%": { opacity: 1 } }); + live.seek(2); + const iframe = { + contentWindow: { __timelines: { main: live }, gsap }, + contentDocument: document, + } as unknown as HTMLIFrameElement; + const anim = { + id: "#clip-to-0-visual", + targetSelector: "#clip", + method: "to", + properties: {}, + keyframes: { + keyframes: [ + { percentage: 0, properties: { opacity: 0 } }, + { percentage: 100, properties: { opacity: 1 } }, + ], + }, + } as unknown as GsapAnimation; + + // commitKeyframeProps: these values plus the edit at the playhead, and backfilled into the rest. + const read = readAllAnimatedProperties(iframe, "#clip", anim); + live.kill(); + gsap.set(el, { clearProps: "all" }); + const edited = build({ + "0%": { ...read, opacity: 0 }, + "50%": { ...read, opacity: 0.3 }, + "100%": { ...read, opacity: 1 }, + }); + edited.seek(3.2); + edited.seek(3.5); + + expect(gsap.getProperty(el, "rotation")).toBe(90); + edited.kill(); + }); +}); diff --git a/packages/studio/src/hooks/gsapRuntimeReaders.ts b/packages/studio/src/hooks/gsapRuntimeReaders.ts index 48d2ed3ffc..0bc7203ac4 100644 --- a/packages/studio/src/hooks/gsapRuntimeReaders.ts +++ b/packages/studio/src/hooks/gsapRuntimeReaders.ts @@ -8,6 +8,7 @@ import { HF_COLOR_GRADING_CANVAS_ID_PREFIX, } from "@hyperframes/core/color-grading"; import { getIframeGsap, queryIframeElement, type IframeGsap } from "./gsapShared"; +import { gsapWritesChannels } from "./gsapRuntimeKeyframes"; import { roundTo3 } from "../utils/rounding"; /** @@ -50,27 +51,6 @@ export function readGsapProperty( } export const POSITION_PROPS = new Set(["x", "y", "xPercent", "yPercent"]); -const GSAP_CONFIG_KEYS = new Set([ - "duration", - "ease", - "delay", - "stagger", - "id", - "onComplete", - "onUpdate", - "onStart", - "onRepeat", - "repeat", - "yoyo", - "repeatDelay", - "paused", - "immediateRender", - "lazy", - "overwrite", - "keyframes", - "parent", -]); - export function readAllAnimatedProperties( iframe: HTMLIFrameElement | null, selector: string, @@ -115,74 +95,7 @@ export function readAllAnimatedProperties( } } - const otherTweenProps = new Set(); - try { - const win = iframe.contentWindow as unknown as { __timelines?: Record }; - const timelines = win.__timelines; - if (timelines) { - for (const tl of Object.values(timelines)) { - const tlObj = tl as { - getChildren?: ( - deep: boolean, - ) => Array<{ targets?: () => Element[]; vars?: Record }>; - }; - if (!tlObj?.getChildren) continue; - for (const child of tlObj.getChildren(true)) { - if (typeof child.targets !== "function") continue; - const targets = child.targets(); - if (!targets.includes(el)) continue; - const vars = child.vars; - if (!vars) continue; - for (const k of Object.keys(vars)) { - if (!GSAP_CONFIG_KEYS.has(k) && inGroup(k)) otherTweenProps.add(k); - } - } - } - } - } catch {} - for (const p of groupedPropKeys) otherTweenProps.delete(p); - - // Tier 1: Transform + visual properties with universal CSS defaults. - // Safe to compare against hardcoded values — these are always 0 or 1 - // regardless of the element's stylesheet. - const UNIVERSAL_BASELINE: Record = { - opacity: 1, - scale: 1, - scaleX: 1, - scaleY: 1, - scaleZ: 1, - rotation: 0, - rotationX: 0, - rotationY: 0, - skewX: 0, - skewY: 0, - z: 0, - xPercent: 0, - yPercent: 0, - transformPerspective: 0, - blur: 0, - brightness: 1, - contrast: 1, - saturate: 1, - hueRotate: 0, - grayscale: 0, - sepia: 0, - invert: 0, - }; - // Collect all properties that ANY tween on this element explicitly targets. - // Only capture baseline values for these — GSAP reports non-default values - // (scaleZ=0, brightness=0) for untouched properties, polluting keyframes. - const allTweenedProps = new Set([...groupedPropKeys, ...otherTweenProps]); - for (const [prop, defaultVal] of Object.entries(UNIVERSAL_BASELINE)) { - if (prop in result) continue; - if (!allTweenedProps.has(prop)) continue; - const val = readLiveGsapValue(gsap, el, prop); - if (Number.isFinite(val) && Math.round(val * 1000) !== Math.round(defaultVal * 1000)) { - result[prop] = roundTo3(val); - } - } - - // Tier 2: Element-dependent properties — their "default" depends on the + // Element-dependent properties — their "default" depends on the // stylesheet, so we compare GSAP's runtime value against the element's // computed CSS value. Only capture if GSAP has actively changed it. const COMPUTED_BASELINE = [ @@ -209,7 +122,7 @@ export function readAllAnimatedProperties( for (const prop of COMPUTED_BASELINE) { if (prop in result) continue; if (!inGroup(prop)) continue; - if (otherTweenProps.has(prop)) continue; + if (gsapWritesChannels(el, [prop])) continue; const gsapVal = Number(gsap.getProperty(el, prop)); if (!Number.isFinite(gsapVal)) continue; let cssVal = NaN; diff --git a/packages/studio/src/hooks/gsapScriptCommitTypes.ts b/packages/studio/src/hooks/gsapScriptCommitTypes.ts index ed292c649f..5682587ad5 100644 --- a/packages/studio/src/hooks/gsapScriptCommitTypes.ts +++ b/packages/studio/src/hooks/gsapScriptCommitTypes.ts @@ -3,10 +3,12 @@ import type { Composition } from "@hyperframes/sdk"; import type { DomEditSelection } from "../components/editor/domEditingTypes"; import type { PublishSdkSession } from "../utils/sdkCutover"; import type { RuntimeTweenChange } from "./gsapRuntimePatch"; +import type { KeyframeUsageAction } from "../utils/keyframeUsage"; export interface MutationResult { ok: boolean; changed?: boolean; + mutationChanges?: boolean[]; parsed?: ParsedGsap; before?: string; after?: string; @@ -15,6 +17,9 @@ export interface MutationResult { export interface CommitMutationOptions { label: string; + keyframeTelemetry?: boolean; + keyframeAction?: KeyframeUsageAction; + keyframeProperty?: string; /** Observe the durable writer result without duplicating the request path. */ onResult?: (result: MutationResult) => void; coalesceKey?: string; diff --git a/packages/studio/src/hooks/gsapShared.writeTarget.test.ts b/packages/studio/src/hooks/gsapShared.writeTarget.test.ts index 6e7b504d39..f1ae8ca2e3 100644 --- a/packages/studio/src/hooks/gsapShared.writeTarget.test.ts +++ b/packages/studio/src/hooks/gsapShared.writeTarget.test.ts @@ -6,6 +6,10 @@ import type { DomEditSelection } from "../components/editor/domEditingTypes"; import { mountGroupSiblings, stableSelectionFor } from "./domSelectionTestHarness"; import { resolveSelectorElementIds, tweenTargetsElement, writeTargetSelector } from "./gsapShared"; import { commitKeyframeAtTimeImpl } from "./gsapKeyframeCommit"; +import { trackStudioEvent } from "../utils/studioTelemetry"; +import { trackKeyframeCommit } from "../utils/keyframeUsage"; +import type { CommitMutation } from "./gsapScriptCommitTypes"; +vi.mock("../utils/studioTelemetry", () => ({ trackStudioEvent: vi.fn() })); import { promoteSetToKeyframes } from "./useEnableKeyframes"; afterEach(() => { @@ -255,3 +259,19 @@ describe("commitKeyframeAtTimeImpl — no one-element target", () => { expect(commitMutation).not.toHaveBeenCalled(); }); }); + +it("counts a keyframe-at-time conversion and insertion as one add gesture", async () => { + vi.clearAllMocks(); + const el = document.createElement("div"); + el.id = "target"; + document.body.append(el); + const selection = selectionFor(el); + const animations = parseGsapScript( + 'const tl = gsap.timeline(); tl.to("#target", {x:100,duration:4},0);', + ).animations; + const commit: CommitMutation = async (_selection, mutation, options) => { + trackKeyframeCommit([mutation], { ok: true, changed: true }, options); + }; + await commitKeyframeAtTimeImpl(selection, 1, animations, { x: 25 }, commit); + expect(trackStudioEvent).toHaveBeenCalledExactlyOnceWith("keyframe", { action: "add" }); +}); diff --git a/packages/studio/src/hooks/gsapValueAtPlayhead.ts b/packages/studio/src/hooks/gsapValueAtPlayhead.ts index 2a43626b4f..b2f9a33159 100644 --- a/packages/studio/src/hooks/gsapValueAtPlayhead.ts +++ b/packages/studio/src/hooks/gsapValueAtPlayhead.ts @@ -57,6 +57,8 @@ export type PlayheadEditPlan = keyframes: Keyframe[]; easeEach?: string; }; + /** A keyframe was added, not only changed: keyframe usage counts it as an add. */ + added: boolean; } | { ok: false; reason: PlayheadEditRefusal }; @@ -185,6 +187,7 @@ export function planValueAtPlayhead(edit: PlayheadEdit): PlayheadEditPlan { } if (Object.keys(values).some((prop) => !keyframes.some((kf) => kf.properties[prop] != null))) return refuse("implicit-end-unknown"); + const authored = keyframes.length; let position = start; let span = duration; @@ -231,6 +234,7 @@ export function planValueAtPlayhead(edit: PlayheadEdit): PlayheadEditPlan { keyframes, ...(norm.easeEach ? { easeEach: norm.easeEach } : {}), }, + added: keyframes.length > authored, }; } @@ -278,6 +282,7 @@ export async function commitValueAtPlayhead( label: options.label, softReload: true, beforeReload: options.beforeReload, + ...(plan.added && { keyframeAction: "add" as const }), }); if (activeKeyframePct != null) { setActiveKeyframePct(null); diff --git a/packages/studio/src/hooks/plainRotation.ts b/packages/studio/src/hooks/plainRotation.ts index b1f163abc6..f96cb0f7de 100644 --- a/packages/studio/src/hooks/plainRotation.ts +++ b/packages/studio/src/hooks/plainRotation.ts @@ -1,3 +1,4 @@ +import type { DomEditPersistOutcome } from "./domEditCommitTypes"; import type { DomEditSelection } from "../components/editor/domEditing"; import { captureStudioRotation, clearStudioRotation } from "../components/editor/manualEdits"; import { buildClearRotationPatches } from "../components/editor/manualEditsDomPatches"; @@ -17,8 +18,8 @@ export function savePlainRotation( { commitPositionPatchToHtml, readOnlyPreview }: Omit, selection: DomEditSelection, next: RotationCommit, -): Promise { - if (readOnlyPreview) return Promise.resolve(); +): Promise { + if (readOnlyPreview) return Promise.resolve(undefined); const { element } = selection; const before = captureStudioRotation(element); // Legacy marks go in the same write, or a seek puts their angle back; clearing them voids the press read. diff --git a/packages/studio/src/hooks/previewPromotionSelection.test.tsx b/packages/studio/src/hooks/previewPromotionSelection.test.tsx index 06fd90b5d2..a60a4b4e0c 100644 --- a/packages/studio/src/hooks/previewPromotionSelection.test.tsx +++ b/packages/studio/src/hooks/previewPromotionSelection.test.tsx @@ -101,7 +101,7 @@ describe("a shadow reload promoted without a host re-render", () => { }); expect(overlayNode).toBe(selection.element); - const commitPositionPatchToHtml = vi.fn(async () => {}); + const commitPositionPatchToHtml = vi.fn(async () => undefined); await savePlainRotation({ commitPositionPatchToHtml }, selection, { angle: 30 }); await stageElementOffset( { commitPositionPatchToHtml, showToast: vi.fn() }, diff --git a/packages/studio/src/hooks/refreshTimelineRowText.test.ts b/packages/studio/src/hooks/refreshTimelineRowText.test.ts new file mode 100644 index 0000000000..5c7f59e70c --- /dev/null +++ b/packages/studio/src/hooks/refreshTimelineRowText.test.ts @@ -0,0 +1,65 @@ +// @vitest-environment happy-dom +import { afterEach, describe, expect, it } from "vitest"; +import { usePlayerStore, type TimelineElement } from "../player/store/playerStore"; +import { refreshTimelineRowText } from "./refreshTimelineRowText"; + +afterEach(() => { + usePlayerStore.getState().reset(); + document.body.innerHTML = ""; +}); + +const row = (key: string, selector: string, sourceFile?: string): TimelineElement => ({ + id: key.split("#").pop()!, + key, + tag: "p", + start: 0, + duration: 2, + track: 0, + selector, + selectorIndex: 0, + sourceFile, + text: { value: "Old" }, +}); + +describe("refreshTimelineRowText", () => { + it("gives the edited layer's row, addressed by its store key, its new words", () => { + document.body.innerHTML = `

New words

`; + usePlayerStore.getState().setElements([row("index.html#title", "#title")]); + + refreshTimelineRowText(document.getElementById("title")!); + + expect(usePlayerStore.getState().elements[0]?.text?.value).toBe("New words"); + }); + + it("finds a row known only by its data-hf-id", () => { + document.body.innerHTML = `

New

`; + usePlayerStore + .getState() + .setElements([ + { ...row("index.html#caption-a", ""), selector: undefined, hfId: "caption-a" }, + ]); + + refreshTimelineRowText(document.querySelector("p")!); + + expect(usePlayerStore.getState().elements[0]?.text?.value).toBe("New"); + }); + + it("finds the row in the edited layer's own composition when two share a selector", () => { + document.body.innerHTML = ` +

A

+

B new

`; + usePlayerStore + .getState() + .setElements([ + row("a.html#a-caption", ".caption", "a.html"), + row("b.html#b-caption", ".caption", "b.html"), + ]); + + refreshTimelineRowText(document.querySelectorAll(".caption")[1]!); + + expect(usePlayerStore.getState().elements.map((element) => element.text?.value)).toEqual([ + "Old", + "B new", + ]); + }); +}); diff --git a/packages/studio/src/hooks/refreshTimelineRowText.ts b/packages/studio/src/hooks/refreshTimelineRowText.ts new file mode 100644 index 0000000000..afe3668bc1 --- /dev/null +++ b/packages/studio/src/hooks/refreshTimelineRowText.ts @@ -0,0 +1,29 @@ +import { + getTimelineElementIdentity, + getTimelineElementSelector, + getTimelineElementSelectorIndex, + getTimelineElementSourceFile, +} from "../player/lib/timelineElementHelpers"; +import { readTimelineText } from "../player/lib/timelineText"; +import { usePlayerStore } from "../player/store/playerStore"; + +/** A text commit skips the preview reload, so the edited layer's row re-reads its words here. */ +export function refreshTimelineRowText(el: HTMLElement): void { + const sourceFile = getTimelineElementSourceFile(el); + const hfId = el.getAttribute("data-hf-id"); + const selector = getTimelineElementSelector(el); + const selectorIndex = selector + ? (getTimelineElementSelectorIndex(el.ownerDocument, el, selector) ?? 0) + : 0; + const { elements, updateElement } = usePlayerStore.getState(); + const row = elements.find( + (candidate) => + candidate.sourceFile === sourceFile && + (hfId + ? candidate.hfId === hfId + : !!selector && + candidate.selector === selector && + (candidate.selectorIndex ?? 0) === selectorIndex), + ); + if (row) updateElement(getTimelineElementIdentity(row), { text: readTimelineText(el) }); +} diff --git a/packages/studio/src/hooks/timelineEditingHelpers.ts b/packages/studio/src/hooks/timelineEditingHelpers.ts index b563f0f663..f88ff38f0c 100644 --- a/packages/studio/src/hooks/timelineEditingHelpers.ts +++ b/packages/studio/src/hooks/timelineEditingHelpers.ts @@ -238,6 +238,7 @@ export function buildTimelineMoveTimingPatch( start: number, duration: number, track?: number, + audioGroup?: null, ): string { if (!Number.isFinite(start) || !Number.isFinite(duration)) { console.warn( @@ -257,6 +258,12 @@ export function buildTimelineMoveTimingPatch( value: formatTimelineAttributeNumber(track), }); } + if (audioGroup === null) + patched = applyPatchByTarget(patched, target, { + type: "attribute", + property: "data-audio-group", + value: null, + }); // Content-driven duration: sync data-duration to the furthest clip end read // from the PATCHED SOURCE (raw data-duration), so it grows if a clip moved // past the end and shrinks if the furthest clip moved left. Measured from the diff --git a/packages/studio/src/hooks/timelineMoveAdapter.test.ts b/packages/studio/src/hooks/timelineMoveAdapter.test.ts index a64dab810e..74ea16ee94 100644 --- a/packages/studio/src/hooks/timelineMoveAdapter.test.ts +++ b/packages/studio/src/hooks/timelineMoveAdapter.test.ts @@ -68,6 +68,18 @@ describe("persistTimelineMoveEditsAtomically", () => { }); }); + it("carries explicit detachment through the atomic move", async () => { + const edit = { + element: { ...element("voice", 1), audioGroup: "group" }, + updates: { start: 1, track: 0, audioGroup: null }, + }; + const handle = await runMove([edit], "move", "track-insert"); + expect(handle).toHaveBeenCalledWith( + [{ element: edit.element, start: 1, track: 0, audioGroup: null }], + { coalesceKey: "move" }, + ); + }); + it("rejects without retrying individual members when the atomic batch fails", async () => { const failure = new Error("batch failed"); const handleTimelineGroupMove = vi.fn().mockRejectedValue(failure); diff --git a/packages/studio/src/hooks/timelineMoveAdapter.ts b/packages/studio/src/hooks/timelineMoveAdapter.ts index 09665c039e..0738b73322 100644 --- a/packages/studio/src/hooks/timelineMoveAdapter.ts +++ b/packages/studio/src/hooks/timelineMoveAdapter.ts @@ -5,9 +5,13 @@ import type { TimelineGroupMoveChange, } from "./useTimelineGroupEditing"; -export interface TimelineMoveEdit { +export type TimelineAtomicMoveUpdates = Pick & { + audioGroup?: null; +}; + +export interface TimelineAtomicMoveEdit { element: TimelineElement; - updates: Pick; + updates: TimelineAtomicMoveUpdates; } interface AtomicMoveDeps { @@ -20,14 +24,14 @@ interface AtomicMoveDeps { export type TimelineMoveOperation = "timing" | "lane-reorder" | "track-insert"; export type TimelineMoveEditsHandler = ( - edits: TimelineMoveEdit[], + edits: TimelineAtomicMoveEdit[], coalesceKey?: string, operation?: TimelineMoveOperation, coalesceMs?: number, ) => Promise; export function persistTimelineMoveEditsAtomically( - edits: TimelineMoveEdit[], + edits: TimelineAtomicMoveEdit[], coalesceKey: string | undefined, operation: TimelineMoveOperation, deps: AtomicMoveDeps, @@ -37,6 +41,7 @@ export function persistTimelineMoveEditsAtomically( edits.map(({ element, updates }) => ({ element, start: updates.start, + audioGroup: updates.audioGroup, // Stable track lanes: a lane is the authored data-track-index, so every // vertical gesture (lane-reorder AND track-insert) must persist the track; // z is paint order only and is synced separately. Plain horizontal moves diff --git a/packages/studio/src/hooks/useAnimatedPropertyCommit.test.tsx b/packages/studio/src/hooks/useAnimatedPropertyCommit.test.tsx index 74c9217dc0..0c28f3fa47 100644 --- a/packages/studio/src/hooks/useAnimatedPropertyCommit.test.tsx +++ b/packages/studio/src/hooks/useAnimatedPropertyCommit.test.tsx @@ -2,17 +2,22 @@ import React, { act } from "react"; import { afterEach, describe, expect, it, vi } from "vitest"; -import type { GsapAnimation } from "@hyperframes/core/gsap-parser"; +import { parseGsapScript, type GsapAnimation } from "@hyperframes/core/gsap-parser"; import type { DomEditSelection } from "../components/editor/domEditingTypes"; import { usePlayerStore } from "../player/store/playerStore"; import { useAnimatedPropertyCommit } from "./useAnimatedPropertyCommit"; import { mountReactHarness, withInlineLayoutBox } from "./domSelectionTestHarness"; import { writeSizeWithCrop } from "../components/editor/cropResize"; -import type { CommitMutation } from "./gsapScriptCommitTypes"; +import { trackStudioEvent } from "../utils/studioTelemetry"; +import { trackKeyframeCommit } from "../utils/keyframeUsage"; +import type { CommitMutationOptions, CommitMutation } from "./gsapScriptCommitTypes"; + +vi.mock("../utils/studioTelemetry", () => ({ trackStudioEvent: vi.fn() })); (globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; afterEach(() => { + vi.clearAllMocks(); document.body.innerHTML = ""; usePlayerStore.setState({ autoKeyframeEnabled: true, currentTime: 0 }); }); @@ -43,7 +48,11 @@ type Commit = ( /** Renders the hook and hands its commit function to the caller via a ref callback. */ function renderHookWith( animations: GsapAnimation[], - onMutation: (mutation: Record, label: string) => unknown | Promise, + onMutation: ( + mutation: Record, + label: string, + options: CommitMutationOptions, + ) => unknown | Promise, onReady: (commit: Commit) => void, bumpGsapCache = vi.fn(), onBatch?: ( @@ -56,9 +65,9 @@ function renderHookWith( async ( _sel: DomEditSelection, mutation: Record, - options: { label: string }, + options: CommitMutationOptions, ) => { - await onMutation(mutation, options.label); + await onMutation(mutation, options.label, options); }, onBatch ? { @@ -401,3 +410,35 @@ describe("useAnimatedPropertyCommit — a size write and its crop are one undo s act(() => root.unmount()); }); }); + +it("counts one add when an inspector edit first converts a flat animation", async () => { + usePlayerStore.setState({ autoKeyframeEnabled: true, currentTime: 1 }); + const flat = parseGsapScript( + 'const tl = gsap.timeline(); tl.to("#box", { rotationX: 0, duration: 2 }, 0);', + ).animations[0]!; + const mutations: Record[] = []; + let commit!: Commit; + const root = renderHookWith( + [flat, keyframedAnim], + (mutation, _label, options) => { + mutations.push(mutation); + trackKeyframeCommit([mutation], { ok: true, changed: true }, options); + }, + (value) => { + commit = value; + }, + ); + try { + await act(async () => { + await commit(selection, { rotationX: 20 }); + }); + expect(mutations.map((mutation) => mutation.type)).toEqual([ + "convert-to-keyframes", + "add-keyframe", + ]); + expect(trackStudioEvent).toHaveBeenCalledTimes(1); + expect(trackStudioEvent).toHaveBeenCalledWith("keyframe", { action: "add" }); + } finally { + act(() => root.unmount()); + } +}); diff --git a/packages/studio/src/hooks/useAnimatedPropertyCommit.ts b/packages/studio/src/hooks/useAnimatedPropertyCommit.ts index 254474be6f..a415ad46f1 100644 --- a/packages/studio/src/hooks/useAnimatedPropertyCommit.ts +++ b/packages/studio/src/hooks/useAnimatedPropertyCommit.ts @@ -333,7 +333,7 @@ async function commitKeyframeProps( await commit( selection, { type: "convert-to-keyframes", animationId: anim.id }, - { label: "Convert to keyframes", skipReload: true }, + { label: "Convert to keyframes", keyframeTelemetry: false, skipReload: true }, ); } const ct = usePlayerStore.getState().currentTime; @@ -389,7 +389,7 @@ async function commitKeyframeProps( duration: roundTo3(newDuration), keyframes: remapped, }, - { label: `Edit ${primaryProp} (extended keyframe)`, softReload: true }, + { label: `Edit ${primaryProp} (extended keyframe)`, keyframeAction: "add", softReload: true }, ); return; } diff --git a/packages/studio/src/hooks/useAppHotkeys.ts b/packages/studio/src/hooks/useAppHotkeys.ts index 78f455dabb..0c3ca51b6b 100644 --- a/packages/studio/src/hooks/useAppHotkeys.ts +++ b/packages/studio/src/hooks/useAppHotkeys.ts @@ -15,6 +15,7 @@ import { type EditHistoryHandle, type UseEditHistoryActionsOptions, } from "./useEditHistoryActions"; +import { useStableHandlers } from "./useStableHandlers"; function iframeContentWindow(iframe: HTMLIFrameElement | null): Window | null { try { @@ -72,6 +73,7 @@ function tryApplyBeatHistory( // ── Types ── interface UseAppHotkeysParams { + projectId?: string | null; handleTimelineElementsDelete: (elements: TimelineElement[]) => Promise; handleLinkEdit?: LinkShortcutCallbacks["handleLinkEdit"]; handleTimelineElementDeleteOnly?: LinkShortcutCallbacks["handleTimelineElementDeleteOnly"]; @@ -117,6 +119,7 @@ interface UseAppHotkeysParams { // ── Hook ── export function useAppHotkeys({ + projectId, handleTimelineElementsDelete, handleLinkEdit, handleTimelineElementDeleteOnly, @@ -266,9 +269,12 @@ export function useAppHotkeys({ [], ); - return { - handleUndo, - handleRedo, - syncPreviewHotkeys, - }; + return useStableHandlers( + { + handleUndo, + handleRedo, + syncPreviewHotkeys, + }, + projectId, + ); } diff --git a/packages/studio/src/hooks/useDomEditPositionPatchCommit.ts b/packages/studio/src/hooks/useDomEditPositionPatchCommit.ts index 173ba4e2e3..101038cae4 100644 --- a/packages/studio/src/hooks/useDomEditPositionPatchCommit.ts +++ b/packages/studio/src/hooks/useDomEditPositionPatchCommit.ts @@ -33,30 +33,25 @@ export function useDomEditPositionPatchCommit({ coalesceMs: options.coalesceMs, skipRefresh: options.skipRefresh ?? true, deferRender: options.deferRender, - }) - .then(() => undefined) - .catch((error) => { - // A paused save queue is not worth a toast: the paused-save banner is - // already on screen, and one toast per blocked edit is what this branch - // exists to prevent. It still has to REJECT, though. Swallowing it - // resolved the commit, which skipped the caller's revert, so the element - // stayed where the drag put it while nothing reached the file. - if (error instanceof DomEditSaveQueueOpenError) throw error; - if (!wasAlreadyToasted(error)) { - showToast(error instanceof Error ? error.message : "Failed to save position"); - } - trackStudioSaveFailure({ - source: "dom_edit", - error, - filePath: selection.sourceFile ?? activeCompPath ?? "index.html", - mutationType: "position", - label: options.label, - targetId: selection.id, - targetSelector: selection.selector, - targetSourceFile: selection.sourceFile, - }); - throw error; + }).catch((error) => { + // The paused-save banner already explains this refusal. Rethrow so the + // caller reverts the preview instead of treating an unsaved edit as committed. + if (error instanceof DomEditSaveQueueOpenError) throw error; + if (!wasAlreadyToasted(error)) { + showToast(error instanceof Error ? error.message : "Failed to save position"); + } + trackStudioSaveFailure({ + source: "dom_edit", + error, + filePath: selection.sourceFile ?? activeCompPath ?? "index.html", + mutationType: "position", + label: options.label, + targetId: selection.id, + targetSelector: selection.selector, + targetSourceFile: selection.sourceFile, }); + throw error; + }); }, [activeCompPath, persistDomEditOperations, showToast], ); diff --git a/packages/studio/src/hooks/useDomEditTextCommits.test.tsx b/packages/studio/src/hooks/useDomEditTextCommits.test.tsx index c4aeedc7cf..eecac6562c 100644 --- a/packages/studio/src/hooks/useDomEditTextCommits.test.tsx +++ b/packages/studio/src/hooks/useDomEditTextCommits.test.tsx @@ -160,6 +160,21 @@ describe("useDomEditTextCommits", () => { }; } + it.each([true, false])( + "counts in-place text only after a changed write (%s)", + async (changed) => { + vi.mocked(trackStudioEvent).mockClear(); + const { persist, save } = richTextProbe(); + persist.mockResolvedValue({ changed, sourceFile: "private.html", version: "v2" }); + await save(); + expect(vi.mocked(trackStudioEvent).mock.calls).toEqual( + changed + ? [["feature_used", { feature: "text_edit", surface: "preview", method: "field" }]] + : [], + ); + }, + ); + it("saves in-place text while the preview is editable, and refreshes the selection it edited", async () => { const applyDomSelection = vi.fn(); const { persist, element, save } = richTextProbe(undefined, () => ({ applyDomSelection })); @@ -487,3 +502,6 @@ describe("useDomEditTextCommits", () => { expect(agentElement.textContent).toBe("Edited"); }); }); + +vi.mock("../utils/studioTelemetry", () => ({ trackStudioEvent: vi.fn() })); +import { trackStudioEvent } from "../utils/studioTelemetry"; diff --git a/packages/studio/src/hooks/useDomEditTextCommits.ts b/packages/studio/src/hooks/useDomEditTextCommits.ts index 61327214b7..4f93719c66 100644 --- a/packages/studio/src/hooks/useDomEditTextCommits.ts +++ b/packages/studio/src/hooks/useDomEditTextCommits.ts @@ -1,4 +1,6 @@ +import { trackPreviewFeatureUsed } from "../utils/previewFeatureUsage"; import { useCallback, useRef } from "react"; +import { refreshTimelineRowText } from "./refreshTimelineRowText"; import { normalizeDomEditStyleValue } from "../utils/studioHelpers"; import { injectPreviewGoogleFont, injectPreviewImportedFont } from "../utils/studioFontHelpers"; import { @@ -63,6 +65,7 @@ async function resyncDomTextSelectionFromPreview( if (!doc) return; const refreshed = findElementForSelection(doc, selection, activeCompPath); if (!refreshed) return; + refreshTimelineRowText(refreshed); const nextSelection = await buildDomSelectionFromTarget(refreshed); if (!nextSelection) return; applyDomSelection(nextSelection, { revealPanel: false, preserveGroup: true }); @@ -278,11 +281,12 @@ export function useDomEditTextCommits({ appliedHtml = element.innerHTML; }, persist: async () => { - await persistDomEditOperations(selection, operations, { + const result = await persistDomEditOperations(selection, operations, { label: "Edit text", skipRefresh: true, shouldSave: isLatestTextCommit, }); + if (result?.changed) trackPreviewFeatureUsed("text_edit", "field"); }, shouldRevert: () => isLatestTextCommit(), revert: () => { diff --git a/packages/studio/src/hooks/useDomEditWiring.ts b/packages/studio/src/hooks/useDomEditWiring.ts index 19178b24d3..106eef1bce 100644 --- a/packages/studio/src/hooks/useDomEditWiring.ts +++ b/packages/studio/src/hooks/useDomEditWiring.ts @@ -104,8 +104,10 @@ export interface UseDomEditWiringParams { animId: string, resolvedFromValues?: Record, ) => Promise; - removeAllKeyframes: (sel: DomEditSelection, animId: string) => Promise; - handleDomManualEditsReset: (sel: DomEditSelection) => Promise; + removeAllKeyframes: Parameters[0]["removeAllKeyframes"]; + handleDomManualEditsReset: ( + sel: DomEditSelection, + ) => Promise; } // fallow-ignore-next-line complexity diff --git a/packages/studio/src/hooks/useDomGeometryCommit.test.tsx b/packages/studio/src/hooks/useDomGeometryCommit.test.tsx index 1c3006e053..c31af2e0c9 100644 --- a/packages/studio/src/hooks/useDomGeometryCommit.test.tsx +++ b/packages/studio/src/hooks/useDomGeometryCommit.test.tsx @@ -127,7 +127,7 @@ describe("useDomGeometryCommit, from the package entry", () => { y: 20, }); - expect(outcome).toEqual({ ok: true }); + expect(outcome).toEqual({ ok: true, changed: true }); expect(mutations).toEqual([ expect.objectContaining({ type: "add", targetSelector: "#card", method: "set" }), ]); @@ -146,7 +146,14 @@ describe("useDomGeometryCommit, from the package entry", () => { const url = String(input instanceof Request ? input.url : input); calls.urls.push(url); if (url.includes("/patch-element/")) calls.patches.push(JSON.parse(String(init?.body))); - const saved = { ok: true, changed: true, matched: true, content: "AFTER", version: "v2" }; + const saved = { + ok: true, + changed: true, + matched: true, + path: "index.html", + content: "AFTER", + version: "v2", + }; const body = url.includes("/files/") ? { content: SOURCE } : saved; const status = url.includes("/patch-element/") ? patchStatus : 200; return new Response(JSON.stringify(body), { @@ -163,7 +170,10 @@ describe("useDomGeometryCommit, from the package entry", () => { const { element, recordEdit, hook, unmount } = renderHost(); const card = makeSelection("card", element); - await expect(hook().commitPathOffset(card, { x: 130.5, y: 90 })).resolves.toEqual({ ok: true }); + await expect(hook().commitPathOffset(card, { x: 130.5, y: 90 })).resolves.toEqual({ + ok: true, + changed: true, + }); expect(element.style.getPropertyValue("translate")).toBe("130.5px 90px"); expect(calls.patches).toEqual([ @@ -185,7 +195,7 @@ describe("useDomGeometryCommit, from the package entry", () => { await expect( hook().commitBoxSize(makeSelection("card", element), { width: 300, height: 90 }), - ).resolves.toEqual({ ok: true }); + ).resolves.toEqual({ ok: true, changed: true }); expect(element.style.getPropertyValue("width")).toBe("300px"); expect(calls.patches).toEqual([ @@ -247,7 +257,7 @@ describe("useDomGeometryCommit, from the package entry", () => { { x: 1, y: 2 }, { plainTranslate: true }, ), - ).resolves.toEqual({ ok: true }); + ).resolves.toEqual({ ok: true, changed: true }); expect(calls.patches).toHaveLength(1); unmount(); }); @@ -396,7 +406,14 @@ describe("useDomGeometryCommit, one word of a staggered phrase", () => { headers: { "content-type": "application/json" }, }); } - return json({ ok: true, changed: true, matched: true, content: "AFTER", version: "v2" }); + return json({ + ok: true, + changed: true, + matched: true, + path: "index.html", + content: "AFTER", + version: "v2", + }); } if (url.includes("/api/projects/p1/gsap-mutations/")) { calls.gsapMutations.push(JSON.parse(String(init?.body))); @@ -426,6 +443,7 @@ describe("useDomGeometryCommit, one word of a staggered phrase", () => { await expect(hook().commitPathOffset(selection, { x: 40, y: 20 })).resolves.toEqual({ ok: true, + changed: true, }); expect(calls.gsapMutations).toHaveLength(0); @@ -455,6 +473,7 @@ describe("useDomGeometryCommit, one word of a staggered phrase", () => { ]); await expect(hook().commitPathOffset(selection, { x: 40, y: 20 })).resolves.toEqual({ ok: true, + changed: true, }); expect(calls.patches).toHaveLength(2); diff --git a/packages/studio/src/hooks/useDomGeometryCommit.ts b/packages/studio/src/hooks/useDomGeometryCommit.ts index c730430e7e..234736ae20 100644 --- a/packages/studio/src/hooks/useDomGeometryCommit.ts +++ b/packages/studio/src/hooks/useDomGeometryCommit.ts @@ -1,3 +1,4 @@ +import type { GeometryCommitResult } from "../utils/previewFeatureUsage"; import type { RotationCommit } from "../components/editor/rotationDraft"; import { useCallback, useMemo, useRef, useState } from "react"; import type { GsapAnimation } from "@hyperframes/core/gsap-parser"; @@ -67,7 +68,7 @@ export function useDomGeometryCommit({ }: UseDomGeometryCommitOptions): DomGeometryCommits { const projectIdRef = useRef(projectId); projectIdRef.current = projectId; - const pending = useRef(new Set>()).current; + const pending = useRef(new Set>()).current; const editHistory = useMemo(() => ({ recordEdit }), [recordEdit]); const reload = useCallback( () => (reloadPreview ? reloadPreview() : iframeRef.current?.contentWindow?.location.reload()), @@ -142,7 +143,10 @@ export function useDomGeometryCommit({ updateArcSegment: gsap.updateArcSegment, }); const saved = useCallback( - async (commit: () => Promise, restore = noop): Promise => { + async ( + commit: () => Promise, + restore = noop, + ): Promise => { const refusal = !projectIdRef.current ? "No project is open" : !isPreviewBooted(projectIdRef.current) @@ -156,11 +160,10 @@ export function useDomGeometryCommit({ const run = commit(); pending.add(run); try { - await run; + return { ok: true, changed: (await run)?.changed === true }; } finally { pending.delete(run); } - return { ok: true }; }, [pending, showToast], ); diff --git a/packages/studio/src/hooks/useDomGeometryCommits.test.tsx b/packages/studio/src/hooks/useDomGeometryCommits.test.tsx index e6d81df47f..4e0af6d849 100644 --- a/packages/studio/src/hooks/useDomGeometryCommits.test.tsx +++ b/packages/studio/src/hooks/useDomGeometryCommits.test.tsx @@ -305,6 +305,7 @@ describe("Reset after a plain move puts the author's translate back", () => { async (_selection, patches) => { project.history.push(project.file); project.file = patches.reduce((html, op) => applyPatch(html, "layer", op), project.file); + return undefined; }, ); const selection = { id: "layer", selector: "#layer", element } as unknown as DomEditSelection; diff --git a/packages/studio/src/hooks/useDomGeometryCommits.ts b/packages/studio/src/hooks/useDomGeometryCommits.ts index 25b4ce8a19..8c133fb3f0 100644 --- a/packages/studio/src/hooks/useDomGeometryCommits.ts +++ b/packages/studio/src/hooks/useDomGeometryCommits.ts @@ -1,3 +1,4 @@ +import type { DomEditPersistOutcome } from "./domEditCommitTypes"; import type { RotationCommit } from "../components/editor/rotationDraft"; import { useCallback } from "react"; import { getDomEditTargetKey, type DomEditSelection } from "../components/editor/domEditing"; @@ -39,7 +40,7 @@ export interface UseDomGeometryCommitsParams { skipRefresh?: boolean; deferRender?: boolean; }, - ) => Promise; + ) => Promise; readOnlyPreview: boolean; } @@ -73,7 +74,7 @@ export function useDomGeometryCommits({ restore?: () => void, undoKey?: string, ) => { - if (readOnlyPreview) return Promise.resolve(); + if (readOnlyPreview) return Promise.resolve(undefined); const element = selection.element; const beforeSize = captureStudioBoxSize(element); const beforeOffset = captureStudioPathOffset(element); diff --git a/packages/studio/src/hooks/useDomSelection.test.ts b/packages/studio/src/hooks/useDomSelection.test.ts index 43047c25f6..fe24abb79e 100644 --- a/packages/studio/src/hooks/useDomSelection.test.ts +++ b/packages/studio/src/hooks/useDomSelection.test.ts @@ -334,3 +334,29 @@ describe("useDomSelection", () => { harness.cleanup(); }); }); + +it("reports unchanged marquee membership and one new additive member", () => { + const { harness, card, chip } = renderCardAndChip(); + try { + act(() => harness.current().applyDomSelection(card)); + let receipt!: ReturnType["applyMarqueeSelection"]>; + act(() => { + receipt = harness.current().applyMarqueeSelection([chip], true); + }); + expect(receipt).toEqual({ changed: true, count: 2 }); + act(() => { + receipt = harness.current().applyMarqueeSelection([card, chip], true); + }); + expect(receipt).toEqual({ changed: false, count: 2 }); + act(() => { + receipt = harness.current().applyMarqueeSelection([], true); + }); + expect(receipt).toEqual({ changed: false, count: 2 }); + act(() => { + receipt = harness.current().applyMarqueeSelection([], false); + }); + expect(receipt).toEqual({ changed: true, count: 0 }); + } finally { + harness.cleanup(); + } +}); diff --git a/packages/studio/src/hooks/useDomSelection.ts b/packages/studio/src/hooks/useDomSelection.ts index 4802a6937e..f64c04e044 100644 --- a/packages/studio/src/hooks/useDomSelection.ts +++ b/packages/studio/src/hooks/useDomSelection.ts @@ -487,12 +487,13 @@ export function useDomSelection({ // fallow-ignore-next-line complexity (selections: DomEditSelection[], additive: boolean) => { logSelect("marquee", { hits: selections.length, additive }); - if (selections.length === 0) { - if (!additive) applyDomSelection(null, { revealPanel: false }); - return; - } const current = domEditSelectionRef.current; const currentGroup = domEditGroupSelectionsRef.current; + if (selections.length === 0) { + const count = seedDomEditGroupWithSelection(currentGroup, current).length; + if (!additive) applyDomSelection(null, { revealPanel: false }); + return { changed: !additive && count > 0, count: additive ? count : 0 }; + } let nextGroup: DomEditSelection[]; if (additive) { nextGroup = seedDomEditGroupWithSelection(currentGroup, current); @@ -507,11 +508,17 @@ export function useDomSelection({ } } const nextSelection = additive && current ? current : selections[0]; + const previous = seedDomEditGroupWithSelection(currentGroup, current); + const changed = + previous.length !== nextGroup.length || + nextGroup.some((selection) => !domEditSelectionInGroup(previous, selection)) || + !domEditSelectionsTargetSame(current, nextSelection); domEditSelectionRef.current = nextSelection; domEditGroupSelectionsRef.current = nextGroup; setDomEditSelection(nextSelection); setDomEditGroupSelections(nextGroup); announceTimelineSelection(nextGroup, nextSelection, true); + return { changed, count: nextGroup.length }; }, [applyDomSelection, announceTimelineSelection], ); diff --git a/packages/studio/src/hooks/useDomSelectionTypes.ts b/packages/studio/src/hooks/useDomSelectionTypes.ts index 85f21f8d86..b118cd4ae1 100644 --- a/packages/studio/src/hooks/useDomSelectionTypes.ts +++ b/packages/studio/src/hooks/useDomSelectionTypes.ts @@ -3,6 +3,11 @@ import type { DomEditSelection } from "../components/editor/domEditing"; import type { SelectElementOptions, TimelineElement } from "../player"; import type { RightPanelTab } from "../utils/studioHelpers"; +export interface DomSelectionResult { + changed: boolean; + count: number; +} + export interface ApplyDomSelectionOptions { revealPanel?: boolean; additive?: boolean; @@ -85,5 +90,5 @@ export interface UseDomSelectionReturn { handleTimelineElementSelect: (element: TimelineElement | null) => Promise; refreshDomEditSelectionFromPreview: (selection: DomEditSelection) => Promise; refreshDomEditGroupSelectionsFromPreview: (selections: DomEditSelection[]) => Promise; - applyMarqueeSelection: (selections: DomEditSelection[], additive: boolean) => void; + applyMarqueeSelection: (selections: DomEditSelection[], additive: boolean) => DomSelectionResult; } diff --git a/packages/studio/src/hooks/useEnableKeyframes.test.ts b/packages/studio/src/hooks/useEnableKeyframes.test.ts index 2d442ac78c..d1405c0eea 100644 --- a/packages/studio/src/hooks/useEnableKeyframes.test.ts +++ b/packages/studio/src/hooks/useEnableKeyframes.test.ts @@ -314,7 +314,7 @@ describe("applyArcKeyframeAtPlayhead", () => { ], ease: "none", }, - { label: "Add keyframe", softReload: true }, + { label: "Add keyframe", softReload: true, keyframeAction: "add" }, ); }); @@ -336,7 +336,7 @@ describe("applyArcKeyframeAtPlayhead", () => { duration: 10, keyframes: expect.arrayContaining([{ percentage: 25, properties: { x: 25, y: 25 } }]), }), - { label: "Add keyframe", softReload: true }, + { label: "Add keyframe", softReload: true, keyframeAction: "add" }, ); }); }); diff --git a/packages/studio/src/hooks/useEnableKeyframes.ts b/packages/studio/src/hooks/useEnableKeyframes.ts index f21527b213..7ccf8ddfed 100644 --- a/packages/studio/src/hooks/useEnableKeyframes.ts +++ b/packages/studio/src/hooks/useEnableKeyframes.ts @@ -160,7 +160,7 @@ async function replaceSetWithSingleKeyframe( keyframes: [{ percentage: 0, properties: position }], ease: setAnim.ease, }, - { label: "Enable keyframes", softReload: true }, + { label: "Enable keyframes", keyframeAction: "add", softReload: true }, ); } @@ -271,6 +271,7 @@ async function extendKeyframedTweenToPlayhead( }, { label: "Add keyframe", + keyframeAction: "add", softReload: true, ...commitOverrides, }, @@ -378,7 +379,7 @@ export async function promoteSetToKeyframes( ], ease: setAnim.ease, }, - { label: "Add keyframe", softReload: true }, + { label: "Add keyframe", keyframeAction: "add", softReload: true }, ); } @@ -455,7 +456,7 @@ export async function applyArcKeyframeAtPlayhead( }), ease: "none", }, - { label: "Add keyframe", softReload: true }, + { label: "Add keyframe", keyframeAction: "add", softReload: true }, ); } @@ -504,6 +505,7 @@ export function useEnableKeyframes( enableKeyframesTransactionCounter += 1; const coalesceKey = `enable-keyframes:${flatAnim.id}:${enableKeyframesTransactionCounter}`; const convertCommitOverrides: Partial = { + keyframeTelemetry: false, skipReload: true, coalesceKey, coalesceMs: Number.POSITIVE_INFINITY, diff --git a/packages/studio/src/hooks/useFrameCapture.ts b/packages/studio/src/hooks/useFrameCapture.ts index e2d62e0202..5280211cdb 100644 --- a/packages/studio/src/hooks/useFrameCapture.ts +++ b/packages/studio/src/hooks/useFrameCapture.ts @@ -1,4 +1,4 @@ -import { useState, useCallback, useRef, type MouseEvent } from "react"; +import { useMemo, useState, useCallback, useRef, type MouseEvent } from "react"; import { useMountEffect } from "./useMountEffect"; import { liveTime, usePlayerStore } from "../player"; import { buildFrameCaptureFilename, buildFrameCaptureUrl } from "../utils/frameCapture"; @@ -35,8 +35,10 @@ export function useFrameCapture({ return isPlaying ? livePlayheadRef.current : currentTime; }, []); + const [captureStamp, setCaptureStamp] = useState(Date.now); const refreshCaptureFrameTime = useCallback(() => { setCaptureFrameTime(playheadTime()); + setCaptureStamp(Date.now()); }, [playheadTime]); const handleCaptureFrameClick = useCallback( @@ -107,13 +109,18 @@ export function useFrameCapture({ [activeCompPath, playheadTime, projectId, showToast, waitForPendingDomEditSaves], ); - const captureFrameHref = projectId - ? buildFrameCaptureUrl({ - projectId, - compositionPath: activeCompPath, - currentTime: captureFrameTime, - }) - : "#"; + const captureFrameHref = useMemo( + () => + projectId + ? buildFrameCaptureUrl({ + projectId, + compositionPath: activeCompPath, + currentTime: captureFrameTime, + version: captureStamp, + }) + : "#", + [projectId, activeCompPath, captureFrameTime, captureStamp], + ); const captureFrameFilename = buildFrameCaptureFilename(activeCompPath, captureFrameTime); return { diff --git a/packages/studio/src/hooks/useGestureCommit.test.tsx b/packages/studio/src/hooks/useGestureCommit.test.tsx index a2077c5e87..5166e049e4 100644 --- a/packages/studio/src/hooks/useGestureCommit.test.tsx +++ b/packages/studio/src/hooks/useGestureCommit.test.tsx @@ -1,12 +1,18 @@ // @vitest-environment jsdom -import { act } from "react"; +import { act, useLayoutEffect } from "react"; import { afterEach, describe, expect, it, vi } from "vitest"; +import type { GsapAnimation } from "@hyperframes/core/gsap-parser"; +import { trackStudioEvent } from "../utils/studioTelemetry"; +import { trackKeyframeCommit } from "../utils/keyframeUsage"; import type { DomEditSelection } from "../components/editor/domEditing"; import { usePlayerStore } from "../player"; import { mountReactHarness } from "./domSelectionTestHarness"; import type { CommitMutationOptions } from "./gsapScriptCommitTypes"; +import { useGsapAwareEditing } from "./useGsapAwareEditing"; import { useGestureCommit } from "./useGestureCommit"; +vi.mock("../utils/studioTelemetry", () => ({ trackStudioEvent: vi.fn() })); + const gestureRecording = vi.hoisted(() => ({ startRecording: vi.fn(), stopRecording: vi.fn(() => [ @@ -84,44 +90,88 @@ function makeSelection(element: HTMLElement): DomEditSelection { }; } +function mountRecording( + writer: ( + mutation: Record, + options: CommitMutationOptions, + selection?: DomEditSelection, + ) => Promise, + animations: GsapAnimation[] = [], + readOnlyPreview = false, +) { + const iframe = document.createElement("iframe"); + document.body.append(iframe); + const element = document.createElement("div"); + element.id = "card"; + const session = { + current: { + domEditSelection: makeSelection(element), + selectedGsapAnimations: animations, + commitMutation: writer, + }, + }; + let hook: ReturnType | null = null; + function Probe() { + const editing = useGsapAwareEditing({ + domEditSelection: session.current.domEditSelection, + selectedGsapAnimations: session.current.selectedGsapAnimations, + gsapCommitMutation: (selection, mutation, options) => writer(mutation, options, selection), + previewIframeRef: { current: iframe }, + showToast: vi.fn(), + bumpGsapCache: vi.fn(), + makeFetchFallback: () => vi.fn(), + trackGsapInteractionFailure: vi.fn(), + stageElementPositionOffset: vi.fn(), + handleDomBoxSizeCommit: vi.fn(), + handleDomRotationCommit: vi.fn(), + commitPositionPatchToHtml: vi.fn(), + addGsapAnimation: vi.fn(), + convertToKeyframes: vi.fn(), + setArcPath: vi.fn(), + updateArcSegment: vi.fn(), + }); + const currentHook = useGestureCommit({ + domEditSessionRef: session, + previewIframeRef: { current: iframe }, + showToast: vi.fn(), + isGestureRecordingRef: { current: false }, + readOnlyPreview, + }); + useLayoutEffect(() => { + session.current.commitMutation = editing.commitMutation; + hook = currentHook; + }); + return null; + } + const root = mountReactHarness(); + cleanup = () => act(() => root.unmount()); + return Object.assign( + () => { + if (!hook) throw new Error("hook did not initialize"); + return hook; + }, + { + select: (selection: DomEditSelection, nextAnimations: GsapAnimation[]) => { + session.current.domEditSelection = selection; + session.current.selectedGsapAnimations = nextAnimations; + act(() => root.render()); + }, + }, + ); +} + describe("useGestureCommit", () => { it("coalesces property-group commits and reloads only the terminal group", async () => { - const iframe = document.createElement("iframe"); - document.body.append(iframe); - const element = document.createElement("div"); - element.id = "card"; - const commitMutation = vi.fn< + const writer = vi.fn< (mutation: Record, options: CommitMutationOptions) => Promise >(async () => {}); - const sessionRef = { - current: { - domEditSelection: makeSelection(element), - selectedGsapAnimations: [], - commitMutation, - }, - }; - const captured: { hook: ReturnType | null } = { hook: null }; - function Probe() { - captured.hook = useGestureCommit({ - domEditSessionRef: sessionRef, - previewIframeRef: { current: iframe }, - showToast: vi.fn(), - isGestureRecordingRef: { current: false }, - readOnlyPreview: false, - }); - return null; - } - const root = mountReactHarness(); - cleanup = () => act(() => root.unmount()); - if (!captured.hook) throw new Error("hook did not initialize"); - - act(() => captured.hook?.handleToggleRecording()); - act(() => captured.hook?.handleToggleRecording()); + const hook = mountRecording(writer); + act(() => hook().handleToggleRecording()); + act(() => hook().handleToggleRecording()); await act(async () => { - await vi.waitFor(() => expect(commitMutation).toHaveBeenCalledTimes(2)); + await vi.waitFor(() => expect(writer).toHaveBeenCalledTimes(2)); }); - - const options = commitMutation.mock.calls.map((call) => call[1]); + const options = writer.mock.calls.map((call) => call[1]); expect(new Set(options.map((entry) => entry.coalesceKey)).size).toBe(1); expect(options[0]).toEqual(expect.objectContaining({ coalesceMs: Infinity, skipReload: true })); expect(options[0]).not.toHaveProperty("softReload"); @@ -130,30 +180,150 @@ describe("useGestureCommit", () => { }); it("does not start a recording while the preview is read-only", () => { - const element = document.createElement("div"); - const commitMutation = vi.fn(async () => {}); - const captured: { hook: ReturnType | null } = { hook: null }; - function Probe() { - captured.hook = useGestureCommit({ - domEditSessionRef: { - current: { - domEditSelection: makeSelection(element), - selectedGsapAnimations: [], - commitMutation, - }, - }, - previewIframeRef: { current: document.createElement("iframe") }, - showToast: vi.fn(), - isGestureRecordingRef: { current: false }, - readOnlyPreview: true, - }); - return null; - } - const root = mountReactHarness(); - cleanup = () => act(() => root.unmount()); - - act(() => captured.hook?.handleToggleRecording()); + const writer = vi.fn(async () => {}); + const hook = mountRecording(writer, [], true); + act(() => hook().handleToggleRecording()); expect(gestureRecording.startRecording).not.toHaveBeenCalled(); - expect(commitMutation).not.toHaveBeenCalled(); + expect(writer).not.toHaveBeenCalled(); + }); +}); + +it.each([ + ["new mixed-property recording", undefined, true, true, 1, "button"], + ["keyboard recording", undefined, true, true, 1, "keyboard"], + ["static hold replacement", "set", true, true, 1, "button"], + ["overlapping tween replacement", "to", true, true, 1, "button"], + ["unchanged recording", undefined, true, false, 0, "button"], + ["refused recording", undefined, false, true, 0, "button"], +] as const)( + "counts writer receipts once for %s", + async (_name, method, ok, changed, count, inputMethod) => { + const animations = method + ? [ + { + id: "card-position", + targetSelector: "#card", + propertyGroup: "position", + method, + properties: { x: 0, y: 0 }, + resolvedStart: 0, + position: 0, + duration: method === "set" ? 0 : 2, + keyframes: { + keyframes: [ + { percentage: 0, properties: { x: 0 } }, + { percentage: 100, properties: { x: 100 } }, + ], + }, + } as unknown as GsapAnimation, + ] + : []; + const writer = vi.fn( + async (mutation: Record, options: CommitMutationOptions) => { + const result = { ok, changed }; + trackKeyframeCommit([mutation], result, options); + options.onResult?.(result); + }, + ); + const hook = mountRecording(writer, animations); + act(() => hook().handleToggleRecording(inputMethod)); + await act(async () => { + hook().handleToggleRecording(); + await vi.waitFor(() => expect(writer).toHaveBeenCalled()); + }); + expect(trackStudioEvent).toHaveBeenCalledTimes(count * 2); + if (count) { + expect(trackStudioEvent).toHaveBeenCalledWith("keyframe", { action: "add" }); + expect(trackStudioEvent).toHaveBeenCalledWith("feature_used", { + feature: "gesture_recording", + surface: "preview", + method: inputMethod, + }); + } + }, +); + +it("keeps a pending recording isolated until its writer settles", async () => { + let release!: () => void; + const pending = new Promise((resolve) => { + release = resolve; + }); + const writer = vi.fn( + async (_mutation: Record, options: CommitMutationOptions) => { + await pending; + options.onResult?.({ ok: true, changed: true }); + }, + ); + const hook = mountRecording(writer); + act(() => hook().handleToggleRecording("keyboard")); + act(() => hook().handleToggleRecording()); + await vi.waitFor(() => expect(writer).toHaveBeenCalledTimes(1)); + act(() => hook().handleToggleRecording("button")); + expect(gestureRecording.startRecording).toHaveBeenCalledTimes(1); + await act(async () => { + release(); + await vi.waitFor(() => + expect(trackStudioEvent).toHaveBeenCalledWith("feature_used", { + feature: "gesture_recording", + surface: "preview", + method: "keyboard", + }), + ); + }); + expect(gestureRecording.clearSamples).toHaveBeenCalledTimes(1); + act(() => hook().handleToggleRecording("button")); + expect(gestureRecording.startRecording).toHaveBeenCalledTimes(2); +}); + +it("writes one recording to its original selection after selecting another source", async () => { + const original = { + id: "original-position", + targetSelector: "#card", + propertyGroup: "position", + method: "set", + properties: { x: 0, y: 0 }, + resolvedStart: 0, + position: 0, + duration: 0, + } as GsapAnimation; + const writer = vi.fn( + async ( + _mutation: Record, + options: CommitMutationOptions, + _selection?: DomEditSelection, + ) => { + options.onResult?.({ ok: true, changed: true }); + }, + ); + const hook = mountRecording(writer, [original]); + act(() => hook().handleToggleRecording("keyboard")); + const other = document.createElement("div"); + other.id = "other"; + hook.select( + { ...makeSelection(other), sourceFile: "other.html", compositionPath: "other.html" }, + [], + ); + await act(async () => { + hook().handleToggleRecording(); + await vi.waitFor(() => expect(trackStudioEvent).toHaveBeenCalledTimes(2)); + }); + expect(writer).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + type: "replace-with-keyframes", + animationId: "original-position", + targetSelector: "#card", + }), + expect.objectContaining({ keyframeAction: "add" }), + expect.objectContaining({ + id: "card", + sourceFile: "index.html", + compositionPath: "index.html", + }), + ); + expect(trackStudioEvent).toHaveBeenCalledWith("keyframe", { action: "add" }); + expect(trackStudioEvent).toHaveBeenCalledWith("feature_used", { + feature: "gesture_recording", + surface: "preview", + method: "keyboard", }); }); diff --git a/packages/studio/src/hooks/useGestureCommit.ts b/packages/studio/src/hooks/useGestureCommit.ts index 0714f0caad..86de46e75a 100644 --- a/packages/studio/src/hooks/useGestureCommit.ts +++ b/packages/studio/src/hooks/useGestureCommit.ts @@ -11,9 +11,12 @@ import { usePlayerStore } from "../player"; import type { DomEditSelection } from "../components/editor/domEditing"; import type { GsapAnimation } from "@hyperframes/core/gsap-parser"; import type { CommitMutationOptions } from "./gsapScriptCommitTypes"; +import { trackPreviewEditResult } from "../utils/previewFeatureUsage"; +import { observeGsapGesture } from "./gsapGestureOutcome"; import { roundTo3 } from "../utils/rounding"; import { classifyPropertyGroup } from "@hyperframes/core/gsap-parser"; import { isInstantHold, idSelector, writeTargetSelector, tweenTargetsElement } from "./gsapShared"; +import { useStableHandlers } from "./useStableHandlers"; type RecordedKeyframe = { percentage: number; @@ -71,6 +74,7 @@ interface GestureSessionRef { commitMutation?: ( mutation: Record, options: CommitMutationOptions, + selection?: DomEditSelection, ) => Promise; } @@ -80,9 +84,16 @@ function reloadOnlyLast(index: number, count: number): Partial 0 ? start + duration : undefined; +} + let gestureRecordingCommitCounter = 0; interface UseGestureCommitParams { + projectId?: string | null; domEditSessionRef: React.MutableRefObject; previewIframeRef: React.RefObject; showToast: (message: string, tone?: "error" | "info") => void; @@ -93,11 +104,12 @@ interface UseGestureCommitParams { export interface UseGestureCommitResult { gestureState: "idle" | "recording"; gestureRecording: ReturnType; - handleToggleRecording: () => void; + handleToggleRecording: (method?: "button" | "keyboard") => void; } // fallow-ignore-next-line complexity export function useGestureCommit({ + projectId, domEditSessionRef, previewIframeRef, showToast, @@ -108,11 +120,13 @@ export function useGestureCommit({ const [gestureState, setGestureState] = useState<"idle" | "recording">("idle"); const gestureStateRef = useRef<"idle" | "recording">("idle"); const recordingAutoStopRef = useRef>(undefined); + const recordingMethodRef = useRef<"button" | "keyboard">("button"); const recordingStartTimeRef = useRef(0); const commitInFlightRef = useRef(false); // Capture selection at recording start so commit always targets the recorded element, // even if the user's selection changes mid-recording. const capturedSelectionRef = useRef(null); + const capturedAnimationsRef = useRef([]); // Unmount: clear auto-stop interval useEffect(() => () => clearInterval(recordingAutoStopRef.current), []); @@ -203,6 +217,12 @@ export function useGestureCommit({ return; } if (liveSession.commitMutation) { + const writer = liveSession.commitMutation; + const outcome = observeGsapGesture((_selection, mutation, options) => + writer(mutation, options, sel), + ); + const commit = (mutation: Record, options: CommitMutationOptions) => + outcome.commit!(sel, mutation, options); const recStart = recordingStartTimeRef.current; const rawKeyframes = sortedPcts.map((pct) => ({ percentage: pct, @@ -213,7 +233,7 @@ export function useGestureCommit({ const hasPositionProps = keyframes.some((kf) => Object.keys(kf.properties).some((k) => classifyPropertyGroup(k) === "position"), ); - const allAnims = liveSession.selectedGsapAnimations ?? []; + const allAnims = capturedAnimationsRef.current; const existingPositionTween = hasPositionProps ? allAnims.find( (a) => @@ -225,7 +245,7 @@ export function useGestureCommit({ if (isInstantHold(existingPositionTween)) { // An instant hold is not a tween to merge into — replace it with the // recorded motion (which already starts from the held position). - await liveSession.commitMutation( + await commit( { type: "replace-with-keyframes", animationId: existingPositionTween.id, @@ -234,7 +254,7 @@ export function useGestureCommit({ duration: roundTo3(duration), keyframes, }, - { label: "Gesture recording (replace set)", softReload: true }, + { label: "Gesture recording (replace set)", softReload: true, keyframeAction: "add" }, ); } else { const tweenStart = existingPositionTween.resolvedStart ?? 0; @@ -271,7 +291,7 @@ export function useGestureCommit({ const merged = [...preserved, ...mapped].sort((a, b) => a.percentage - b.percentage); - await liveSession.commitMutation( + await commit( { type: "replace-with-keyframes", animationId: existingPositionTween.id, @@ -283,7 +303,7 @@ export function useGestureCommit({ duration: tweenDur, keyframes: merged, }, - { label: "Gesture recording (merge)", softReload: true }, + { label: "Gesture recording (merge)", softReload: true, keyframeAction: "add" }, ); } else { // Emit one tween per property group so a mixed-prop gesture (e.g. @@ -291,7 +311,7 @@ export function useGestureCommit({ // tween that the position-only drag intercept can't edit. const keyframeGroups = partitionKeyframesByGroup(keyframes); for (const [index, groupKfs] of keyframeGroups.entries()) { - await liveSession.commitMutation( + await commit( { type: "add-with-keyframes", targetSelector: writeSelector, @@ -317,7 +337,7 @@ export function useGestureCommit({ // No existing tween — same per-group split as the new-range branch above. const keyframeGroups = partitionKeyframesByGroup(keyframes); for (const [index, groupKfs] of keyframeGroups.entries()) { - await liveSession.commitMutation( + await commit( { type: "add-with-keyframes", targetSelector: writeSelector, @@ -335,6 +355,7 @@ export function useGestureCommit({ ); } } + trackPreviewEditResult("gesture_recording", recordingMethodRef.current, outcome.finish()); } showToast(`Recorded ${sortedPcts.length} keyframes`, "info"); } catch (err) { @@ -348,58 +369,71 @@ export function useGestureCommit({ } }, [gestureRecording, showToast, isGestureRecordingRef, domEditSessionRef]); - // fallow-ignore-next-line complexity - const handleToggleRecording = useCallback(() => { - if (gestureStateRef.current === "recording") { - if (readOnlyPreview) { - cancelRecording(); + const armAutoStop = useCallback( + (elementEnd: number | undefined) => { + clearInterval(recordingAutoStopRef.current); + const autoStopAt = elementEnd ?? Infinity; + recordingAutoStopRef.current = setInterval(() => { + const { currentTime: t, duration: d } = usePlayerStore.getState(); + const limit = Math.min(autoStopAt, d); + if (limit > 0 && t >= limit - 0.05) { + void stopAndCommitRecording(); + } + }, 100); + }, + [stopAndCommitRecording], + ); + + const startRecording = useCallback( + (method: "button" | "keyboard") => { + if (readOnlyPreview) return; + const sel = domEditSessionRef.current.domEditSelection; + if (!sel) { + showToast("Select an element first", "error"); return; } - void stopAndCommitRecording(); - return; - } - if (readOnlyPreview) return; - const sel = domEditSessionRef.current.domEditSelection; - if (!sel) { - showToast("Select an element first", "error"); - return; - } - const iframe = previewIframeRef.current; - if (!iframe) { - showToast("Preview not ready — try again", "error"); - return; - } - - const store = usePlayerStore.getState(); - recordingStartTimeRef.current = store.currentTime; - const elStart = Number.parseFloat(sel.dataAttributes?.start ?? "0") || 0; - const elDur = Number.parseFloat(sel.dataAttributes?.duration ?? "0") || 0; - const elementEnd = elDur > 0 ? elStart + elDur : undefined; - capturedSelectionRef.current = sel; - gestureRecording.startRecording(sel.element, iframe, elementEnd); - gestureStateRef.current = "recording"; - isGestureRecordingRef.current = true; - setGestureState("recording"); - - clearInterval(recordingAutoStopRef.current); - const autoStopAt = elementEnd ?? Infinity; - recordingAutoStopRef.current = setInterval(() => { - const { currentTime: t, duration: d } = usePlayerStore.getState(); - const limit = Math.min(autoStopAt, d); - if (limit > 0 && t >= limit - 0.05) { - void stopAndCommitRecording(); + const iframe = previewIframeRef.current; + if (!iframe) { + showToast("Preview not ready — try again", "error"); + return; } - }, 100); - }, [ - gestureRecording, - showToast, - stopAndCommitRecording, - cancelRecording, - previewIframeRef, - domEditSessionRef, - isGestureRecordingRef, - readOnlyPreview, - ]); - return { gestureState, gestureRecording, handleToggleRecording }; + const store = usePlayerStore.getState(); + recordingMethodRef.current = method; + recordingStartTimeRef.current = store.currentTime; + const elementEnd = recordingEnd(sel); + capturedSelectionRef.current = sel; + capturedAnimationsRef.current = domEditSessionRef.current.selectedGsapAnimations ?? []; + gestureRecording.startRecording(sel.element, iframe, elementEnd); + gestureStateRef.current = "recording"; + isGestureRecordingRef.current = true; + setGestureState("recording"); + + armAutoStop(elementEnd); + }, + [ + gestureRecording, + showToast, + previewIframeRef, + domEditSessionRef, + isGestureRecordingRef, + readOnlyPreview, + armAutoStop, + ], + ); + + const handleToggleRecording = useCallback( + (method: "button" | "keyboard" = "button") => { + if (commitInFlightRef.current) return; + if (gestureStateRef.current === "recording") { + if (readOnlyPreview) cancelRecording(); + else void stopAndCommitRecording(); + return; + } + startRecording(method); + }, + [cancelRecording, readOnlyPreview, startRecording, stopAndCommitRecording], + ); + + return useStableHandlers({ gestureState, gestureRecording, handleToggleRecording }, projectId); } diff --git a/packages/studio/src/hooks/useGestureTrailOverlay.tsx b/packages/studio/src/hooks/useGestureTrailOverlay.tsx new file mode 100644 index 0000000000..485b8e3eca --- /dev/null +++ b/packages/studio/src/hooks/useGestureTrailOverlay.tsx @@ -0,0 +1,33 @@ +import { useLayoutEffect, useRef } from "react"; +import { GestureTrailOverlay } from "../components/editor/GestureTrailOverlay"; +import type { UseGestureCommitResult } from "./useGestureCommit"; + +/** The live gesture trail drawn over the preview while a gesture is recording, or nothing. */ +export function useGestureTrailOverlay( + { + gestureState, + gestureRecording, + }: Pick, + previewIframe: HTMLIFrameElement | null, + compositionSize: { width: number; height: number } | null, +) { + const canvasRectRef = useRef(null); + useLayoutEffect(() => { + if (gestureState !== "recording" || !previewIframe) { + canvasRectRef.current = null; + return; + } + canvasRectRef.current = previewIframe.getBoundingClientRect(); + }, [gestureState, previewIframe]); + if (gestureState !== "recording" || !previewIframe) return undefined; + return ( + + ); +} diff --git a/packages/studio/src/hooks/useGsapAwareEditing.test.tsx b/packages/studio/src/hooks/useGsapAwareEditing.test.tsx index 5d09a95222..9568bfda5e 100644 --- a/packages/studio/src/hooks/useGsapAwareEditing.test.tsx +++ b/packages/studio/src/hooks/useGsapAwareEditing.test.tsx @@ -74,7 +74,7 @@ function mountResizeHandler( size: { width: number; height: number }, offset?: { x: number; y: number }, restore?: () => void, - ) => Promise) + ) => Promise) | null = null; let property: ReturnType["commitAnimatedProperty"] | null = null; function Harness() { @@ -134,13 +134,18 @@ function mountGroupHandler({ | "handleDomRotationCommit" > > = {}) { - let groupCommit!: (updates: DomEditGroupPathOffsetCommit[]) => Promise; + let groupCommit!: ( + updates: DomEditGroupPathOffsetCommit[], + ) => Promise; let pathOffsetCommit!: ( selection: DomEditSelection, next: { x: number; y: number }, route?: { plainTranslate?: boolean }, - ) => Promise; - let rotationCommit!: (selection: DomEditSelection, next: RotationCommit) => Promise; + ) => Promise; + let rotationCommit!: ( + selection: DomEditSelection, + next: RotationCommit, + ) => Promise; function Harness() { const editing = useGsapAwareEditing({ domEditSelection: null, @@ -581,7 +586,7 @@ describe("useGsapAwareEditing anchored resize", () => { h.selection.element.setAttribute("data-hf-drag-initial-offset-x", "0"); h.selection.element.setAttribute("data-hf-drag-initial-offset-y", "0"); - let commit!: Promise; + let commit!: Promise; act(() => { commit = h.resize(h.selection, { width: 300, height: 200 }, { x: -50.2, y: -25.6 }); }); @@ -628,7 +633,7 @@ describe("useGsapAwareEditing anchored resize", () => { s: DomEditSelection, m: unknown, o: { coalesceKey?: string; label?: string; softReload?: boolean }, - ) => Promise, + ) => Promise, _fetch: unknown, options?: { preflightOnly?: boolean }, ) => { diff --git a/packages/studio/src/hooks/useGsapAwareEditing.ts b/packages/studio/src/hooks/useGsapAwareEditing.ts index f2deb8798a..d1b4a1ed29 100644 --- a/packages/studio/src/hooks/useGsapAwareEditing.ts +++ b/packages/studio/src/hooks/useGsapAwareEditing.ts @@ -1,3 +1,6 @@ +import { useGsapAwareGroupMove } from "./useGsapAwareGroupMove"; +import { observeGsapGesture } from "./gsapGestureOutcome"; +import type { DomEditPersistOutcome } from "./domEditCommitTypes"; /** * GSAP-aware move/resize/rotation wrappers that intercept geometry commits * for animated elements and route them through script mutation instead of @@ -21,14 +24,9 @@ import { useGsapSaveFailureTelemetry, useSafeGsapCommitMutation, } from "./useSafeGsapCommitMutation"; -import type { - CommitMutation, - CommitMutationCall, - CommitMutationOptions, -} from "./gsapScriptCommitTypes"; +import type { CommitMutation, CommitMutationOptions } from "./gsapScriptCommitTypes"; import { setElementGsapPosition } from "../utils/elementGsap"; import { logResize, logResizeSettle } from "../utils/resizeDebug"; -import type { DomEditGroupPathOffsetCommit } from "../components/editor/DomEditOverlay"; import type { MoveCommitOptions } from "../components/editor/domEditOverlayGestures"; import { runGestureTransaction } from "./gestureTransaction"; import { @@ -39,19 +37,14 @@ import { POSITION_CHANNELS, } from "./gsapRuntimeKeyframes"; import { assertGsapEditPersisted, saveMove } from "./gsapEditOutcome"; -import { firstPreflightFailure } from "./gsapGroupPreflight"; import type { GsapAnimationFetchOptions } from "./useGsapAnimationFetchFallback"; -import { refuseGsapTakeover, type ElementOffsetStagerDeps } from "./elementOffsetStager"; +import { type ElementOffsetStagerDeps } from "./elementOffsetStager"; import { prepareCropResize, saveCropResize, writeSizeWithCrop, } from "../components/editor/cropResize"; -// Distinct coalesceKey per group drag so consecutive group drags don't fold -// into one another's undo entry (module-local counter, not Date.now()). -let groupDragCommitCounter = 0; - export interface UseGsapAwareEditingParams { domEditSelection: DomEditSelection | null; selectedGsapAnimations: GsapAnimation[]; @@ -76,15 +69,18 @@ export interface UseGsapAwareEditingParams { next: { x: number; y: number }, plainTranslate: boolean, coalesceKey?: string, - ) => { save: () => Promise; rollback: () => void }; - handleDomRotationCommit: (selection: DomEditSelection, next: RotationCommit) => Promise; + ) => { save: () => Promise; rollback: () => void }; + handleDomRotationCommit: ( + selection: DomEditSelection, + next: RotationCommit, + ) => Promise; handleDomBoxSizeCommit: ( selection: DomEditSelection, next: { width: number; height: number }, offset?: { x: number; y: number }, restore?: () => void, undoKey?: string, - ) => Promise; + ) => Promise; commitPositionPatchToHtml: ElementOffsetStagerDeps["commitPositionPatchToHtml"]; // GSAP script commit ops (from useGsapScriptCommits) addGsapAnimation: ( @@ -152,10 +148,12 @@ export function useGsapAwareEditing({ next: { x: number; y: number }, modifiers?: MoveCommitOptions, ) => { - // A gesture and the panel carry their route; webmcp's moveTo decides here. - if (modifiers?.plainTranslate ?? !gsapWritesPosition(selection.element)) - return stageElementPositionOffset(selection, next, true).save(); - if (gsapCommitMutation) { + const writes = observeGsapGesture(gsapCommitMutation); + if (modifiers?.plainTranslate ?? !gsapWritesPosition(selection.element)) { + const result = await stageElementPositionOffset(selection, next, true).save(); + return writes.finish(result?.changed === true); + } + if (writes.commit) { try { const ownedAnimations = getGsapAnimationsForSelection(selection); const targetAnimations = Array.isArray(ownedAnimations) @@ -166,11 +164,15 @@ export function useGsapAwareEditing({ next, targetAnimations, previewIframeRef.current, - gsapCommitMutation, + writes.commit, makeFetchFallback(selection), modifiers, ); - await saveMove(outcome, () => stageElementPositionOffset(selection, next, false).save()); + await saveMove(outcome, async () => { + const result = await stageElementPositionOffset(selection, next, false).save(); + writes.recordDomResult(result); + }); + return writes.finish(); } catch (error) { trackGsapInteractionFailure(error, selection, "drag", "Move animated layer"); throw error; @@ -187,135 +189,14 @@ export function useGsapAwareEditing({ ], ); - // Multi-select (group) drag: each member takes the single drag's writer, so a member GSAP - // does not position is saved on itself and the rest go through the GSAP intercept. - const handleGsapAwareGroupPathOffsetCommit = useCallback( - async (updates: DomEditGroupPathOffsetCommit[], options: { refusalToast?: boolean } = {}) => { - if (!gsapCommitMutation || updates.length === 0) return; - const toastRefusal = options.refusalToast !== false; - // One user action, one undo entry: a shared coalesceKey with an infinite window survives - // the N sequential round trips, so N members don't take N presses to undo. - const coalesceKey = `group-drag:${++groupDragCommitCounter}`; - // Members are written one at a time, and a re-render re-runs the script with the OLD - // position of every member not yet written, so they snap back until their own write - // lands. The drafts are already on screen: hold the render until the last member. - let renderOnCommit = false; - const previewFallbackLatch = { pending: false }; - const withGroupOptions = (options: CommitMutationOptions): CommitMutationOptions => ({ - ...options, - coalesceKey, - coalesceMs: Number.POSITIVE_INFINITY, - deferPreviewSync: !renderOnCommit, - previewFallbackLatch, - }); - // Every member writes the same file: queue the mutations and send ONE request, so the - // server parses and writes the composition once and the preview patches once. - const queued: CommitMutationCall[] = []; - const flushQueued = async () => { - if (queued.length === 0) return; - const calls = queued.splice(0, queued.length); - if (!gsapCommitMutation.batch) { - for (const call of calls) { - await gsapCommitMutation(call.selection, call.mutation, call.options); - } - return; - } - await gsapCommitMutation.batch(calls, { - ...(calls.at(-1)?.options ?? { label: "Move animated layer (group)" }), - label: "Move animated layer (group)", - }); - }; - const coalescedCommit: typeof gsapCommitMutation = (selection, mutation, options) => { - queued.push({ selection, mutation, options: withGroupOptions(options) }); - return Promise.resolve(); - }; - const preflightAnimations = new Map(); - // Members saved on themselves, each with its route: true for its CSS translate. - const offsetMembers = new Map(); - // Prove every member can be written, keyframe plan included, before the first mutation, so a - // blocked one never leaves siblings half moved. Preflights write nothing and share one parse. - const preflightResults = await Promise.allSettled( - updates.map(async ({ selection, next, plainTranslate }) => { - if (plainTranslate ?? !gsapWritesPosition(selection.element)) { - refuseGsapTakeover(selection.element, toastRefusal ? showToast : () => {}); - return void offsetMembers.set(selection, true); - } - const animations = await makeFetchFallback(selection, { failOnFetchError: true })(); - preflightAnimations.set(selection, animations); - const outcome = await tryGsapDragIntercept( - selection, - next, - animations, - previewIframeRef.current, - coalescedCommit, - undefined, - { preflightOnly: true, group: true }, - ); - if (outcome.status === "element-offset") offsetMembers.set(selection, false); - assertGsapEditPersisted(outcome); - }), - ); - const preflightFailure = firstPreflightFailure(preflightResults, updates, offsetMembers); - if (preflightFailure) { - trackGsapInteractionFailure( - preflightFailure.error, - preflightFailure.selection, - "drag", - "Move animated layer (group)", - toastRefusal, - ); - throw preflightFailure.error; - } - const lastScriptWrite = updates.findLastIndex( - ({ selection }) => !offsetMembers.has(selection), - ); - for (const [index, { selection, next }] of updates.entries()) { - renderOnCommit = index === lastScriptWrite; - const plain = offsetMembers.get(selection); - if (plain !== undefined) { - await stageElementPositionOffset(selection, next, plain, coalesceKey).save(); - continue; - } - try { - const outcome = await tryGsapDragIntercept( - selection, - next, - preflightAnimations.get(selection) ?? [], - previewIframeRef.current, - coalescedCommit, - // The intercept re-reads the file to resolve a stale or shared tween. - // Anything already queued has to be on disk before that read, or it - // resolves against a file missing writes it is about to build on. - async () => { - await flushQueued(); - return makeFetchFallback(selection, { fresh: true })(); - }, - { preflightPassed: true }, - ); - assertGsapEditPersisted(outcome); - } catch (error) { - trackGsapInteractionFailure(error, selection, "drag", "Move animated layer (group)"); - throw error; - } - } - try { - await flushQueued(); - } catch (error) { - // The aggregate write has no uniquely failing member; do not misattribute - // its telemetry to whichever member happened to be last in the array. - trackGsapInteractionFailure(error, null, "drag", "Move animated layer (group)"); - throw error; - } - }, - [ - gsapCommitMutation, - previewIframeRef, - makeFetchFallback, - trackGsapInteractionFailure, - stageElementPositionOffset, - showToast, - ], - ); + const handleGsapAwareGroupPathOffsetCommit = useGsapAwareGroupMove({ + gsapCommitMutation, + previewIframeRef, + makeFetchFallback, + trackGsapInteractionFailure, + stageElementPositionOffset, + showToast, + }); const handleGsapAwareBoxSizeCommit = useCallback( async ( @@ -324,8 +205,11 @@ export function useGsapAwareEditing({ offset?: { x: number; y: number }, restore: () => void = () => undefined, ) => { - if (!gsapWritesBox(selection.element)) - return handleDomBoxSizeCommit(selection, next, offset, restore); + const writes = observeGsapGesture(gsapCommitMutation); + if (!gsapWritesBox(selection.element)) { + const result = await handleDomBoxSizeCommit(selection, next, offset, restore); + return writes.finish(result?.changed === true); + } let targetAnimations: GsapAnimation[]; try { const ownedAnimations = getGsapAnimationsForSelection(selection); @@ -355,7 +239,28 @@ export function useGsapAwareEditing({ let anchorMove: ReturnType | null = null; const stageCrop = prepareCropResize(selection.element); let cropUndoKey: string | null = null; - return runGestureTransaction({ + const saveResizeAnchor = async ( + ownsDragOffset: boolean, + commitMutation: CommitMutation, + coalesceKey: string, + ) => { + if (offset && !ownsDragOffset) { + const dragOutcome = await tryGsapDragIntercept( + selection, + offset, + targetAnimations, + previewIframeRef.current, + commitMutation, + makeFetchFallback(selection), + ); + // Saved after the size, under its undo key, so the two are one step. + await saveMove(dragOutcome, async () => { + const plain = !gsapWritesPosition(selection.element); + anchorMove = stageElementPositionOffset(selection, offset, plain, coalesceKey); + }); + } + }; + await runGestureTransaction({ element: selection.element, label: "Resize layer", settle: () => { @@ -371,8 +276,8 @@ export function useGsapAwareEditing({ setElementGsapPosition(selection.element, newX, newY); }, persist: async (commit, coalesceKey) => { - if (gsapCommitMutation) { - const commitMutation = commit(gsapCommitMutation); + if (writes.commit) { + const commitMutation = commit(writes.commit); try { const outcome = await tryGsapResizeIntercept( selection, @@ -385,9 +290,16 @@ export function useGsapAwareEditing({ ); assertGsapEditPersisted(outcome); // Saved before the buffered GSAP writes, so their reload stays the gesture's last render. - if (outcome.status === "element-size") - await handleDomBoxSizeCommit(selection, next, undefined, undefined, coalesceKey); - else cropUndoKey = coalesceKey; + if (outcome.status === "element-size") { + const result = await handleDomBoxSizeCommit( + selection, + next, + undefined, + undefined, + coalesceKey, + ); + writes.recordDomResult(result); + } else cropUndoKey = coalesceKey; // What the resize did, not what its tweens suggest: a scale hold still commits a size. const ownsDragOffset = outcome.status === "persisted" && outcome.ownsDragOffset === true; @@ -398,21 +310,7 @@ export function useGsapAwareEditing({ }); // A resize that moved the element itself has already written // where it landed. Everything else leaves the anchor to the drag. - if (offset && !ownsDragOffset) { - const dragOutcome = await tryGsapDragIntercept( - selection, - offset, - targetAnimations, - previewIframeRef.current, - commitMutation, - makeFetchFallback(selection), - ); - // Saved after the size, under its undo key, so the two are one step. - await saveMove(dragOutcome, async () => { - const plain = !gsapWritesPosition(selection.element); - anchorMove = stageElementPositionOffset(selection, offset, plain, coalesceKey); - }); - } + await saveResizeAnchor(ownsDragOffset, commitMutation, coalesceKey); logResizeSettle(selection.element, ownsDragOffset ? "gsap-scale" : "gsap-size"); return; } catch (error) { @@ -423,10 +321,17 @@ export function useGsapAwareEditing({ throw new Error("Resize of a GSAP-owned box has no GSAP writer"); }, afterBufferedCommitsSaved: async () => { - await anchorMove?.save(); + const anchorResult = await anchorMove?.save(); + writes.recordDomResult(anchorResult); // Only now is the size live for every caller, drag or not. if (cropUndoKey) { - await saveCropResize(stageCrop, selection, commitPositionPatchToHtml, cropUndoKey); + const cropResult = await saveCropResize( + stageCrop, + selection, + commitPositionPatchToHtml, + cropUndoKey, + ); + writes.recordDomResult(cropResult); } }, restore: () => { @@ -435,6 +340,7 @@ export function useGsapAwareEditing({ }, skipPixelAssert: hasLivePositionTween, }); + return writes.finish(); }, [ handleDomBoxSizeCommit, @@ -450,9 +356,12 @@ export function useGsapAwareEditing({ const handleGsapAwareRotationCommit = useCallback( async (selection: DomEditSelection, next: RotationCommit) => { - if (next.plain || !gsapWritesRotation(selection.element)) - return handleDomRotationCommit(selection, next); - if (gsapCommitMutation) { + const writes = observeGsapGesture(gsapCommitMutation); + if (next.plain || !gsapWritesRotation(selection.element)) { + const result = await handleDomRotationCommit(selection, next); + return writes.finish(result?.changed === true); + } + if (writes.commit) { try { const targetAnimations = await getGsapAnimationsForSelection(selection); // A keyframe or a tl.set; a computed source rejects, so the gesture restores its draft. @@ -461,10 +370,11 @@ export function useGsapAwareEditing({ next.angle, targetAnimations, previewIframeRef.current, - gsapCommitMutation, + writes.commit, makeFetchFallback(selection), ); assertGsapEditPersisted(outcome); + return writes.finish(); } catch (error) { trackGsapInteractionFailure(error, selection, "rotation", "Rotate animated layer"); throw error; @@ -553,12 +463,16 @@ export function useGsapAwareEditing({ ); const commitMutation = useCallback( - async (mutation: Record, options: { label: string; softReload?: boolean }) => { - if (!domEditSelection) return; + async ( + mutation: Record, + options: CommitMutationOptions, + selection = domEditSelection, + ) => { + if (!selection) return; // Return (await) the safe-commit chain so consumers that `await // session.commitMutation(...)` (gesture recording, enable-keyframes) run // their post-actions only after the server save has settled. - await safeGsapCommit(domEditSelection, mutation, options); + await safeGsapCommit(selection, mutation, options); }, [domEditSelection, safeGsapCommit], ); diff --git a/packages/studio/src/hooks/useGsapAwareGroupMove.ts b/packages/studio/src/hooks/useGsapAwareGroupMove.ts new file mode 100644 index 0000000000..b8518260ab --- /dev/null +++ b/packages/studio/src/hooks/useGsapAwareGroupMove.ts @@ -0,0 +1,171 @@ +import { useCallback } from "react"; +import type { DomEditSelection } from "../components/editor/domEditingTypes"; +import type { DomEditGroupPathOffsetCommit } from "../components/editor/DomEditOverlay"; +import type { GsapAnimation } from "@hyperframes/core/gsap-parser"; +import type { CommitMutationCall, CommitMutationOptions } from "./gsapScriptCommitTypes"; +import type { UseGsapAwareEditingParams } from "./useGsapAwareEditing"; +import { observeGsapGesture } from "./gsapGestureOutcome"; +import { gsapWritesPosition } from "./gsapRuntimeKeyframes"; +import { refuseGsapTakeover } from "./elementOffsetStager"; +import { tryGsapDragIntercept } from "./gsapRuntimeBridge"; +import { assertGsapEditPersisted } from "./gsapEditOutcome"; +import { firstPreflightFailure } from "./gsapGroupPreflight"; + +// A distinct key keeps consecutive group drags in separate undo entries. +let groupDragCommitCounter = 0; + +export function useGsapAwareGroupMove({ + gsapCommitMutation, + previewIframeRef, + makeFetchFallback, + trackGsapInteractionFailure, + stageElementPositionOffset, + showToast, +}: Pick< + UseGsapAwareEditingParams, + | "gsapCommitMutation" + | "previewIframeRef" + | "makeFetchFallback" + | "trackGsapInteractionFailure" + | "stageElementPositionOffset" + | "showToast" +>) { + const handleGsapAwareGroupPathOffsetCommit = useCallback( + async ( + updates: DomEditGroupPathOffsetCommit[], + options: { refusalToast?: boolean } = {}, + ): Promise => { + const writes = observeGsapGesture(gsapCommitMutation); + const writer = writes.commit; + if (!writer) return { ok: true, changed: false }; + const toastRefusal = options.refusalToast !== false; + // One coalesce key across slow writes keeps the group drag in one undo entry. + const coalesceKey = `group-drag:${++groupDragCommitCounter}`; + // Hold the render until every member is saved, or unwritten members snap back. + let renderOnCommit = false; + const previewFallbackLatch = { pending: false }; + const withGroupOptions = (options: CommitMutationOptions): CommitMutationOptions => ({ + ...options, + coalesceKey, + coalesceMs: Number.POSITIVE_INFINITY, + deferPreviewSync: !renderOnCommit, + previewFallbackLatch, + }); + // Batch members in the same file to avoid repeating its read, parse, write and preview patch. + const queued: CommitMutationCall[] = []; + const flushQueued = async () => { + if (queued.length === 0) return; + const calls = queued.splice(0, queued.length); + if (!writer.batch) { + for (const call of calls) { + await writer(call.selection, call.mutation, call.options); + } + return; + } + await writer.batch(calls, { + ...(calls.at(-1)?.options ?? { label: "Move animated layer (group)" }), + label: "Move animated layer (group)", + }); + }; + const coalescedCommit: typeof gsapCommitMutation = (selection, mutation, options) => { + queued.push({ selection, mutation, options: withGroupOptions(options) }); + return Promise.resolve(); + }; + const preflightAnimations = new Map(); + // Members saved on themselves, each with its route: true for its CSS translate. + const offsetMembers = new Map(); + // Editability is user-atomic: prove every member can be written before the first source + // mutation, so a blocked member never leaves earlier siblings partially moved. Preflights + // write nothing and share one in-flight parse per file, so they run together. + const preflightResults = await Promise.allSettled( + updates.map(async ({ selection, next, plainTranslate }) => { + if (plainTranslate ?? !gsapWritesPosition(selection.element)) { + refuseGsapTakeover(selection.element, toastRefusal ? showToast : () => {}); + return void offsetMembers.set(selection, true); + } + const animations = await makeFetchFallback(selection, { failOnFetchError: true })(); + preflightAnimations.set(selection, animations); + const outcome = await tryGsapDragIntercept( + selection, + next, + animations, + previewIframeRef.current, + coalescedCommit, + undefined, + { preflightOnly: true, group: true }, + ); + if (outcome.status === "element-offset") offsetMembers.set(selection, false); + assertGsapEditPersisted(outcome); + }), + ); + const preflightFailure = firstPreflightFailure(preflightResults, updates, offsetMembers); + if (preflightFailure) { + trackGsapInteractionFailure( + preflightFailure.error, + preflightFailure.selection, + "drag", + "Move animated layer (group)", + toastRefusal, + ); + throw preflightFailure.error; + } + const lastScriptWrite = updates.findLastIndex( + ({ selection }) => !offsetMembers.has(selection), + ); + for (const [index, { selection, next }] of updates.entries()) { + renderOnCommit = index === lastScriptWrite; + const plain = offsetMembers.get(selection); + if (plain !== undefined) { + const result = await stageElementPositionOffset( + selection, + next, + plain, + coalesceKey, + ).save(); + writes.recordDomResult(result); + continue; + } + try { + const outcome = await tryGsapDragIntercept( + selection, + next, + preflightAnimations.get(selection) ?? [], + previewIframeRef.current, + coalescedCommit, + // The intercept re-reads the file to resolve a stale or shared tween. + // Anything already queued has to be on disk before that read, or it + // resolves against a file missing writes it is about to build on. + async () => { + await flushQueued(); + return makeFetchFallback(selection, { fresh: true })(); + }, + { preflightPassed: true }, + ); + assertGsapEditPersisted(outcome); + } catch (error) { + trackGsapInteractionFailure(error, selection, "drag", "Move animated layer (group)"); + throw error; + } + } + try { + await flushQueued(); + return writes.finish(); + } catch (error) { + // The aggregate write has no uniquely failing member; do not misattribute + // its telemetry to whichever member happened to be last in the array. + trackGsapInteractionFailure(error, null, "drag", "Move animated layer (group)"); + throw error; + } + }, + [ + gsapCommitMutation, + previewIframeRef, + makeFetchFallback, + trackGsapInteractionFailure, + stageElementPositionOffset, + showToast, + ], + ); + + return handleGsapAwareGroupPathOffsetCommit; +} diff --git a/packages/studio/src/hooks/useGsapKeyframeOps.sdkUsage.test.tsx b/packages/studio/src/hooks/useGsapKeyframeOps.sdkUsage.test.tsx new file mode 100644 index 0000000000..8f0a56d961 --- /dev/null +++ b/packages/studio/src/hooks/useGsapKeyframeOps.sdkUsage.test.tsx @@ -0,0 +1,114 @@ +// @vitest-environment happy-dom +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { useGsapKeyframeOps } from "./useGsapKeyframeOps"; +import type { CutoverResult } from "../utils/sdkCutover"; +import type { DomEditSelection } from "../components/editor/domEditingTypes"; +import { trackStudioEvent } from "../utils/studioTelemetry"; + +const sdkWrite = vi.hoisted(() => vi.fn<(...args: unknown[]) => Promise>()); +vi.mock("../utils/sdkCutover", async (original) => ({ + ...(await original()), + sdkGsapKeyframePersist: sdkWrite, + sdkGsapConvertToKeyframesPersist: sdkWrite, + sdkGsapRemoveAllKeyframesPersist: sdkWrite, +})); +vi.mock("../utils/studioTelemetry", () => ({ trackStudioEvent: vi.fn() })); +Reflect.set(globalThis, "IS_REACT_ACT_ENVIRONMENT", true); +type Params = Parameters[0]; +let root: Root; +function mount() { + let api: ReturnType | undefined; + const legacy = vi.fn(async () => undefined); + function Probe() { + api = useGsapKeyframeOps({ + activeCompPath: "index.html", + commitMutation: legacy, + commitMutationSafely: legacy, + trackGsapSaveFailure: vi.fn(), + sdkSession: {} as NonNullable, + sdkDeps: { + editHistory: { recordEdit: vi.fn(async () => undefined) }, + writeProjectFile: vi.fn(async () => undefined), + reloadPreview: vi.fn(), + }, + }); + return null; + } + root = createRoot(document.createElement("div")); + act(() => root.render()); + if (!api) throw new Error("hook did not mount"); + return { api, legacy }; +} +const selection = { id: "private-target", sourceFile: "private.html" } as DomEditSelection; +beforeEach(() => { + vi.clearAllMocks(); + sdkWrite.mockResolvedValue({ + status: "committed", + version: "v2", + before: "before", + after: "after", + }); +}); +afterEach(() => act(() => root.unmount())); +describe("SDK keyframe usage", () => { + it.each(["add", "convert", "remove_all", "reset"] as const)( + "counts a changed committed %s operation once", + async (action) => { + const { api, legacy } = mount(); + await act(async () => { + if (action === "add") + await api.addKeyframeBatch(selection, "private-animation", 50, { x: 12, y: 4 }); + else if (action === "convert") await api.convertToKeyframes(selection, "private-animation"); + else await api.removeAllKeyframes(selection, "private-animation", action); + }); + expect(legacy).not.toHaveBeenCalled(); + expect(trackStudioEvent).toHaveBeenCalledExactlyOnceWith("keyframe", { action }); + }, + ); + it("preserves property metadata on a single-property SDK add", async () => { + const { api } = mount(); + await act(async () => api.addKeyframe(selection, "private-animation", 50, "x", 12)); + expect(trackStudioEvent).toHaveBeenCalledExactlyOnceWith("keyframe", { + action: "add", + property: "x", + }); + }); + it("does not count unchanged SDK source", async () => { + sdkWrite.mockResolvedValue({ + status: "committed", + version: "v2", + before: "same", + after: "same", + }); + const { api } = mount(); + await api.addKeyframeBatch(selection, "private-animation", 50, { x: 12 }); + expect(await api.removeAllKeyframes(selection, "private-animation")).toBe(false); + expect(trackStudioEvent).not.toHaveBeenCalled(); + }); + it("honors intermediate-write suppression in SDK paths", async () => { + const { api } = mount(); + await api.convertToKeyframes(selection, "private-animation", undefined, undefined, { + keyframeTelemetry: false, + }); + await api.addKeyframeBatch( + selection, + "private-animation", + 50, + { x: 12 }, + { keyframeTelemetry: false }, + ); + await api.removeAllKeyframes(selection, "private-animation", "remove_all", false); + expect(trackStudioEvent).not.toHaveBeenCalled(); + }); + it("does not fall back or count after a failed SDK write", async () => { + sdkWrite.mockResolvedValue({ status: "failed", error: new Error("refused") }); + const { api, legacy } = mount(); + await expect( + api.addKeyframeBatch(selection, "private-animation", 50, { x: 12 }), + ).rejects.toThrow("refused"); + expect(legacy).not.toHaveBeenCalled(); + expect(trackStudioEvent).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/studio/src/hooks/useGsapKeyframeOps.ts b/packages/studio/src/hooks/useGsapKeyframeOps.ts index ca77fe0c0c..16b4b88d15 100644 --- a/packages/studio/src/hooks/useGsapKeyframeOps.ts +++ b/packages/studio/src/hooks/useGsapKeyframeOps.ts @@ -1,3 +1,4 @@ +import { trackKeyframeUsage } from "../utils/keyframeUsage"; // fallow-ignore-file code-duplication // Add/remove operation-family transaction shapes stay parallel until SDK graduation. import { useCallback } from "react"; @@ -139,10 +140,14 @@ export function useGsapKeyframeOps({ coalesceKey: `gsap:${animationId}:kf:${percentage}`, }, ); - if (cutoverCommittedOrThrow(handled)) return; + if (cutoverCommittedOrThrow(handled)) { + if (handled.before !== handled.after) trackKeyframeUsage("add", property); + return; + } } await commitMutation(selection, mutation, { label: `Add keyframe at ${percentage}%`, + keyframeProperty: property, softReload: true, }); }, @@ -172,7 +177,11 @@ export function useGsapKeyframeOps({ sdkDeps, toSdkPersistOptions(`Add keyframe at ${percentage}%`, commitOverrides), ); - if (cutoverCommittedOrThrow(handled)) return; + if (cutoverCommittedOrThrow(handled)) { + if (handled.before !== handled.after && commitOverrides?.keyframeTelemetry !== false) + trackKeyframeUsage("add"); + return; + } } return commitMutation( selection, @@ -319,7 +328,11 @@ export function useGsapKeyframeOps({ sdkDeps, toSdkPersistOptions("Convert to keyframes", commitOverrides), ); - if (cutoverCommittedOrThrow(handled)) return; + if (cutoverCommittedOrThrow(handled)) { + if (handled.before !== handled.after && commitOverrides.keyframeTelemetry !== false) + trackKeyframeUsage("convert"); + return; + } } return commitMutation( selection, @@ -333,11 +346,19 @@ export function useGsapKeyframeOps({ ); const removeAllKeyframes = useCallback( - async (selection: DomEditSelection, animationId: string) => { + async ( + selection: DomEditSelection, + animationId: string, + action: "remove_all" | "reset" = "remove_all", + telemetry = true, + ): Promise => { const targetPath = selection.sourceFile || activeCompPath || "index.html"; // A class/descendant selector can resolve a live element whose selection // deliberately has no id. The cache is still keyed by that DOM id. - const cacheElementId = selection.id || selection.element?.id; + const clearCache = () => { + const cacheElementId = selection.id || selection.element?.id; + if (cacheElementId) clearKeyframeCacheForElement(targetPath, cacheElementId); + }; if (sdkSession && sdkDeps) { const handled = await sdkGsapRemoveAllKeyframesPersist( targetPath, @@ -347,26 +368,31 @@ export function useGsapKeyframeOps({ { label: "Remove all keyframes" }, ); if (cutoverCommittedOrThrow(handled)) { - if (cacheElementId) clearKeyframeCacheForElement(targetPath, cacheElementId); - return; + clearCache(); + const changed = handled.before !== handled.after; + if (changed && telemetry) trackKeyframeUsage(action); + return changed; } } + let changed = false; await commitMutationSafely( selection, { type: "remove-all-keyframes", animationId }, { label: "Remove all keyframes", + keyframeAction: action, + keyframeTelemetry: telemetry, softReload: true, // The committed result is the single success boundary: clearing // before it makes failed saves lie, while waiting for the reload leaves // stale diamonds visible during the source round-trip. onResult: (result) => { - if (result.changed !== false && cacheElementId) { - clearKeyframeCacheForElement(targetPath, cacheElementId); - } + changed = result.ok && result.changed === true; + if (changed) clearCache(); }, }, ); + return changed; }, [commitMutationSafely, activeCompPath, sdkSession, sdkDeps], ); diff --git a/packages/studio/src/hooks/useGsapScriptCommits.test.tsx b/packages/studio/src/hooks/useGsapScriptCommits.test.tsx index 22667405f1..caba304cfa 100644 --- a/packages/studio/src/hooks/useGsapScriptCommits.test.tsx +++ b/packages/studio/src/hooks/useGsapScriptCommits.test.tsx @@ -590,6 +590,63 @@ describe("runCommit — instantPatch wiring", () => { vi.unstubAllGlobals(); }); + it.each([ + ["add-keyframe", "add"], + ["add-with-keyframes", "add"], + ["convert-to-keyframes", "convert"], + ["remove-all-keyframes", "remove_all"], + ])("counts %s only after a changed durable write", async (type, action) => { + mockFetchResult(); + const deps = renderCommitHook(); + await deps.api.commitMutation( + selection, + { type, properties: { text: "private-content" } }, + { label: "Edit" }, + ); + expect(trackStudioEvent.mock.calls.filter(([event]) => event === "keyframe")).toEqual([ + ["keyframe", { action }], + ]); + }); + + it("counts reset with its explicit action and suppresses intermediate writes", async () => { + mockFetchResult(); + const deps = renderCommitHook(); + await deps.api.commitMutation( + selection, + { type: "convert-to-keyframes" }, + { label: "Convert", keyframeTelemetry: false }, + ); + await deps.api.commitMutation( + selection, + { type: "remove-all-keyframes" }, + { label: "Reset", keyframeAction: "reset" }, + ); + expect(trackStudioEvent.mock.calls.filter(([event]) => event === "keyframe")).toEqual([ + ["keyframe", { action: "reset" }], + ]); + }); + + it("does not count a successful unchanged keyframe write", async () => { + mockFetchResult({ changed: false }); + const deps = renderCommitHook(); + await deps.api.commitMutation(selection, { type: "add-keyframe" }, { label: "Add" }); + expect(trackStudioEvent.mock.calls.filter(([event]) => event === "keyframe")).toEqual([]); + }); + + it("does not count a failed write that skipReload suppresses", async () => { + vi.stubGlobal( + "fetch", + vi.fn(async () => ({ ok: false, status: 500 })), + ); + const deps = renderCommitHook(); + await deps.api.commitMutation( + selection, + { type: "add-keyframe" }, + { label: "Add", skipReload: true }, + ); + expect(trackStudioEvent.mock.calls.filter(([event]) => event === "keyframe")).toEqual([]); + }); + const NESTED_SCRIPT = 'window.__timelines["root"] = tl;'; const SUB = ``; diff --git a/packages/studio/src/hooks/useGsapScriptCommits.ts b/packages/studio/src/hooks/useGsapScriptCommits.ts index 8519ef8a8b..dfd6d7c35f 100644 --- a/packages/studio/src/hooks/useGsapScriptCommits.ts +++ b/packages/studio/src/hooks/useGsapScriptCommits.ts @@ -11,6 +11,7 @@ import { } from "../utils/gsapSoftReload"; import type { SoftReloadResult } from "../utils/gsapSoftReload"; import { trackStudioEvent } from "../utils/studioTelemetry"; +import { trackKeyframeCommit } from "../utils/keyframeUsage"; import { serializeStudioFileMutation } from "../utils/studioFileMutationCoordinator"; import { trackedStudioEdit } from "../utils/studioPendingEdits"; import { @@ -392,6 +393,7 @@ export function useGsapScriptCommits({ projectIdRef, activeCompPath, previewIfra mutateGsapScript(pid, targetPath, mutation), ); if (!result) return; + trackKeyframeCommit([mutation], result, options); options.onResult?.(result); await finalizeSuccessfulMutation(pid, compositionPath, selection, mutation, targetPath, result, options); }, [showToast, finalizeSuccessfulMutation]); @@ -405,6 +407,7 @@ export function useGsapScriptCommits({ projectIdRef, activeCompPath, previewIfra mutateGsapScriptBatch(pid, targetPath, mutations), ); if (!result) return; + trackKeyframeCommit(mutations, result, options, calls.map((call) => call.options)); options.onResult?.(result); // Each call brings its own fast-path patch; the batch wrote them all, so the // preview sync applies them all rather than just the last call's. diff --git a/packages/studio/src/hooks/useGsapSelectionHandlers.test.tsx b/packages/studio/src/hooks/useGsapSelectionHandlers.test.tsx index 6317c2b249..47b00f805f 100644 --- a/packages/studio/src/hooks/useGsapSelectionHandlers.test.tsx +++ b/packages/studio/src/hooks/useGsapSelectionHandlers.test.tsx @@ -42,7 +42,7 @@ function makeParams(overrides: Partial = {}): Params { moveKeyframe: vi.fn().mockResolvedValue(true), resizeKeyframedTween: vi.fn().mockResolvedValue(true), convertToKeyframes: resolved(), - removeAllKeyframes: resolved(), + removeAllKeyframes: vi.fn().mockResolvedValue(true), handleDomManualEditsReset: vi.fn(), selectedGsapAnimations: [], showToast: vi.fn(), diff --git a/packages/studio/src/hooks/useGsapSelectionHandlers.ts b/packages/studio/src/hooks/useGsapSelectionHandlers.ts index 6479061cd5..e7101ffca5 100644 --- a/packages/studio/src/hooks/useGsapSelectionHandlers.ts +++ b/packages/studio/src/hooks/useGsapSelectionHandlers.ts @@ -109,9 +109,16 @@ export function useGsapSelectionHandlers({ duration?: number, commitOverrides?: Partial, ) => Promise; - removeAllKeyframes: (sel: DomEditSelection, animId: string) => Promise; + removeAllKeyframes: ( + sel: DomEditSelection, + animId: string, + action?: "remove_all" | "reset", + telemetry?: boolean, + ) => Promise; - handleDomManualEditsReset: (sel: DomEditSelection) => Promise; + handleDomManualEditsReset: ( + sel: DomEditSelection, + ) => Promise; selectedGsapAnimations: GsapAnimation[]; showToast: (message: string, tone?: "error" | "info") => void; }) { @@ -323,7 +330,6 @@ export function useGsapSelectionHandlers({ ) => { const sel = resolveWriteSelection(selectionOverride); if (!sel) return; - trackStudioEvent("keyframe", { action: "add", property }); addKeyframe(sel, animId, percentage, property, value); }, [resolveWriteSelection, addKeyframe], @@ -441,31 +447,31 @@ export function useGsapSelectionHandlers({ ); const handleGsapRemoveAllKeyframes = useCallback( - (animId: string, selectionOverride?: DomEditSelection | null) => { + (animId: string, selectionOverride?: DomEditSelection | null, telemetry = true) => { const selection = resolveWriteSelection(selectionOverride); if (!selection) return Promise.resolve(false); - return observeGsapMutation( - removeAllKeyframes(selection, animId), - selection, - "remove-all-keyframes", - "Remove all keyframes", - ); + return removeAllKeyframes(selection, animId, "remove_all", telemetry).catch((error) => { + trackGsapHandlerFailure(error, selection, "remove-all-keyframes", "Remove all keyframes"); + return false; + }); }, - [resolveWriteSelection, observeGsapMutation, removeAllKeyframes], + [resolveWriteSelection, trackGsapHandlerFailure, removeAllKeyframes], ); const handleResetSelectedElementKeyframes = useCallback((): boolean => { if (!domEditSelection) return false; const withKeyframes = selectedGsapAnimations.find((a) => a.keyframes); if (!withKeyframes) return false; - observeGsapMutation( - removeAllKeyframes(domEditSelection, withKeyframes.id), - domEditSelection, - "remove-all-keyframes", - "Remove all keyframes", - ); + void removeAllKeyframes(domEditSelection, withKeyframes.id, "reset").catch((error) => { + trackGsapHandlerFailure( + error, + domEditSelection, + "remove-all-keyframes", + "Remove all keyframes", + ); + }); return true; - }, [domEditSelection, observeGsapMutation, removeAllKeyframes, selectedGsapAnimations]); + }, [domEditSelection, trackGsapHandlerFailure, removeAllKeyframes, selectedGsapAnimations]); return { handleGsapUpdateProperty, diff --git a/packages/studio/src/hooks/usePanelLayout.ts b/packages/studio/src/hooks/usePanelLayout.ts index ddeda8f120..3e83f0fcae 100644 --- a/packages/studio/src/hooks/usePanelLayout.ts +++ b/packages/studio/src/hooks/usePanelLayout.ts @@ -3,6 +3,7 @@ import type { RightPanelTab } from "../utils/studioHelpers"; import { trackStudioEvent } from "../utils/studioTelemetry"; import { useDockLayoutStore, visiblePanelInZone } from "../components/dock/dockLayoutStore"; import { PANEL_DEFINITIONS, type PanelId } from "../components/dock/panelRegistry"; +import { useStableHandlers } from "./useStableHandlers"; export interface InitialPanelLayoutState { rightCollapsed?: boolean | null; @@ -66,5 +67,8 @@ export function usePanelLayout(initialState?: InitialPanelLayoutState) { store.setZoneVisible("right", !collapsed); }, []); - return { rightCollapsed, setRightCollapsed, rightPanelTab, setRightPanelTab }; + return useStableHandlers( + { rightCollapsed, setRightCollapsed, rightPanelTab, setRightPanelTab }, + null, + ); } diff --git a/packages/studio/src/hooks/usePreviewInteraction.test.ts b/packages/studio/src/hooks/usePreviewInteraction.test.ts index 7a7013dfb1..6bc79817fa 100644 --- a/packages/studio/src/hooks/usePreviewInteraction.test.ts +++ b/packages/studio/src/hooks/usePreviewInteraction.test.ts @@ -299,3 +299,24 @@ describe("a refused move's toast", () => { ]); }); }); + +vi.mock("../utils/studioTelemetry", () => ({ trackStudioEvent: vi.fn() })); +import { trackStudioEvent } from "../utils/studioTelemetry"; +it("counts additive preview selection only after resolving a hit", async () => { + vi.mocked(trackStudioEvent).mockClear(); + const selection = makeSelection("Card", document.createElement("div")); + const applyDomSelection = vi.fn(); + const { canvas, cleanup } = renderHarness({ + previewIframe: createPreviewIframe(vi.fn()), + resolveDomSelectionFromPreviewPoint: vi.fn(async () => selection), + applyDomSelection, + }); + await dispatchMouseDown(canvas, { shiftKey: true }); + expect(applyDomSelection).toHaveBeenCalledWith(selection, { additive: true }); + expect(trackStudioEvent).toHaveBeenCalledExactlyOnceWith("feature_used", { + feature: "multi_select", + surface: "preview", + method: "button", + }); + cleanup(); +}); diff --git a/packages/studio/src/hooks/usePreviewInteraction.ts b/packages/studio/src/hooks/usePreviewInteraction.ts index 563cc816d8..9b5395307e 100644 --- a/packages/studio/src/hooks/usePreviewInteraction.ts +++ b/packages/studio/src/hooks/usePreviewInteraction.ts @@ -1,3 +1,4 @@ +import { trackPreviewFeatureUsed } from "../utils/previewFeatureUsage"; import { useCallback, useRef } from "react"; import { liveTime, usePlayerStore } from "../player"; import { pauseStudioPreviewPlayback } from "../utils/studioPreviewHelpers"; @@ -169,6 +170,7 @@ export function usePreviewInteraction({ e.preventDefault(); e.stopPropagation(); applyDomSelection(nextSelection, { additive: true }); + trackPreviewFeatureUsed("multi_select", "button"); return; } diff --git a/packages/studio/src/hooks/useRenderClipContent.test.ts b/packages/studio/src/hooks/useRenderClipContent.test.ts index 9528406fb0..5146a0c987 100644 --- a/packages/studio/src/hooks/useRenderClipContent.test.ts +++ b/packages/studio/src/hooks/useRenderClipContent.test.ts @@ -6,6 +6,7 @@ import { afterEach, describe, expect, it } from "vitest"; import { CompositionThumbnail, VideoThumbnail } from "../player"; import { AudioWaveform } from "../player/components/AudioWaveform"; import { AudibleVideoClipContent } from "../player/components/AudibleVideoClipContent"; +import { TextClipContent } from "../player/components/TextClipContent"; import { ClipPeakMarks } from "../player/components/ClipPeakMarks"; function unwrapPeakMarks(node: ReactNode): ReactNode { @@ -280,6 +281,23 @@ describe("useRenderClipContent", () => { expect(isValidElement(content) && content.type).toBe(AudibleVideoClipContent); }); + it("gives a layer spanning the whole film its own frame, whatever its id", () => { + usePlayerStore.setState({ thumbnailMode: "adaptive" }); + for (const id of ["waves", "background-glyphs"]) { + const content = renderClipContent({ id, tag: "div", start: 0, duration: 12, track: 0 }, null); + expect(isValidElement(content) && content.type).toBe(CompositionThumbnail); + } + }); + + it("draws a text layer's own words instead of capturing them", () => { + usePlayerStore.setState({ thumbnailMode: "adaptive" }); + const content = renderClipContent( + { id: "title", tag: "h1", start: 0, duration: 12, track: 0, text: { value: "Ship it" } }, + null, + ); + expect(isValidElement(content) && content.type).toBe(TextClipContent); + }); + it("passes empty labels to thumbnail content so TimelineClip owns clip names", () => { usePlayerStore.setState({ thumbnailMode: "adaptive" }); diff --git a/packages/studio/src/hooks/useRenderClipContent.ts b/packages/studio/src/hooks/useRenderClipContent.ts index b677c531a4..5dc25c92d3 100644 --- a/packages/studio/src/hooks/useRenderClipContent.ts +++ b/packages/studio/src/hooks/useRenderClipContent.ts @@ -12,6 +12,7 @@ import type { TimelineClipRenderContext } from "../player/components/TimelineTyp import { audioPillFlags } from "../player/components/audioClipLink"; import { AudioWaveform, rendersWaveform } from "../player/components/AudioWaveform"; import { ImageThumbnail } from "../player/components/ImageThumbnail"; +import { TextClipContent } from "../player/components/TextClipContent"; import { AudibleVideoClipContent } from "../player/components/AudibleVideoClipContent"; import { ClipPeakMarks } from "../player/components/ClipPeakMarks"; import { clipPeaksUrl, clipSourceWindow } from "../player/components/clipPeakMap"; @@ -184,6 +185,8 @@ export function useRenderClipContent({ return renderAudioClip(el, pid, sessionEpoch, style.label, context, elements); } + if (el.text) return createElement(TextClipContent, { text: el.text }); + // When drilled into a composition, render all inner elements via // CompositionThumbnail at their start time — most accurate visual. if (activePreviewUrl && el.duration > 0) { @@ -207,11 +210,7 @@ export function useRenderClipContent({ }); } - const htmlPreviewEligible = - el.duration > 0 && - effectiveTimelineDuration > 0 && - el.duration < effectiveTimelineDuration * 0.92 && - !/(backdrop|background|overlay|scrim|mask)/i.test(el.id); + const htmlPreviewEligible = el.duration > 0 && effectiveTimelineDuration > 0; if ((el.tag === "video" || el.tag === "img") && el.src) { const mediaSrc = resolveMediaPreviewUrl(el.src, pid, window.location.origin); diff --git a/packages/studio/src/hooks/useShellSlices.ts b/packages/studio/src/hooks/useShellSlices.ts new file mode 100644 index 0000000000..28470a2881 --- /dev/null +++ b/packages/studio/src/hooks/useShellSlices.ts @@ -0,0 +1,53 @@ +import { useMemo } from "react"; +import type { EnableKeyframesSession } from "./useEnableKeyframes"; + +interface HistoryFlags { + canUndo: boolean; + canRedo: boolean; + undoLabel: string | undefined; + redoLabel: string | undefined; +} + +/** The four history fields the shell context carries, as one object that changes only when they do. */ +export function useHistoryFlags({ canUndo, canRedo, undoLabel, redoLabel }: HistoryFlags) { + return useMemo( + () => ({ canUndo, canRedo, undoLabel, redoLabel }), + [canUndo, canRedo, undoLabel, redoLabel], + ); +} + +/** The session fields the timeline toolbar reads, so a hover or any other session change leaves it alone. */ +export function useToolbarSession(session: EnableKeyframesSession): EnableKeyframesSession { + const { + domEditSelection, + selectedGsapAnimations, + previewIframeRef, + commitMutation, + handleGsapAddAnimation, + handleGsapAddKeyframeBatch, + handleGsapConvertToKeyframes, + handleGsapRemoveKeyframe, + } = session; + return useMemo( + () => ({ + domEditSelection, + selectedGsapAnimations, + previewIframeRef, + commitMutation, + handleGsapAddAnimation, + handleGsapAddKeyframeBatch, + handleGsapConvertToKeyframes, + handleGsapRemoveKeyframe, + }), + [ + domEditSelection, + selectedGsapAnimations, + previewIframeRef, + commitMutation, + handleGsapAddAnimation, + handleGsapAddKeyframeBatch, + handleGsapConvertToKeyframes, + handleGsapRemoveKeyframe, + ], + ); +} diff --git a/packages/studio/src/hooks/useStableHandlers.test.tsx b/packages/studio/src/hooks/useStableHandlers.test.tsx new file mode 100644 index 0000000000..e5166a79b4 --- /dev/null +++ b/packages/studio/src/hooks/useStableHandlers.test.tsx @@ -0,0 +1,77 @@ +// @vitest-environment happy-dom + +import React, { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, describe, expect, it } from "vitest"; +import { useStableHandlers } from "./useStableHandlers"; + +(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +interface Result { + count: number; + read: () => number; +} + +let root: Root | null = null; +afterEach(() => { + act(() => root?.unmount()); + root = null; +}); + +function renderStable(seen: Result[]) { + function Probe({ count, base }: { count: number; base: number }) { + seen.push(useStableHandlers({ count, read: () => base }, "project")); + return null; + } + root = createRoot(document.createElement("div")); + return (count: number, base: number) => + act(() => root!.render()); +} + +describe("useStableHandlers", () => { + it("keeps the object while only its handlers change, and the handler calls the latest one", () => { + const seen: Result[] = []; + const render = renderStable(seen); + render(1, 10); + render(1, 20); + expect(seen[1]).toBe(seen[0]); + expect(seen[1]!.read()).toBe(20); + }); + + it("gives a new object when a data field changes, with the same handler identity", () => { + const seen: Result[] = []; + const render = renderStable(seen); + render(1, 10); + render(2, 10); + expect(seen[1]).not.toBe(seen[0]); + expect(seen[1]!.count).toBe(2); + expect(seen[1]!.read).toBe(seen[0]!.read); + }); + + it("keeps a wrapper from an earlier scope calling that scope's handler", () => { + const seen: { write: () => string }[] = []; + function Scoped({ project }: { project: string }) { + seen.push(useStableHandlers({ write: () => project }, project)); + return null; + } + root = createRoot(document.createElement("div")); + act(() => root!.render()); + const kept = seen[0]!.write; + act(() => root!.render()); + expect(kept()).toBe("a"); + expect(seen[1]!.write).not.toBe(kept); + expect(seen[1]!.write()).toBe("b"); + }); + + it("gives a new object when a key is swapped for another with the same value", () => { + const seen: Record[] = []; + function Keys({ name }: { name: string }) { + seen.push(useStableHandlers({ [name]: undefined }, "project")); + return null; + } + root = createRoot(document.createElement("div")); + act(() => root!.render()); + act(() => root!.render()); + expect(Object.keys(seen[1]!)).toEqual(["fresh"]); + }); +}); diff --git a/packages/studio/src/hooks/useStableHandlers.ts b/packages/studio/src/hooks/useStableHandlers.ts new file mode 100644 index 0000000000..ad124f2d1e --- /dev/null +++ b/packages/studio/src/hooks/useStableHandlers.ts @@ -0,0 +1,44 @@ +import { useRef } from "react"; + +type Handler = (...args: never[]) => unknown; +type Epoch = { + scope: unknown; + latest: object; + wrappers: Map; + previous: object | null; +}; + +// The same object while its non-function fields are unchanged, and one identity per function field calling the +// latest one; a new `scope` (the project) starts new identities, and a wrapper kept from before calls its own scope's. +export function useStableHandlers(value: T, scope: unknown): T { + const epoch = useRef(null); + if (!epoch.current || !Object.is(epoch.current.scope, scope)) + epoch.current = { scope, latest: value, wrappers: new Map(), previous: null }; + const current = epoch.current; + current.latest = value; + + const next: Record = {}; + for (const [key, field] of Object.entries(value)) { + if (typeof field !== "function") { + next[key] = field; + continue; + } + let wrapper = current.wrappers.get(key); + if (!wrapper) { + wrapper = (...args: never[]) => + (current.latest as Record unknown>)[key]!(...args); + current.wrappers.set(key, wrapper); + } + next[key] = wrapper; + } + const prev = current.previous as Record | null; + const keys = Object.keys(next); + if ( + prev && + keys.length === Object.keys(prev).length && + keys.every((k) => k in prev && prev[k] === next[k]) + ) + return prev as T; + current.previous = next; + return next as T; +} diff --git a/packages/studio/src/hooks/useStudioSdkSessions.ts b/packages/studio/src/hooks/useStudioSdkSessions.ts index 648b735a9a..202cc0626d 100644 --- a/packages/studio/src/hooks/useStudioSdkSessions.ts +++ b/packages/studio/src/hooks/useStudioSdkSessions.ts @@ -1,6 +1,7 @@ import { useEffect } from "react"; import { useSdkSession } from "./useSdkSession"; import { usePreviewVariablesStore } from "./previewVariablesStore"; +import { useStableHandlers } from "./useStableHandlers"; /** * Open the studio's SDK session with master-view semantics. @@ -37,5 +38,5 @@ export function useStudioSdkSessions( useEffect(() => { usePreviewVariablesStore.getState().setValues(null); }, [projectId, activeCompPath]); - return { sdkHandle, editFlowSdkSession }; + return { sdkHandle: useStableHandlers(sdkHandle, projectId), editFlowSdkSession }; } diff --git a/packages/studio/src/hooks/useStudioSidePanels.test.tsx b/packages/studio/src/hooks/useStudioSidePanels.test.tsx new file mode 100644 index 0000000000..f48d12d1ae --- /dev/null +++ b/packages/studio/src/hooks/useStudioSidePanels.test.tsx @@ -0,0 +1,44 @@ +// @vitest-environment happy-dom + +import React, { act, type ComponentProps } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { StudioLeftPanels } from "../components/StudioLeftPanels"; +import type { StudioRightPanels } from "../components/StudioRightPanels"; +import { useStudioSidePanels } from "./useStudioSidePanels"; + +const rightProps = vi.hoisted(() => [] as { recordEdit: (project: string) => string }[]); +vi.mock("../components/StudioLeftPanels", () => ({ StudioLeftPanels: () => null })); +vi.mock("../components/StudioRightPanels", () => ({ + StudioRightPanels: (props: { recordEdit: (project: string) => string }) => { + rightProps.push(props); + return null; + }, +})); + +(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +let root: Root | null = null; +afterEach(() => { + act(() => root?.unmount()); + root = null; + rightProps.length = 0; +}); + +function Panels({ project }: { project: string }) { + const right = { recordEdit: () => project } as unknown as ComponentProps< + typeof StudioRightPanels + >; + return useStudioSidePanels({} as ComponentProps, right, project); +} + +describe("useStudioSidePanels", () => { + it("keeps a panel handler from one project calling that project after a switch", () => { + root = createRoot(document.createElement("div")); + act(() => root!.render()); + const kept = rightProps.at(-1)!.recordEdit; + act(() => root!.render()); + expect(kept("")).toBe("a"); + expect(rightProps.at(-1)!.recordEdit("")).toBe("b"); + }); +}); diff --git a/packages/studio/src/hooks/useStudioSidePanels.tsx b/packages/studio/src/hooks/useStudioSidePanels.tsx new file mode 100644 index 0000000000..41fa916a4d --- /dev/null +++ b/packages/studio/src/hooks/useStudioSidePanels.tsx @@ -0,0 +1,23 @@ +import { useMemo, type ComponentProps } from "react"; +import { StudioLeftPanels } from "../components/StudioLeftPanels"; +import { StudioRightPanels } from "../components/StudioRightPanels"; +import { useStableHandlers } from "./useStableHandlers"; + +/** Both side panels as one element that changes only when a panel's data does, never for a new handler. */ +export function useStudioSidePanels( + left: ComponentProps, + right: ComponentProps, + projectId: string | null, +) { + const stableLeft = useStableHandlers(left, projectId); + const stableRight = useStableHandlers(right, projectId); + return useMemo( + () => ( + <> + + + + ), + [stableLeft, stableRight], + ); +} diff --git a/packages/studio/src/hooks/useTimelineAddAtPlayhead.ts b/packages/studio/src/hooks/useTimelineAddAtPlayhead.ts index 4307f1ffec..11cbc9654d 100644 --- a/packages/studio/src/hooks/useTimelineAddAtPlayhead.ts +++ b/packages/studio/src/hooks/useTimelineAddAtPlayhead.ts @@ -1,15 +1,23 @@ import { useCallback } from "react"; import { usePlayerStore } from "../player"; +import { useStableHandlers } from "./useStableHandlers"; type AddAtPlacement = (path: string, placement: { start: number; track: number }) => unknown; -export function useTimelineAddAtPlayhead(addAsset: AddAtPlacement, addComposition: AddAtPlacement) { +export function useTimelineAddAtPlayhead( + addAsset: AddAtPlacement, + addComposition: AddAtPlacement, + projectId: string | null, +) { const placement = () => ({ start: usePlayerStore.getState().currentTime, track: 0 }); - return { - addAssetAtPlayhead: useCallback((path: string) => addAsset(path, placement()), [addAsset]), - addCompositionAtPlayhead: useCallback( - (path: string) => addComposition(path, placement()), - [addComposition], - ), - }; + return useStableHandlers( + { + addAssetAtPlayhead: useCallback((path: string) => addAsset(path, placement()), [addAsset]), + addCompositionAtPlayhead: useCallback( + (path: string) => addComposition(path, placement()), + [addComposition], + ), + }, + projectId, + ); } diff --git a/packages/studio/src/hooks/useTimelineEditing.ts b/packages/studio/src/hooks/useTimelineEditing.ts index 3471a11e3d..427f874c89 100644 --- a/packages/studio/src/hooks/useTimelineEditing.ts +++ b/packages/studio/src/hooks/useTimelineEditing.ts @@ -1,5 +1,6 @@ // fallow-ignore-file complexity import { useCallback, useRef } from "react"; +import { useStableHandlers } from "./useStableHandlers"; import { usePlayerStore, type TimelineElement } from "../player"; import { toAuthoredStart, toCompositionTime } from "../player/store/timelineElement"; import { useRazorSplit } from "./useRazorSplit"; @@ -508,13 +509,41 @@ export function useTimelineEditing({ return [...flatMembers, ...domMembers]; }; + const audioGroupAttribute = { + ...setAudioGroupAttribute, + // Same two-array member lookup syncStoredGroupAttribute mirrors into + // (timelineAudioGroupVolume.ts): a sub-composition's group members have + // no flat twin, only a domClipChildren entry, so both are checked. + setQuiet: track( + guard(audioGroupMembers, setAudioGroupAttribute.setQuiet, (reason, groupId, attr) => { + setAudioGroupAttribute.revertLive(groupId, attr); + return refused(reason); + }), + ), + }; + const stableAudioGroupAttribute = useStableHandlers(audioGroupAttribute, projectId); + const elementFxAttribute = { + ...setElementFxAttribute, + setMany: track(guard((edits) => edits.map((edit) => edit.element), setElementsAttribute)), + setQuiet: track( + guard( + (element) => [element], + setElementFxAttribute.setQuiet, + (reason, element, attr) => { + setElementFxAttribute.revertLive(element, attr); + return refused(reason); + }, + ), + ), + }; + const stableElementFxAttribute = useStableHandlers(elementFxAttribute, projectId); // Every write-handler is tracked here, the one place all hand edits // converge, so undo never races a write; canEdit gates the same point. // Coverage boundary: see the PR body, not every kind resolves an element. const trackedRazorSplit = track( guard((element) => withLinkPartners([element]), handleRazorSplit), ); - return { + const editing = { handleTimelineElementMove: track(guard((element) => [element], handleTimelineElementMove)), handleTimelineElementResize: track(guard((element) => [element], handleTimelineElementResize)), handleToggleTrackHidden: track( @@ -530,32 +559,8 @@ export function useTimelineEditing({ }, handleToggleElementHidden), ), handleAutoGroupCarveSources: track(handleAutoGroupCarveSources), - setAudioGroupAttribute: { - ...setAudioGroupAttribute, - // Same two-array member lookup syncStoredGroupAttribute mirrors into - // (timelineAudioGroupVolume.ts): a sub-composition's group members have - // no flat twin, only a domClipChildren entry, so both are checked. - setQuiet: track( - guard(audioGroupMembers, setAudioGroupAttribute.setQuiet, (reason, groupId, attr) => { - setAudioGroupAttribute.revertLive(groupId, attr); - return refused(reason); - }), - ), - }, - setElementFxAttribute: { - ...setElementFxAttribute, - setMany: track(guard((edits) => edits.map((edit) => edit.element), setElementsAttribute)), - setQuiet: track( - guard( - (element) => [element], - setElementFxAttribute.setQuiet, - (reason, element, attr) => { - setElementFxAttribute.revertLive(element, attr); - return refused(reason); - }, - ), - ), - }, + setAudioGroupAttribute: stableAudioGroupAttribute, + setElementFxAttribute: stableElementFxAttribute, handleTimelineElementDelete: track( guard((element) => withLinkPartners([element]), linkEditing.handleLinkedElementDelete), ), @@ -591,4 +596,5 @@ export function useTimelineEditing({ setAudioGroupAttribute.restoreLive(restore); }, }; + return useStableHandlers(editing, projectId); } diff --git a/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx b/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx index 998ae8513f..a8bbf75d63 100644 --- a/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx +++ b/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx @@ -4,6 +4,7 @@ import { act } from "react"; import { afterEach, describe, expect, it, vi } from "vitest"; import type { Root } from "react-dom/client"; import type { TimelineElement } from "../player"; +import { persistTimelineMoveEditsAtomically } from "./timelineMoveAdapter"; import { useTimelineGroupEditing } from "./useTimelineGroupEditing"; import { installReactActEnvironment, mountReactHarness } from "./domSelectionTestHarness"; @@ -72,3 +73,79 @@ describe("useTimelineGroupEditing: handleTimelineGroupMove suppressFailureToast" expect(showToast).toHaveBeenCalledTimes(1); }); }); + +it.each([false, true])( + "keeps detachment and the lane atomic, including a refused history write ($0)", + async (refused) => { + const before = + '
'; + let disk = before; + const failure = new Error("history refused"); + const recordEdit = refused ? vi.fn().mockRejectedValue(failure) : vi.fn(); + const iframe = document.createElement("iframe"); + document.body.append(iframe); + iframe.contentDocument!.body.innerHTML = before; + const writeProjectFile = vi.fn(async (_path: string, content: string) => { + disk = content; + }); + vi.stubGlobal( + "fetch", + vi.fn( + async () => + new Response(JSON.stringify({ content: disk }), { + headers: { "content-type": "application/json" }, + }), + ), + ); + let hook: ReturnType; + function Harness() { + hook = useTimelineGroupEditing({ + activeCompPath: "index.html", + editQueueRef: { current: Promise.resolve() }, + pendingTimelineEditPathRef: { current: new Set() }, + previewIframeRef: { current: iframe }, + projectIdRef: { current: "fixture" }, + recordEdit, + writeProjectFile, + reloadPreview: vi.fn(), + showToast: vi.fn(), + }); + return null; + } + const root = mountReactHarness(); + try { + await act(async () => { + const moved = persistTimelineMoveEditsAtomically( + [ + { + element: { ...el("voice", 0, 2, 1), tag: "audio", audioGroup: "group" }, + updates: { start: 0, track: 0, audioGroup: null }, + }, + ], + "insert", + "track-insert", + { handleTimelineGroupMove: hook!.handleTimelineGroupMove }, + ); + if (refused) await expect(moved).rejects.toBe(failure); + else await moved; + }); + expect( + iframe.contentDocument!.getElementById("voice")?.getAttribute("data-audio-group"), + ).toBe("group"); + if (refused) { + expect(disk).toBe(before); + expect(writeProjectFile).toHaveBeenCalledTimes(2); + return; + } + expect(writeProjectFile).toHaveBeenCalledOnce(); + expect(recordEdit).toHaveBeenCalledOnce(); + expect(disk).not.toContain("data-audio-group"); + expect(disk).toContain('data-track-index="0"'); + expect(recordEdit.mock.calls[0][0].files["index.html"]).toEqual({ before, after: disk }); + } finally { + act(() => root.unmount()); + iframe.remove(); + vi.unstubAllGlobals(); + } + }, +); diff --git a/packages/studio/src/hooks/useTimelineGroupEditing.ts b/packages/studio/src/hooks/useTimelineGroupEditing.ts index 03cb03bc6b..9eb124252d 100644 --- a/packages/studio/src/hooks/useTimelineGroupEditing.ts +++ b/packages/studio/src/hooks/useTimelineGroupEditing.ts @@ -37,6 +37,7 @@ export interface TimelineGroupMoveChange { element: TimelineElement; start: number; track?: number; + audioGroup?: null; } export interface TimelineGroupResizeChange { @@ -296,7 +297,9 @@ export function useTimelineGroupEditing({ sdkChanges: toSdkTimingChanges(changes, (change) => ({ start: toAuthoredStart(change.element, change.start), })), - eligible: changes.every((change) => change.track == null), + eligible: changes.every( + (change) => change.track == null && change.audioGroup === undefined, + ), needsExtension, label, coalesceKey, @@ -315,6 +318,7 @@ export function useTimelineGroupEditing({ toAuthoredStart(change.element, change.start), change.element.duration, change.track, + change.audioGroup, ), })), coalesceKey, diff --git a/packages/studio/src/index.ts b/packages/studio/src/index.ts index 4024a375d1..126ecd89d5 100644 --- a/packages/studio/src/index.ts +++ b/packages/studio/src/index.ts @@ -62,6 +62,13 @@ export { TimelineProvider, useTimelineContext } from "./player/components/Timeli export type { TimelineTheme } from "./player/components/timelineTheme"; export { TRACK_H } from "./player/components/timelineLayout"; export type { TimelineTrackPadding } from "./player/components/timelineLayout"; +export { displayTrackOrder } from "./player/components/useTimelineTrackDerivations"; +export { fadeHandleBoxes } from "./player/components/timelineClipFadeGeometry"; +export type { + FadeEdge, + FadeHandleBox, + FadeHandleClipBox, +} from "./player/components/timelineClipFadeGeometry"; // Clip content thumbnails: used by a host rendering its own timeline lane. export { AudioWaveform } from "./player/components/AudioWaveform"; diff --git a/packages/studio/src/main.tsx b/packages/studio/src/main.tsx index 7ee9e3953f..63c0ab5710 100644 --- a/packages/studio/src/main.tsx +++ b/packages/studio/src/main.tsx @@ -7,8 +7,12 @@ import { StudioErrorBoundary } from "./components/StudioErrorBoundary"; import { readIconTokens } from "./styles/iconTokens"; import { trackStudioEvent } from "./utils/studioTelemetry"; import { prefetchPreviewForHash } from "./utils/previewPrefetch"; +import { bindThumbnailPageLifecycle } from "./player/lib/thumbnailPageLifecycle"; import "./styles/studio.css"; +const unbindThumbnailPageLifecycle = bindThumbnailPageLifecycle(window, document); +import.meta.hot?.dispose(unbindThumbnailPageLifecycle); + prefetchPreviewForHash(window.location.hash); window.addEventListener("hashchange", () => prefetchPreviewForHash(window.location.hash)); trackStudioEvent("session_start"); diff --git a/packages/studio/src/player/components/ClipBadges.tsx b/packages/studio/src/player/components/ClipBadges.tsx index 3e3c514b9a..69a8980307 100644 --- a/packages/studio/src/player/components/ClipBadges.tsx +++ b/packages/studio/src/player/components/ClipBadges.tsx @@ -24,7 +24,7 @@ function SpeakerGlyph({ muted }: { muted: boolean }) { const BADGE_CLASS = "timeline-clip__badge inline-flex items-center gap-0.5 rounded-[3px] border bg-black/55 px-1 text-[9px] leading-[14px] whitespace-nowrap"; const FX_ON = "border-white/40 text-white font-semibold"; -const FX_OFF = "border-white/10 text-white/35"; +const FX_OFF = "border-white/10 text-white/60"; /** Premiere's fx badge — grey with no effects, white with any; hover lists them, click opens the clip menu. */ export const ClipBadges = memo(function ClipBadges({ @@ -44,21 +44,21 @@ export const ClipBadges = memo(function ClipBadges({ }; return ( {volume && ( - {volume === "Muted" ? null : {volume}} + {volume === "Muted" ? null : {volume}} )} { + it("puts dark text on a light strip and light text on a dark one", () => { + expect(textClipBackground({ value: "a", color: "rgb(16, 20, 24)" })).toBe( + "var(--timeline-text-clip-light-bg)", + ); + expect(textClipBackground({ value: "a", color: "rgb(255, 255, 255)" })).toBe( + "var(--timeline-text-clip-dark-bg)", + ); + }); + + it("uses the layer's own background when it paints one", () => { + expect( + textClipBackground({ value: "a", color: "rgb(16, 20, 24)", background: "rgb(230, 57, 70)" }), + ).toBe("rgb(230, 57, 70)"); + }); +}); diff --git a/packages/studio/src/player/components/TextClipContent.tsx b/packages/studio/src/player/components/TextClipContent.tsx new file mode 100644 index 0000000000..1ca8d3c58d --- /dev/null +++ b/packages/studio/src/player/components/TextClipContent.tsx @@ -0,0 +1,27 @@ +import { parseCssColor } from "../../components/editor/colorValue"; +import type { TimelineText } from "../store/timelineElement"; + +/** The layer's own background, or a strip the text reads on: light behind dark text, dark otherwise. */ +export function textClipBackground(text: TimelineText): string { + if (text.background) return text.background; + const color = parseCssColor(text.color ?? ""); + const light = color ? 0.2126 * color.red + 0.7152 * color.green + 0.0722 * color.blue : 255; + return light < 128 ? "var(--timeline-text-clip-light-bg)" : "var(--timeline-text-clip-dark-bg)"; +} + +/** A text layer's row: its own words in its own font and colour, live, on one clipped line. */ +export function TextClipContent({ text }: { text: TimelineText }) { + return ( +
+ + {text.value} + +
+ ); +} diff --git a/packages/studio/src/player/components/Timeline.ghostLane.test.tsx b/packages/studio/src/player/components/Timeline.ghostLane.test.tsx index d777c0b888..dfc0126409 100644 --- a/packages/studio/src/player/components/Timeline.ghostLane.test.tsx +++ b/packages/studio/src/player/components/Timeline.ghostLane.test.tsx @@ -1,14 +1,14 @@ // @vitest-environment happy-dom -import React, { act } from "react"; -import { createRoot } from "react-dom/client"; +import { act } from "react"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { Timeline } from "./Timeline"; +import { + mountThreeTrackTimeline as mountThreeTracks, + dragTimelineFixtureAsset, + pointerTimelineFixture as pointer, +} from "./timelineMountFixtures"; import { installTimelineMountEnv } from "./timelineMountTestEnv"; -import { usePlayerStore } from "../store/playerStore"; import { CLIP_Y, TRACK_H, getTimelineRowTop } from "./timelineLayout"; -import { TIMELINE_ASSET_MIME } from "../../utils/timelineAssetDrop"; -import type { TimelineProps } from "./TimelineTypes"; (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; @@ -21,32 +21,6 @@ afterEach(() => { const GHOST_MID = getTimelineRowTop(3) + TRACK_H / 2; const ROW1_MID = getTimelineRowTop(1) + TRACK_H / 2; -async function mountThreeTracks(props: TimelineProps = {}) { - usePlayerStore.setState({ - duration: 10, - currentTime: 0, - timelineReady: true, - gsapAnimations: new Map(), - selectedElementId: null, - selectedElementIds: new Set(), - elements: [0, 1, 2].map((track) => ({ - id: `c${track}`, - key: `c${track}`, - domId: `c${track}`, - tag: "div", - start: 0, - duration: 2, - track, - })), - }); - const host = document.createElement("div"); - document.body.append(host); - const root = createRoot(host); - await act(async () => root.render()); - const ghost = () => host.querySelector('[data-testid="timeline-ghost-lane"]'); - return { host, root, ghost }; -} - describe("Timeline ghost lane", () => { it("draws one empty track below the last with a drop hint", async () => { const { root, ghost } = await mountThreeTracks({ onAssetDrop: vi.fn() }); @@ -70,22 +44,8 @@ describe("Timeline ghost lane", () => { const onAssetDrop = vi.fn(); const { host, root, ghost } = await mountThreeTracks({ onAssetDrop }); const viewport = host.querySelector("[data-timeline-scroll-viewport]")!; - const drag = (type: string, clientY: number) => { - const event = new Event(type, { bubbles: true, cancelable: true }); - Object.defineProperties(event, { - clientX: { value: 400 }, - clientY: { value: clientY }, - dataTransfer: { - value: { - types: [TIMELINE_ASSET_MIME], - files: [], - dropEffect: "none", - getData: (mime: string) => (mime === TIMELINE_ASSET_MIME ? '{"path":"a.png"}' : ""), - }, - }, - }); - act(() => void viewport.dispatchEvent(event)); - }; + const drag = (type: string, clientY: number) => + dragTimelineFixtureAsset(viewport, type, clientY); drag("dragover", ROW1_MID); expect(ghost()?.dataset.active).toBeUndefined(); drag("dragover", GHOST_MID); @@ -100,19 +60,6 @@ describe("Timeline ghost lane", () => { onMoveElement: vi.fn(), onResizeElement: vi.fn(), }); - const pointer = (target: EventTarget, type: string, clientY: number) => - act( - () => - void target.dispatchEvent( - new PointerEvent(type, { - bubbles: true, - button: 0, - pointerId: 1, - clientX: 400, - clientY, - }), - ), - ); const clipMid = getTimelineRowTop(track) + TRACK_H / 2; pointer(host.querySelector(`[data-clip][data-el-id="c${track}"]`)!, "pointerdown", clipMid); pointer(window, "pointermove", ROW1_MID); diff --git a/packages/studio/src/player/components/Timeline.trackPadding.test.tsx b/packages/studio/src/player/components/Timeline.trackPadding.test.tsx index 83c422ea2b..b73d0d6254 100644 --- a/packages/studio/src/player/components/Timeline.trackPadding.test.tsx +++ b/packages/studio/src/player/components/Timeline.trackPadding.test.tsx @@ -7,7 +7,11 @@ import { Timeline } from "./Timeline"; import { installTimelineMountEnv } from "./timelineMountTestEnv"; import { usePlayerStore } from "../store/playerStore"; import { CLIP_Y, RULER_H, TRACK_H, TRACKS_BOTTOM_PAD, TRACKS_TOP_PAD } from "./timelineLayout"; -import { TIMELINE_ASSET_MIME } from "../../utils/timelineAssetDrop"; +import { + mountThreeTrackTimeline, + dragTimelineFixtureAsset, + pointerTimelineFixture as pointer, +} from "./timelineMountFixtures"; import type { TimelineProps } from "./TimelineTypes"; (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; @@ -59,29 +63,7 @@ describe("Timeline trackPadding", () => { const hostPads = { top: 0, bottom: TRACK_H }; async function mountThreeTracks(props: TimelineProps = {}) { - usePlayerStore.setState({ - duration: 10, - currentTime: 0, - timelineReady: true, - gsapAnimations: new Map(), - selectedElementId: null, - selectedElementIds: new Set(), - elements: [0, 1, 2].map((track) => ({ - id: `c${track}`, - key: `c${track}`, - domId: `c${track}`, - tag: "div", - start: 0, - duration: 2, - track, - })), - }); - const host = document.createElement("div"); - document.body.append(host); - const root = createRoot(host); - await act(async () => root.render()); - const viewport = host.querySelector("[data-timeline-scroll-viewport]")!; - return { host, root, viewport }; + return mountThreeTrackTimeline({ trackPadding: hostPads, ...props }); } const top = (el: Element | null | undefined) => (el as HTMLElement | null)?.style.top; @@ -94,22 +76,8 @@ describe("Timeline trackPadding", () => { `${RULER_H + TRACK_H + CLIP_Y}px`, ); - const drag = (type: string, clientY: number) => { - const event = new Event(type, { bubbles: true, cancelable: true }); - Object.defineProperties(event, { - clientX: { value: 400 }, - clientY: { value: clientY }, - dataTransfer: { - value: { - types: [TIMELINE_ASSET_MIME], - files: [], - dropEffect: "none", - getData: (mime: string) => (mime === TIMELINE_ASSET_MIME ? '{"path":"a.png"}' : ""), - }, - }, - }); - act(() => void viewport.dispatchEvent(event)); - }; + const drag = (type: string, clientY: number) => + dragTimelineFixtureAsset(viewport, type, clientY); drag("dragover", ROW1_MID); expect(top(host.querySelector('[data-testid="timeline-drop-preview"]'))).toBe( `${RULER_H + TRACK_H + CLIP_Y}px`, @@ -128,19 +96,6 @@ describe("Timeline trackPadding", () => { onMoveElement: vi.fn(), onResizeElement: vi.fn(), }); - const pointer = (target: EventTarget, type: string, clientY: number) => - act( - () => - void target.dispatchEvent( - new PointerEvent(type, { - bubbles: true, - button: 0, - pointerId: 1, - clientX: 400, - clientY, - }), - ), - ); const clip = host.querySelector('[data-clip][data-el-id="c0"]')!; pointer(clip, "pointerdown", RULER_H + TRACK_H / 2); pointer(window, "pointermove", ROW1_MID); @@ -149,9 +104,9 @@ describe("Timeline trackPadding", () => { ).find((el) => el.style.zIndex === "30" && !el.dataset.testid); expect(top(ghost)).toBe(`${RULER_H + TRACK_H + CLIP_Y}px`); pointer(window, "pointermove", RULER_H + 3 * TRACK_H + TRACK_H / 2); - expect(top(host.querySelector('[data-testid="timeline-insert-line"]'))).toBe( - `${RULER_H + 3 * TRACK_H - 0.5}px`, - ); + const lane = host.querySelector("[data-timeline-new-track-lane]"); + expect(top(lane)).toBe(`${RULER_H + 3 * TRACK_H}px`); + expect(lane?.style.height).toBe(`${TRACK_H}px`); act(() => root.unmount()); }); }); diff --git a/packages/studio/src/player/components/TimelineCanvas.tsx b/packages/studio/src/player/components/TimelineCanvas.tsx index a40078df0a..dd9739fc8f 100644 --- a/packages/studio/src/player/components/TimelineCanvas.tsx +++ b/packages/studio/src/player/components/TimelineCanvas.tsx @@ -16,7 +16,9 @@ export const TimelineCanvas = memo(function TimelineCanvas() { const props = state.canvas; const { draggedClip, scrollRef, displayTrackOrder } = props; const draggedRowIndex = - draggedClip?.started === true ? displayTrackOrder.indexOf(draggedClip.previewTrack) : -1; + draggedClip?.started === true + ? (draggedClip.insertRow ?? displayTrackOrder.indexOf(draggedClip.previewTrack)) + : -1; const dropTrackIndex = props.dropPreview ? displayTrackOrder.indexOf(props.dropPreview.track) : -1; @@ -168,7 +170,7 @@ export const TimelineCanvas = memo(function TimelineCanvas() { {/* Insertion line — a new track will be inserted at this boundary on drop. Shown while the pointer is near a lane boundary (insert mode). */} - {insertLineRow != null && ( + {insertLineRow != null && !draggedClip?.started && (
{ + css = ( + await compile('@import "tailwindcss";\n@import "./theme.css";\n@import "./components.css";', { + base: STYLES_DIR, + loadStylesheet: async (id, base) => loadStylesheet(id, base), + }) + ).build(["absolute", "inset-0", "overflow-hidden"]); +}); + +afterEach(() => { + cleanupMounted(); + usePlayerStore.getState().setLintFindingsByElement(new Map()); + document.body.innerHTML = ""; +}); + +function render(tag: string, overrides: Partial = {}, picture = true) { + const host = document.createElement("div"); + document.body.append(host); + const root = trackedRoot(host); + const element: TimelineElement = { + id: "clip", + label: "City", + tag, + start: 0, + duration: 1, + track: 0, + ...overrides, + }; + const renderContent = picture ? () => : undefined; + act(() => { + root.render( + + {renderClipChildren( + element, + { clip: "#222", label: "#fff", accent: "#fff" }, + renderContent, + undefined, + )} + , + ); + }); + return host; +} + +describe("Filmstrip clips", () => { + it.each(["video", "img"])("reserves a 15px name band above %s pictures", (tag) => { + const host = render(tag); + const name = host.querySelector(".timeline-clip__name"); + const picture = host.querySelector(".timeline-clip__content"); + expect(name?.textContent).toBe("City"); + expect(picture).not.toBeNull(); + expect(picture?.querySelector("img")).not.toBeNull(); + expect(css).toMatch(/--timeline-clip-band-height:\s*15px;/); + expect(css).toMatch( + /\.timeline-clip:not\(\.is-audio\) \.timeline-clip__label\s*\{[^}]*height:\s*var\(--timeline-clip-band-height\)/, + ); + expect(css).toMatch( + /\.timeline-clip:not\(\.is-audio\) \.timeline-clip__content\s*\{[^}]*top:\s*var\(--timeline-clip-band-height\);[^}]*border-top-left-radius:\s*0;/, + ); + }); + + it("keeps applied-state badges above the opaque name band", () => { + const host = render("video", { hasAudio: true, volume: 1.8 }); + expect(host.querySelector('[data-badge="volume"]')?.textContent).toBe("180%"); + const badges = host.querySelector('[data-testid="clip-badges"]'); + expect(badges?.classList.contains("z-[31]")).toBe(true); + expect(badges?.classList.contains("max-w-[calc(100%-12px)]")).toBe(true); + expect(badges?.classList.contains("overflow-hidden")).toBe(true); + expect(badges?.parentElement?.classList.contains("timeline-clip__label")).toBe(true); + expect(css).toMatch( + /\.timeline-clip:not\(\.is-audio\) \.timeline-clip__name\s*\{[^}]*flex:\s*1;[^}]*min-width:\s*0;[^}]*overflow:\s*hidden;/, + ); + expect(css).toMatch( + /\.timeline-clip:not\(\.is-audio\) \.timeline-clip__label\s*\{[^}]*z-index:\s*auto;/, + ); + }); + + it("keeps fallback lint warnings clear of the name band and menu badge", () => { + usePlayerStore + .getState() + .setLintFindingsByElement(new Map([["clip", { count: 1, messages: ["Lint warning"] }]])); + const host = render("div", { duration: 0.3 }, false); + const name = host.querySelector(".timeline-clip__name"); + const warning = host.querySelector('[title="Lint warning"]'); + expect(warning).not.toBeNull(); + expect(warning?.style.bottom).toBe("7px"); + expect(warning?.style.top).toBe(""); + expect(css).toMatch(/\.timeline-clip__timecode\s*\{[^}]*right:\s*16px;/); + expect( + (name?.compareDocumentPosition(warning!) ?? 0) & Node.DOCUMENT_POSITION_FOLLOWING, + ).toBeTruthy(); + expect(css).toMatch( + /\.timeline-clip:not\(\.is-audio\) \.timeline-clip__label\s*\{[^}]*z-index:\s*auto;/, + ); + }); + + it.each([0.02, 0.295])( + "keeps the name band without badge targets on a narrow visual clip (%ss)", + (duration) => { + const host = render("video", { duration, hasAudio: true, volume: 1.8 }); + expect(host.querySelector(".timeline-clip__name")?.textContent).toBe("City"); + expect(host.querySelector('[data-testid="clip-badges"]')).toBeNull(); + expect(css).toMatch(/padding:\s*0 min\(6px,\s*25%\);/); + expect(css).toMatch(/padding-left:\s*min\(8px,\s*25%\);/); + }, + ); + + it("lets audio keep its full-height content and pill radius", () => { + const host = render("audio"); + const clip = host.querySelector(".timeline-clip"); + const picture = host.querySelector(".timeline-clip__content"); + expect(clip?.classList.contains("is-audio")).toBe(true); + expect(picture?.classList.contains("inset-0")).toBe(true); + expect(css).toMatch(/--timeline-clip-audio-radius:\s*21px;/); + expect(clip instanceof HTMLElement && clip.style.borderRadius).toBe( + "var(--timeline-clip-audio-radius)", + ); + }); + + it("exports a single 1px selection ring around a 12px visual clip", () => { + const clip = render("video").querySelector(".timeline-clip"); + expect(clip?.classList.contains("is-selected")).toBe(true); + expect(css).toMatch(/--timeline-clip-radius:\s*12px;/); + expect(css).toMatch( + /\.timeline-clip\.is-selected,\s*\.timeline-clip\[data-active\]\.is-selected\s*\{[^}]*outline:\s*1px solid var\(--timeline-clip-selection\);[^}]*outline-offset:\s*0;/, + ); + expect(css).toMatch(/\.timeline-clip:not\(\.is-audio\)\s*\{\s*border-width:\s*0;/); + }); +}); diff --git a/packages/studio/src/player/components/TimelineClip.test.tsx b/packages/studio/src/player/components/TimelineClip.test.tsx index 8a9ebe7f8c..35ebc22b0e 100644 --- a/packages/studio/src/player/components/TimelineClip.test.tsx +++ b/packages/studio/src/player/components/TimelineClip.test.tsx @@ -127,7 +127,7 @@ describe("TimelineClip", () => { element: { id: "hero", label: "Hero", tag: "div", start: 1, duration: 1, track: 0 }, }); - expect(host.querySelector(".timeline-clip__label")?.textContent).toBe("Hero"); + expect(host.querySelector(".timeline-clip__name")?.textContent).toBe("Hero"); expect(host.querySelector(".timeline-clip__timecode")).toBeNull(); act(() => root.unmount()); @@ -145,7 +145,7 @@ describe("TimelineClip", () => { playbackRate: 1.5, }, }); - expect(fast.host.querySelector(".timeline-clip__label")?.textContent).toBe("Hero [150%]"); + expect(fast.host.querySelector(".timeline-clip__name")?.textContent).toBe("Hero [150%]"); act(() => fast.root.unmount()); const automation = JSON.stringify({ version: 1, @@ -170,18 +170,18 @@ describe("TimelineClip", () => { automation, }, }); - expect(ramp.host.querySelector(".timeline-clip__label")?.textContent).toBe("Hero [ramp]"); + expect(ramp.host.querySelector(".timeline-clip__name")?.textContent).toBe("Hero [ramp]"); act(() => ramp.root.unmount()); }); - it("drops the label chip under 60px even when the clip is selected", () => { + it("keeps the name band under 60px even when the clip is selected", () => { const { host, root } = renderClip({ element: { id: "fx", label: "FX", tag: "div", start: 0, duration: 1, track: 0 }, pps: 59, isSelected: true, }); - expect(host.querySelector(".timeline-clip__label")).toBeNull(); + expect(host.querySelector(".timeline-clip__name")?.textContent).toBe("FX"); expect(host.querySelector(".timeline-clip__timecode")).toBeNull(); expect(host.querySelector(".timeline-clip")?.getAttribute("data-ladder")).toBe("picture"); @@ -193,7 +193,7 @@ describe("TimelineClip", () => { element: { id: "wide", label: "City", tag: "video", start: 0, duration: 1, track: 0 }, pps: 200, }); - expect(labeled.host.querySelector(".timeline-clip__label")?.textContent).toBe("City"); + expect(labeled.host.querySelector(".timeline-clip__name")?.textContent).toBe("City"); expect(labeled.host.querySelector(".timeline-clip")?.getAttribute("data-ladder")).toBe( "labeled", ); @@ -207,7 +207,7 @@ describe("TimelineClip", () => { pps: 23, isSelected: true, }); - expect(frame.host.querySelector(".timeline-clip__label")).toBeNull(); + expect(frame.host.querySelector(".timeline-clip__name")?.textContent).toBe("City"); expect(frame.host.querySelector(".timeline-clip")?.getAttribute("data-ladder")).toBe("frame"); act(() => frame.root.unmount()); }); diff --git a/packages/studio/src/player/components/TimelineClip.tsx b/packages/studio/src/player/components/TimelineClip.tsx index c5d959c883..9bf880a3df 100644 --- a/packages/studio/src/player/components/TimelineClip.tsx +++ b/packages/studio/src/player/components/TimelineClip.tsx @@ -1,6 +1,7 @@ import { memo, type CSSProperties, type ReactNode } from "react"; import type { TimelineElement } from "../store/playerStore"; import { + CLIP_TRIM_HIT_PX, clipWidthLadder, defaultTimelineTheme, getClipHandleOpacity, @@ -70,9 +71,10 @@ export const TimelineClip = memo(function TimelineClip({ const widthPx = Math.max(el.duration * pps, 4); const handleOpacity = getClipHandleOpacity({ isHovered, isSelected, isDragging }); const displayLabel = `${el.label || el.id || el.tag}${clipSpeedSuffix(el.playbackRate, el.automation)}`; + const isAudioClip = isAudioTimelineElement(el); const ladder = clipWidthLadder(widthPx); const showHandles = handleOpacity > 0.01 && (widthPx >= 32 || isSelected); - const showLabel = ladder === "labeled"; + const showLabel = !isAudioClip || ladder === "labeled"; const showDefaultText = !hasCustomContent && ladder === "labeled"; const startLabel = el.start.toFixed(1); const endLabel = (el.start + el.duration).toFixed(1); @@ -88,9 +90,12 @@ export const TimelineClip = memo(function TimelineClip({ } as CSSProperties; const linkColor = linkLabelColor(el.link); if (linkColor) Object.assign(themeVariables, { "--clip-link-color": linkColor }); - const isAudioClip = isAudioTimelineElement(el); const hasFades = (isAudioClip || Boolean(el.hasAudio)) && !isGestureActor; const fade = useClipFadeDraft(el); + const badges = + ladder === "labeled" && !isGestureActor ? ( + + ) : null; const clipClassName = [ "timeline-clip", "absolute", @@ -136,12 +141,18 @@ export const TimelineClip = memo(function TimelineClip({ tabIndex={isGestureActor ? undefined : tabIndex} aria-label={`${displayLabel}, ${startLabel} to ${endLabel} seconds`} aria-pressed={isGestureActor ? undefined : isSelected} + aria-keyshortcuts={isGestureActor || !capabilities.canMove ? undefined : "Space"} + aria-description={ + isGestureActor || !capabilities.canMove + ? undefined + : "Space picks up. Up and Down choose a new track. Enter drops. Escape cancels." + } className={clipClassName} style={style} title={ isComposition ? `${el.compositionSrc} • Double-click to open` - : `${displayLabel} • ${el.start.toFixed(1)}s – ${(el.start + el.duration).toFixed(1)}s` + : `${displayLabel} • ${startLabel}s – ${endLabel}s` } onPointerEnter={onHoverStart} onPointerLeave={onHoverEnd} @@ -160,7 +171,7 @@ export const TimelineClip = memo(function TimelineClip({ left: 0, top: 0, bottom: 0, - width: 14, + width: CLIP_TRIM_HIT_PX, cursor: "col-resize", zIndex: 4, }} @@ -190,7 +201,7 @@ export const TimelineClip = memo(function TimelineClip({ right: 0, top: 0, bottom: 0, - width: 14, + width: CLIP_TRIM_HIT_PX, cursor: "col-resize", zIndex: 4, }} @@ -210,8 +221,13 @@ export const TimelineClip = memo(function TimelineClip({ />
)} - {showLabel && {displayLabel}} - {showLabel && !isGestureActor && } + {showLabel && ( + + {displayLabel} + {!isAudioClip && badges} + + )} + {isAudioClip && badges} {!isGestureActor && el.syncOrigin && } {showDefaultText && ( diff --git a/packages/studio/src/player/components/TimelineClipFades.tsx b/packages/studio/src/player/components/TimelineClipFades.tsx index ee24790d0f..f82596e6fd 100644 --- a/packages/studio/src/player/components/TimelineClipFades.tsx +++ b/packages/studio/src/player/components/TimelineClipFades.tsx @@ -20,6 +20,14 @@ import { usePlayerStore, type TimelineElement } from "../store/playerStore"; import { Tooltip } from "../../components/ui"; import { useTimelineEditContextOptional } from "../../contexts/TimelineEditContext"; import { releasedOutsideWindow } from "./timelinePointerRelease"; +import { + FADE_TAB_CENTER_IN_HIT, + FADE_TAB_WIDTH, + fadeHandleBoxes, + type FadeEdge, + type FadeHandleBox, + type FadeHandleClipBox, +} from "./timelineClipFadeGeometry"; import { collectTimelineSnapTargets, snapTimelineTime, @@ -28,14 +36,9 @@ import { type TimelineSnapType, } from "./timelineSnapping"; -type FadeEdge = "in" | "out"; type FadeDraft = { edge: FadeEdge; seconds: number } | null; -const TAB_WIDTH = 4; const TAB_HEIGHT = 15; -const HANDLE_HIT = 24; -const TAB_INSET = 7; -const TAB_CENTER_IN_HIT = 8; const HANDLE_Z_ABOVE_CLIP_CONTENT = 30; const SUPPRESS_CLIP_NATIVE_TITLE = ""; /** Pixels of pointer travel before a press on the handle counts as a drag. */ @@ -102,12 +105,6 @@ function keyedFadeSeconds(key: string, shift: boolean, current: number, limit: n return FADE_KEYS[key]?.(current, shift ? 1 : 0.1, limit) ?? null; } -function topEdgeY(x: number, widthPx: number, heightPx: number, radiusPx: number): number { - const r = Math.min(radiusPx, widthPx / 2, heightPx / 2); - const d = x < r ? r - x : x > widthPx - r ? x - (widthPx - r) : 0; - return d > 0 ? r - Math.sqrt(Math.max(0, r * r - d * d)) : 0; -} - /** Slim tabs at each fade's end that drag `data-fade-in` / `data-fade-out`. */ // fallow-ignore-next-line complexity export function TimelineClipFades({ @@ -135,14 +132,29 @@ export function TimelineClipFades({ const visible = fades.fadeIn > 0 || fades.fadeOut > 0 || showHandles || dragging !== null || focused !== null; const rootRef = useRef(null); - const [clipBox, setClipBox] = useState({ height: 0, radius: 0 }); + const [clipBox, setClipBox] = useState({ + height: 0, + width: 0, + radius: 0, + toolsLeft: null, + }); useLayoutEffect(() => { - const clip = rootRef.current?.parentElement; - if (!clip) return; + const root = rootRef.current; + const clip = root?.parentElement; + if (!root || !clip) return; const radius = parseFloat(getComputedStyle(clip).borderTopLeftRadius) || 0; - const height = clip.clientHeight; + const { clientHeight: height, clientWidth: width } = root; + const fx = clip.querySelector('[data-badge="fx"]'); + const toolsLeft = fx + ? fx.getBoundingClientRect().left - root.getBoundingClientRect().left + : null; setClipBox((box) => - box.height === height && box.radius === radius ? box : { height, radius }, + box.height === height && + box.width === width && + box.radius === radius && + box.toolsLeft === toolsLeft + ? box + : { height, width, radius, toolsLeft }, ); }, [widthPx, visible]); @@ -332,39 +344,25 @@ export function TimelineClipFades({ const handlesVisible = showHandles || dragging !== null || focused !== null; if (!visible) return null; - const hitWidth = Math.min(HANDLE_HIT, widthPx / 2); - const tabX = (edge: FadeEdge) => { - const knee = edge === "in" ? inPx : widthPx - outPx; - const inset = Math.min(TAB_INSET, widthPx / 2); - return Math.min(widthPx - inset, Math.max(inset, knee)); - }; - const boxLeft = (x: number) => Math.min(widthPx - hitWidth, Math.max(0, x - hitWidth / 2)); - const [inX, outX] = [tabX("in"), tabX("out")]; - const mid = (inX + outX) / 2; // A handle with no 0.01 s step to move is not drawn, unless in use: its twin owns the spot. const drawn = (edge: FadeEdge) => currentSeconds(edge) > 0 || Math.round(limitFor(edge) * 100) >= 1 || dragging === edge || focused === edge; - const overlap = drawn("in") && drawn("out") && boxLeft(inX) + hitWidth > boxLeft(outX); - const handleGeometry = (edge: FadeEdge) => { - const x = edge === "in" ? inX : outX; - // Boxes that would overlap meet at the midpoint between the two tabs. - const [left, right] = !overlap - ? [boxLeft(x), boxLeft(x) + hitWidth] - : edge === "in" - ? [Math.max(0, mid - hitWidth), mid] - : [mid, Math.min(widthPx, mid + hitWidth)]; - const edgeY = topEdgeY(x, widthPx, clipBox.height, clipBox.radius); - return { left, width: right - left, tabLeft: x - left, top: edgeY + 1 - TAB_CENTER_IN_HIT }; - }; - const handleStyle = (geometry: { left: number; top: number; width: number }): CSSProperties => ({ + const handleBoxes = fadeHandleBoxes({ + widthPx, + inPx, + outPx, + clipBox, + drawn: { in: drawn("in"), out: drawn("out") }, + }); + const handleStyle = (geometry: FadeHandleBox): CSSProperties => ({ position: "absolute", top: geometry.top, left: geometry.left, width: geometry.width, - height: HANDLE_HIT, + height: geometry.height, cursor: "ew-resize", opacity: handlesVisible ? 1 : 0, pointerEvents: handlesVisible && canEdit ? "auto" : "none", @@ -417,7 +415,7 @@ export function TimelineClipFades({ )} {canEdit && (["in", "out"] as const).filter(drawn).map((edge) => { - const geometry = handleGeometry(edge); + const geometry = handleBoxes[edge]; return (