Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(studio): show every automated knob at the playhead (#3210)
Vance Ingalls7d38fed97fd5
diff --git a/packages/studio/src/components/StudioRightPanel.tsx b/packages/studio/src/components/StudioRightPanel.tsxindex 8ee3b9c88d..31ac169dd0 100644--- a/packages/studio/src/components/StudioRightPanel.tsx+++ b/packages/studio/src/components/StudioRightPanel.tsx@@ -327,6 +327,21 @@ export function StudioRightPanel({},[projectId, refreshFileTree, showToast],);++ /**+ * A dial being dragged writes to the preview and stops there.+ *+ * Every one of these panels previews on each pointermove and commits on+ * release. Persisting the moves too put a fragment of the drag in the undo+ * stack — and since those writes race, history could not coalesce them+ * reliably, so undo took back a sliver of the gesture rather than the gesture.+ * The release's own commit is what reaches the file and the undo stack.+ */+ const setAttributeWhileDragging = useCallback(+ (attr: string, value: string | null) =>+ handleDomAttributeLiveCommit(attr, value, undefined, { previewOnly: true }),+ [handleDomAttributeLiveCommit],+ );const handleHideAllSelected = () => {const { elements } = usePlayerStore.getState();const keys = timelineKeysForSelections(domEditGroupSelections, elements, activeCompPath);@@ -361,7 +376,7 @@ export function StudioRightPanel({onSetStyle={handleDomStyleCommit}onSetAttribute={handleDomAttributeCommit}onSetAttributes={handleDomAttributesCommit}- onSetAttributeLive={handleDomAttributeLiveCommit}+ onSetAttributeLive={setAttributeWhileDragging}onSetAttributeQuiet={handleDomAttributeQuietCommit}onApplyColorGradingScope={handleApplyColorGradingScope}onSetHtmlAttribute={handleDomHtmlAttributeCommit}diff --git a/packages/studio/src/components/TimelineToolbar.test.tsx b/packages/studio/src/components/TimelineToolbar.test.tsxindex 2e7900e826..ab07e8cd7a 100644--- a/packages/studio/src/components/TimelineToolbar.test.tsx+++ b/packages/studio/src/components/TimelineToolbar.test.tsx@@ -118,3 +118,49 @@ describe("TimelineToolbar — motion path endpoints", () => {act(() => root.unmount());});});++describe("TimelineToolbar — keyframes on audio tracks", () => {+ const clip = (tag: string) => ({+ id: "bgm",+ key: "bgm",+ tag,+ start: 0,+ duration: 10,+ track: 1,+ });++ /** A session whose selection would otherwise offer the keyframe toggle. */+ function sessionFor(tag: string) {+ usePlayerStore.setState({ elements: [clip(tag)], selectedElementId: "bgm", currentTime: 1 });+ const element = document.createElement(tag);+ element.id = "bgm";+ return {+ domEditSelection: makeSelection("Element", element),+ selectedGsapAnimations: [],+ handleGsapAddAnimation: vi.fn(),+ handleGsapConvertToKeyframes: vi.fn(),+ handleGsapRemoveKeyframe: vi.fn(),+ } satisfies NonNullable<React.ComponentProps<typeof TimelineToolbar>["domEditSession"]>;+ }++ it("offers no keyframe toggle for an audio clip", () => {+ // An audio clip has no box on the canvas, so there is nothing to move or fade —+ // and pressing this seeded a tween from the position properties, which put a+ // position lane on a track that has no position. Audio is automated instead.+ const { host, root } = renderToolbar(sessionFor("audio"));+ const button = host.querySelector<HTMLButtonElement>(+ 'button[aria-label="Add keyframe at playhead"]',+ );+ expect(button?.disabled).toBe(true);+ act(() => root.unmount());+ });++ it("still offers it for a visual clip", () => {+ const { host, root } = renderToolbar(sessionFor("div"));+ const button = host.querySelector<HTMLButtonElement>(+ 'button[aria-label="Add keyframe at playhead"]',+ );+ expect(button?.disabled).toBe(false);+ act(() => root.unmount());+ });+});diff --git a/packages/studio/src/components/TimelineToolbar.tsx b/packages/studio/src/components/TimelineToolbar.tsxindex 1417665071..12cde02a6c 100644--- a/packages/studio/src/components/TimelineToolbar.tsx+++ b/packages/studio/src/components/TimelineToolbar.tsx@@ -86,8 +86,22 @@ function resolveKeyframeToggleState(};}+/**+ * Can this element be keyframed at all?+ *+ * An audio clip cannot. It has no box on the canvas, so there is nothing to move,+ * scale or fade — and "add a keyframe" on one seeds a tween from the position+ * properties, which produced a position lane on a track that has no position. Audio+ * is automated instead: volume and effect parameters, on their own lanes.+ */+function isKeyframeable(element: TimelineElement | undefined): boolean {+ return element?.tag !== "audio";+}+function useKeyframeToggle(session?: DomEditSessionSlice) {const currentTime = usePlayerStore((s) => s.currentTime);+ const selectedElementId = usePlayerStore((s) => s.selectedElementId);+ const elements = usePlayerStore((s) => s.elements);const sessionRef = useRef(session);sessionRef.current = session;@@ -95,6 +109,9 @@ function useKeyframeToggle(session?: DomEditSessionSlice) {sessionRef as React.RefObject<EnableKeyframesSession | undefined>,);+ const selected = elements.find((element) => (element.key ?? element.id) === selectedElementId);+ if (!isKeyframeable(selected)) return { ...NO_KEYFRAME_TOGGLE, onToggle: undefined };+const toggleState = resolveKeyframeToggleState(session, currentTime);return {diff --git a/packages/studio/src/components/editor/PropertyPanel.tsx b/packages/studio/src/components/editor/PropertyPanel.tsxindex 7308aca237..9b14d83a6d 100644--- a/packages/studio/src/components/editor/PropertyPanel.tsx+++ b/packages/studio/src/components/editor/PropertyPanel.tsx@@ -1,5 +1,5 @@import { scopedElementKey } from "../../hooks/gsapKeyframeCacheHelpers";-import { memo, useEffect, useMemo, useRef, useState } from "react";+import { memo, useMemo, useRef, useState } from "react";import { Move } from "../../icons/SystemIcons";import { InspectorHeaderActions } from "./InspectorHeaderActions";import { useStudioShellContext } from "../../contexts/StudioContext";@@ -29,7 +29,8 @@ import { KeyframeNavigation } from "./KeyframeNavigation";import { STUDIO_FLAT_INSPECTOR_ENABLED } from "./manualEditingAvailability";import { PropertyPanelFlat } from "./PropertyPanelFlat";import { createGsapLivePreview } from "./gsapLivePreview";-import { usePlayerStore, liveTime } from "../../player";+import { usePlayerStore } from "../../player";+import { useLivePlayheadTime } from "../../hooks/useLivePlayheadTime";import { TimingSection } from "./propertyPanelTimingSection";import { type PropertyPanelProps } from "./propertyPanelHelpers";import { GestureRecordPanelButton } from "./GestureRecordControl";@@ -114,31 +115,14 @@ export const PropertyPanel = memo(function PropertyPanel(props: PropertyPanelProconst { showToast } = useStudioShellContext();const [clipboardCopied, setClipboardCopied] = useState(false);const clipboardTimerRef = useRef<ReturnType<typeof setTimeout>>(undefined);- const storeTime = usePlayerStore((s) => s.currentTime);- const isPlaying = usePlayerStore((s) => s.isPlaying);const timelineElements = usePlayerStore((s) => s.elements);const selectedElementId = usePlayerStore((s) => s.selectedElementId);const selectedElementHidden = isSelectedElementHidden(timelineElements, selectedElementId);const visibilityToggleLabel = selectedElementHidden ? "Show element" : "Hide element";- const liveTimeRef = useRef(storeTime);- const [, forceRender] = useState(0);- useEffect(() => {- if (!isPlaying) return;- let timerId: ReturnType<typeof setTimeout> | 0 = 0;- const unsub = liveTime.subscribe((t) => {- liveTimeRef.current = t;- if (!timerId)- timerId = setTimeout(() => {- timerId = 0;- forceRender((v) => v + 1);- }, 33);- });- return () => {- unsub();- if (timerId) clearTimeout(timerId);- };- }, [isPlaying]);- const currentTime = isPlaying ? liveTimeRef.current : storeTime;+ // Live during playback, the store's when paused — see the hook. Shared with the+ // audio FX panel, which follows the playhead for the same reason: a value the+ // timeline drives has to be shown moving, not frozen at what the attribute says.+ const currentTime = useLivePlayheadTime();const cacheElementKey = element?.id ?? element?.selector ?? "";const cacheEntry = usePlayerStore((s) => s.keyframeCache.get(cacheElementKey));diff --git a/packages/studio/src/components/editor/PropertyPanelFlat.tsx b/packages/studio/src/components/editor/PropertyPanelFlat.tsxindex 59e2a92c8f..32b1aeaabe 100644--- a/packages/studio/src/components/editor/PropertyPanelFlat.tsx+++ b/packages/studio/src/components/editor/PropertyPanelFlat.tsx@@ -6,6 +6,7 @@ import { slugifyDesignInput } from "../../utils/designInputTracking";import { isTextEditableSelection } from "./domEditing";import type { PropertyPanelFlatProps } from "./propertyPanelFlatProps";import { formatPxMetricValue } from "./propertyPanelHelpers";+import { audioFxSummary } from "./audioFxSummary";import { PropertyPanelFlatHeader } from "./PropertyPanelFlatHeader";import { PropertyPanelFlatFooter } from "./PropertyPanelFlatFooter";import { FlatGroupHeader } from "./propertyPanelFlatPrimitives";@@ -14,8 +15,7 @@ import { FlatStyleSection } from "./propertyPanelFlatStyleSections";import { FlatLayoutSection } from "./propertyPanelFlatLayoutSection";import { FlatMotionSection } from "./propertyPanelFlatMotionSection";import { isCanaryEnabled } from "../../telemetry/canary";-import { audioFxSummary } from "./audioFxSummary";-import { AudioFxGroup } from "./propertyPanelAudioFxGroup";+import { AudioFxGroup } from "./propertyPanelAudioFxGroup.js";import { useVolumeAutomation } from "./useVolumeAutomation";import { FlatMediaSection } from "./propertyPanelFlatMediaSection";import { deriveElementTiming } from "./propertyPanelFlatTimingDerivation";diff --git a/packages/studio/src/components/editor/audioFxSummary.test.ts b/packages/studio/src/components/editor/audioFxSummary.test.tsnew file mode 100644index 0000000000..5ba7a87a5a--- /dev/null+++ b/packages/studio/src/components/editor/audioFxSummary.test.ts@@ -0,0 +1,75 @@+import { describe, expect, it } from "vitest";+import { audioFxSummary } from "./audioFxSummary";+import type { DomEditSelection } from "./domEditingTypes";++const el = (dataAttributes: Record<string, string>): DomEditSelection =>+ ({ dataAttributes }) as unknown as DomEditSelection;++const chain = (nodes: unknown[]) => JSON.stringify({ version: 1, nodes });++describe("audioFxSummary", () => {+ it("counts a carve as one module, not as the filters behind it", () => {+ // Six bands and a level stage reading "7 effects" is the misreading the+ // grouping exists to prevent.+ const summary = audioFxSummary(+ el({+ "fx-chain": chain([+ { type: "peaking", id: "n1", fromCarve: true, params: { frequency: 400 } },+ { type: "peaking", id: "n2", fromCarve: true, params: { frequency: 1600 } },+ { type: "gain", id: "n3", fromCarve: true, params: { gain: -6 } },+ ]),+ "fx-carve": JSON.stringify({ source: "vo", strength: 0.25 }),+ }),+ );+ expect(summary).toBe("carve");+ });++ it("counts hand-built effects alongside the module", () => {+ expect(+ audioFxSummary(+ el({+ "fx-chain": chain([+ { type: "peaking", id: "n1", fromCarve: true, params: { frequency: 400 } },+ { type: "lowpass", id: "n2", params: { frequency: 8000 } },+ { type: "delay", id: "n3", params: { time: 200 } },+ ]),+ }),+ ),+ ).toBe("2 effects + carve");+ });++ it("says how many when there is no carve", () => {+ expect(audioFxSummary(el({ "fx-chain": chain([{ type: "lowpass", id: "n1" }]) }))).toBe(+ "1 effect",+ );+ });++ it("names a carve that is on but has not compiled to filters yet", () => {+ // Switching it on with no voice chosen leaves the control in this section with+ // nothing behind it; the summary should still say the section holds one.+ expect(audioFxSummary(el({ "fx-carve": JSON.stringify({ source: "", strength: 0.25 }) }))).toBe(+ "carve",+ );+ });++ it("ignores bypassed effects, as it always did", () => {+ expect(+ audioFxSummary(+ el({+ "fx-chain": chain([+ { type: "lowpass", id: "n1", enabled: false },+ { type: "delay", id: "n2" },+ ]),+ }),+ ),+ ).toBe("1 effect");+ });++ it("says none for a track with neither", () => {+ expect(audioFxSummary(el({}))).toBe("none");+ });++ it("says so when the chain cannot be read", () => {+ expect(audioFxSummary(el({ "fx-chain": "{not json" }))).toBe("unreadable");+ });+});diff --git a/packages/studio/src/components/editor/audioFxSummary.ts b/packages/studio/src/components/editor/audioFxSummary.tsindex 9accb8cfad..441217a8ab 100644--- a/packages/studio/src/components/editor/audioFxSummary.ts+++ b/packages/studio/src/components/editor/audioFxSummary.ts@@ -1,27 +1,36 @@/*** What the collapsed Audio FX group says it holds.*- * Its own module because `PropertyPanelFlat.tsx` is at the repo's 600-line- * budget, and this is the piece with no dependency on the panel around it.+ * It has to describe the rack the author would see on opening it, which counts a+ * carve as one module rather than as the filters it compiles to. Six peaking+ * bands and a level stage reading "7 effects" invited exactly the misreading the+ * grouping exists to prevent — that they are seven things to manage.*/import { parseAudioFxChain } from "@hyperframes/core/audio-fx";-import type { DomEditSelection } from "./domEditing";+import type { DomEditSelection } from "./domEditingTypes";-/** Chain length at a glance, so the collapsed group says whether anything is on. */export function audioFxSummary(element: DomEditSelection): string {const raw = element.dataAttributes?.["fx-chain"];- const carve = element.dataAttributes?.["fx-carve"];- let count = 0;+ const carveAttr = element.dataAttributes?.["fx-carve"];+ let handBuilt = 0;+ let carveNodes = 0;if (raw) {try {- count = parseAudioFxChain(raw).nodes.filter((n) => n.enabled !== false).length;+ for (const node of parseAudioFxChain(raw).nodes) {+ if (node.enabled === false) continue;+ if (node.fromCarve) carveNodes += 1;+ else handBuilt += 1;+ }} catch {return "unreadable";}}const parts: string[] = [];- if (count > 0) parts.push(`${count} effect${count === 1 ? "" : "s"}`);- if (carve) parts.push("carve");+ if (handBuilt > 0) parts.push(`${handBuilt} effect${handBuilt === 1 ? "" : "s"}`);+ // One name for the module however many filters are behind it. Named when the+ // carve is switched on at all, because the control is in this section whether or+ // not it has compiled to anything yet.+ if (carveNodes > 0 || carveAttr) parts.push("carve");return parts.length > 0 ? parts.join(" + ") : "none";}diff --git a/packages/studio/src/components/editor/propertyPanelAudioFxGroup.test.tsx b/packages/studio/src/components/editor/propertyPanelAudioFxGroup.test.tsxindex e176af0cf3..f9cad3b146 100644--- a/packages/studio/src/components/editor/propertyPanelAudioFxGroup.test.tsx+++ b/packages/studio/src/components/editor/propertyPanelAudioFxGroup.test.tsx@@ -4,6 +4,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { createRoot } from "react-dom/client";import { AudioFxGroup } from "./propertyPanelAudioFxGroup.js";import type { DomEditSelection } from "./domEditingTypes";+import { liveTime, usePlayerStore } from "../../player";(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -174,13 +175,7 @@ describe("AudioFxGroup carve", () => {],});- const carveOn = JSON.stringify({- source: "vo",- maxCutDb: 6,- bands: 3,- q: 1.4,- intelligibilityBias: 0.7,- });+ const carveOn = JSON.stringify({ source: "vo", strength: 0.5, dynamic: false });const carveToggle = (host: HTMLElement): HTMLButtonElement => {const block = host.querySelector(".hf-fx-carve")!;@@ -232,7 +227,8 @@ describe("AudioFxGroup carve", () => {act(() => {// React's value tracker swallows a plain assignment, so go through the// prototype setter the way the other panel tests do.- Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(dial, "0.5");+ // A different value than the carve holds; setting the same one is not a change.+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(dial, "0.8");dial?.dispatchEvent(new Event("input", { bubbles: true }));});expect(onSetAttributeLive.mock.calls.map((c) => c[0])).toEqual(["data-fx-carve"]);@@ -250,6 +246,372 @@ describe("AudioFxGroup carve", () => {});});+describe("AudioFxGroup dynamic carve", () => {+ const carvedChain = JSON.stringify({+ version: 1,+ nodes: [{ type: "lowpass", id: "n1", params: { frequency: 400, q: 0.9, poles: "2" } }],+ });+ // Strength 0 carves frequencies only — no level ducking — so the spectral+ // cases measure just the spectral half. A case that wants the duck raises it.+ const settings = (dynamic: boolean, over: Record<string, unknown> = {}) =>+ JSON.stringify({ source: "vo", strength: 0, dynamic, ...over });++ /** The value written for one attribute, whatever order the writes landed in. */+ const writeFor = (calls: unknown[][], attr: string) =>+ JSON.parse(String(calls.find((c) => c[0] === attr)![1]));++ /** Choose a voice track the way the select does. */+ const pickSource = (host: HTMLElement, id: string) => {+ const select = host.querySelector<HTMLSelectElement>(".hf-fx-carve select")!;+ Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, "value")?.set?.call(select, id);+ select.dispatchEvent(new Event("change", { bubbles: true }));+ };++ const dynamicBox = (host: HTMLElement) =>+ host.querySelector<HTMLInputElement>(".hf-fx-carve-dynamic")!;++ /** A voice with a pause in it, decoded through a stubbed offline context. */+ function stubDecode(): void {+ const sampleRate = 48000;+ const data = new Float32Array(sampleRate * 4);+ for (let i = 0; i < data.length; i++) {+ const t = i / sampleRate;+ data[i] = t > 1 && t < 3 ? 0.7 * Math.sin(2 * Math.PI * 1000 * t) : 0;+ }+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => ({ arrayBuffer: async () => new ArrayBuffer(8) })),+ );+ vi.stubGlobal(+ "OfflineAudioContext",+ class {+ decodeAudioData = async () => ({ sampleRate, getChannelData: () => data });+ },+ );+ }++ afterEach(() => vi.unstubAllGlobals());++ it("records the choice in the carve settings", () => {+ const { host, onSetAttributeQuiet } = mount({+ "fx-chain": carvedChain,+ "fx-carve": settings(false),+ });+ act(() => dynamicBox(host).click());+ const write = onSetAttributeQuiet.mock.calls.find((c) => c[0] === "data-fx-carve");+ expect(JSON.parse(String(write![1])).dynamic).toBe(true);+ });++ it("automates the carve filters' gain from the voice, in the bed's own time", async () => {+ stubDecode();+ // Voice starts 10s into the composition, bed at 0: the envelope is measured+ // against the voice but read from the start of the bed, so it has to shift.+ const { host, onSetAttributeQuiet } = mount({+ "fx-chain": carvedChain,+ // No source yet: picking one is what applies the carve.+ "fx-carve": settings(true, { source: "" }),+ start: "0",+ });+ const vo = document.getElementById("vo")!;+ vo.setAttribute("data-start", "10");+ vo.setAttribute("src", "voice.wav");+ await act(async () => {+ pickSource(host, "vo");+ });++ // Chain first, then automation: a lane naming a node the chain does not+ // carry yet is dropped when it is read back.+ const order = onSetAttributeQuiet.mock.calls.map((c) => c[0]);+ // The settings land first, then the filters they imply, then the envelopes.+ expect(order.indexOf("data-fx-chain")).toBeLessThan(order.indexOf("data-automation"));++ const carved = writeFor(onSetAttributeQuiet.mock.calls, "data-fx-chain").nodes;+ const carveNode = carved.find((n: { fromCarve?: boolean }) => n.fromCarve);+ expect(carveNode.id).toBeTruthy();++ const lanes = writeFor(onSetAttributeQuiet.mock.calls, "data-automation").lanes;+ const lane = lanes.find((l: { target: string }) => l.target === `fx.${carveNode.id}.gain`) as {+ points: { t: number; v: number }[];+ };+ expect(lane).toBeTruthy();+ // Flat at the bed's own start, before the voice exists at all.+ expect(lane.points[0]).toMatchObject({ t: 0, v: 0 });+ // The voice's pause is at 0-1s of its own clip, so 10-11s of the bed's.+ expect(lane.points.find((p) => p.t > 10.5 && p.t < 11)?.v ?? 0).toBe(0);+ // And it cuts once the voice speaks, a second later. Depth is per band and+ // relative to that band's own peak in the voice, so the invariant is that the+ // envelope gets most of the way to what the analysis put on the node — not a+ // fixed number of dB, which changes with the band the analysis chose.+ const bandGain = Number(carveNode.params?.gain ?? 0);+ // At least half the depth the analysis put on the node; the exact floor+ // depends on which band it chose and how the envelope was thinned.+ expect(Math.min(...lane.points.map((p) => p.v))).toBeLessThanOrEqual(bandGain * 0.5);+ // Ends back at no cut, so the bed is not left dipped for the rest of the clip.+ expect(lane.points.at(-1)!.v).toBe(0);+ });++ it("adds a gain stage that ducks the bed under the voice, automated when dynamic", async () => {+ // Carving frequencies cannot beat a bed that is simply louder than the+ // voice. The level half rides a gain node the carve owns, so the track's own+ // volume lane is left alone.+ stubDecode();+ const { host, onSetAttributeQuiet } = mount({+ "fx-chain": carvedChain,+ "fx-carve": settings(true, { strength: 1, source: "" }),+ start: "0",+ });+ const vo = document.getElementById("vo")!;+ vo.setAttribute("data-start", "0");+ vo.setAttribute("src", "voice.wav");+ // The bed is measured too — "how far over the voice is it" needs both.+ document.getElementById("bed")!.setAttribute("src", "bed.m4a");+ await act(async () => {+ pickSource(host, "vo");+ });++ const nodes = writeFor(onSetAttributeQuiet.mock.calls, "data-fx-chain").nodes;+ const gain = nodes.find((n: { type: string }) => n.type === "gain");+ expect(gain).toBeTruthy();+ expect(gain.fromCarve).toBe(true);+ // Dynamic hands the value to the envelope, so the static one stays at unity.+ expect(gain.params.gain).toBe(0);++ const lanes = writeFor(onSetAttributeQuiet.mock.calls, "data-automation").lanes;+ const duckLane = lanes.find((l: { target: string }) => l.target === `fx.${gain.id}.gain`);+ expect(duckLane).toBeTruthy();+ expect(Math.min(...duckLane.points.map((p: { v: number }) => p.v))).toBeLessThan(0);+ // Every carved band gets an envelope reaching that band's own analysed depth.+ for (const node of nodes.filter((n: { type: string }) => n.type === "peaking")) {+ const lane = lanes.find((l: { target: string }) => l.target === `fx.${node.id}.gain`) as+ | { points: { v: number }[] }+ | undefined;+ expect(lane, `band ${node.id} has no envelope`).toBeTruthy();+ const deepest = Math.min(...lane!.points.map((p) => p.v));+ expect(deepest).toBeLessThanOrEqual(0);+ expect(deepest).toBeGreaterThanOrEqual(node.params.gain - 0.2);+ expect(deepest).toBeLessThanOrEqual(node.params.gain * 0.5);+ }+ // The author's own volume lane is not something a carve gets to touch.+ expect(lanes.some((l: { target: string }) => l.target === "volume")).toBe(false);+ });++ it("holds one measured value when the carve is not dynamic", async () => {+ stubDecode();+ const { host, onSetAttributeQuiet } = mount({+ "fx-chain": carvedChain,+ "fx-carve": settings(false, { strength: 1, source: "" }),+ start: "0",+ });+ const vo = document.getElementById("vo")!;+ vo.setAttribute("data-start", "0");+ vo.setAttribute("src", "voice.wav");+ // The bed is measured too — "how far over the voice is it" needs both.+ document.getElementById("bed")!.setAttribute("src", "bed.m4a");+ await act(async () => {+ pickSource(host, "vo");+ });+ const nodes = writeFor(onSetAttributeQuiet.mock.calls, "data-fx-chain").nodes;+ const gain = nodes.find((n: { type: string }) => n.type === "gain");+ expect(gain.params.gain).toBeLessThan(0);+ // Nothing to schedule: a static carve is a value, not an envelope.+ expect(onSetAttributeQuiet.mock.calls.some((c) => c[0] === "data-automation")).toBe(false);+ });++ it("carves frequencies only when the duck is off", async () => {+ stubDecode();+ const { host, onSetAttributeQuiet } = mount({+ "fx-chain": carvedChain,+ "fx-carve": settings(true, { strength: 0, source: "" }),+ start: "0",+ });+ document.getElementById("vo")!.setAttribute("src", "voice.wav");+ document.getElementById("bed")!.setAttribute("src", "bed.m4a");+ await act(async () => {+ pickSource(host, "vo");+ });+ const nodes = writeFor(onSetAttributeQuiet.mock.calls, "data-fx-chain").nodes;+ expect(nodes.some((n: { type: string }) => n.type === "gain")).toBe(false);+ });++ it("applies as soon as a voice track is picked, with no second step", async () => {+ // A carve with a source and no filters is a setting nobody applied. Choosing+ // the voice is the whole gesture.+ stubDecode();+ const { host, onSetAttributeQuiet } = mount({+ "fx-chain": JSON.stringify({ version: 1, nodes: [] }),+ "fx-carve": JSON.stringify({ source: "", strength: 0.25, dynamic: true }),+ start: "0",+ });+ document.getElementById("vo")!.setAttribute("src", "voice.wav");+ document.getElementById("bed")!.setAttribute("src", "bed.m4a");+ await act(async () => {+ pickSource(host, "vo");+ });+ const written = onSetAttributeQuiet.mock.calls.map((c) => c[0]);+ expect(written).toEqual(["data-fx-carve", "data-fx-chain", "data-automation"]);+ const nodes = JSON.parse(+ String(onSetAttributeQuiet.mock.calls.find((c) => c[0] === "data-fx-chain")![1]),+ ).nodes;+ expect(nodes.every((n: { fromCarve?: boolean }) => n.fromCarve)).toBe(true);+ });++ it("re-applies when dynamic is switched on, not just when strength moves", async () => {+ stubDecode();+ const carvedAlready = JSON.stringify({+ version: 1,+ nodes: [+ {+ type: "peaking",+ id: "n1",+ fromCarve: true,+ params: { frequency: 1000, gain: -6, q: 1.4 },+ },+ ],+ });+ const { host, onSetAttributeQuiet } = mount({+ "fx-chain": carvedAlready,+ "fx-carve": settings(false, { strength: 0.25 }),+ start: "0",+ });+ document.getElementById("vo")!.setAttribute("src", "voice.wav");+ document.getElementById("bed")!.setAttribute("src", "bed.m4a");+ await act(async () => {+ host.querySelector<HTMLInputElement>(".hf-fx-carve-dynamic")!.click();+ });+ // Static and dynamic are different chains, so the switch has to rebuild them.+ expect(onSetAttributeQuiet.mock.calls.some((c) => c[0] === "data-fx-chain")).toBe(true);+ });++ it("re-applies an existing carve when strength moves", async () => {+ // Strength is the whole control surface, so it has to act on what is already+ // applied. Left to the button alone, a carve kept the filters and envelopes+ // its old strength produced and the knob silently described nothing.+ stubDecode();+ const carvedAlready = JSON.stringify({+ version: 1,+ nodes: [+ {+ type: "peaking",+ id: "n1",+ fromCarve: true,+ params: { frequency: 1000, gain: -6, q: 1.4 },+ },+ { type: "gain", id: "n2", fromCarve: true, params: { gain: -6 } },+ ],+ });+ const { host, onSetAttributeQuiet } = mount({+ "fx-chain": carvedAlready,+ "fx-carve": settings(true, { strength: 0.25 }),+ start: "0",+ });+ document.getElementById("vo")!.setAttribute("src", "voice.wav");+ document.getElementById("bed")!.setAttribute("src", "bed.m4a");++ const dial = host.querySelector<HTMLInputElement>(".hf-fx-carve input[type=range]")!;+ await act(async () => {+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(dial, "1");+ dial.dispatchEvent(new Event("input", { bubbles: true }));+ dial.dispatchEvent(new PointerEvent("pointerup", { bubbles: true }));+ });++ const written = onSetAttributeQuiet.mock.calls.map((c) => c[0]);+ expect(written).toContain("data-fx-carve");+ // The settings land first, then the filters they imply, then the envelopes.+ expect(written.indexOf("data-fx-carve")).toBeLessThan(written.indexOf("data-fx-chain"));+ expect(written.indexOf("data-fx-chain")).toBeLessThan(written.indexOf("data-automation"));++ const chainWrite = onSetAttributeQuiet.mock.calls.find((c) => c[0] === "data-fx-chain");+ const nodes = JSON.parse(String(chainWrite![1])).nodes;+ // Full strength: deeper than the 6 dB the quarter-strength carve had.+ const deepest = Math.min(+ ...nodes+ .filter((n: { type: string }) => n.type === "peaking")+ .map((n: { params: { gain: number } }) => n.params.gain),+ );+ expect(deepest).toBeLessThan(-6);+ });++ it("does nothing but record the setting while no voice track is chosen", async () => {+ // There is nothing to listen to, so there is nothing to derive. This is the+ // one case that only writes the setting now that the apply button is gone.+ stubDecode();+ const { host, onSetAttributeQuiet } = mount({+ "fx-chain": JSON.stringify({ version: 1, nodes: [] }),+ "fx-carve": settings(true, { strength: 0.25, source: "" }),+ start: "0",+ });+ const dial = host.querySelector<HTMLInputElement>(".hf-fx-carve input[type=range]")!;+ await act(async () => {+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(dial, "1");+ dial.dispatchEvent(new Event("input", { bubbles: true }));+ dial.dispatchEvent(new PointerEvent("pointerup", { bubbles: true }));+ });+ expect(onSetAttributeQuiet.mock.calls.map((c) => c[0])).toEqual(["data-fx-carve"]);+ });++ it("does not re-analyse on every pixel of a drag", async () => {+ // Only the release re-applies. Analysing per pointermove would decode both+ // tracks on each pixel.+ stubDecode();+ const carvedAlready = JSON.stringify({+ version: 1,+ nodes: [+ {+ type: "peaking",+ id: "n1",+ fromCarve: true,+ params: { frequency: 1000, gain: -6, q: 1.4 },+ },+ ],+ });+ const { host, onSetAttributeQuiet, onSetAttributeLive } = mount({+ "fx-chain": carvedAlready,+ "fx-carve": settings(true, { strength: 0.25 }),+ start: "0",+ });+ document.getElementById("vo")!.setAttribute("src", "voice.wav");+ const dial = host.querySelector<HTMLInputElement>(".hf-fx-carve input[type=range]")!;+ await act(async () => {+ for (const v of ["0.4", "0.6", "0.8"]) {+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(dial, v);+ dial.dispatchEvent(new Event("input", { bubbles: true }));+ }+ });+ expect(onSetAttributeLive.mock.calls.every((c) => c[0] === "data-fx-carve")).toBe(true);+ expect(onSetAttributeQuiet.mock.calls.some((c) => c[0] === "data-fx-chain")).toBe(false);+ });++ it("drops the envelopes when dynamic is switched back off", async () => {+ // An automated gain ignores the panel's depth, so leaving the lanes behind+ // would keep the filters following a voice with nothing saying they do.+ const automation = JSON.stringify({+ version: 1,+ lanes: [+ { target: "fx.n2.gain", points: [{ t: 0, v: 0 }] },+ { target: "volume", points: [{ t: 0, v: 1 }] },+ ],+ });+ const withCarveNode = JSON.stringify({+ version: 1,+ nodes: [+ { type: "peaking", id: "n2", fromCarve: true, params: { frequency: 1000, gain: -6 } },+ ],+ });+ const { host, onSetAttributeQuiet } = mount({+ "fx-chain": withCarveNode,+ "fx-carve": settings(true),+ automation,+ });+ await act(async () => {+ dynamicBox(host).click();+ });+ const write = onSetAttributeQuiet.mock.calls.find((c) => c[0] === "data-automation");+ expect(write).toBeTruthy();+ const lanes = JSON.parse(String(write![1])).lanes;+ expect(lanes.map((l: { target: string }) => l.target)).toEqual(["volume"]);+ });+});+describe("AudioFxGroup successive edits", () => {const three = JSON.stringify({version: 1,@@ -298,6 +660,72 @@ describe("AudioFxGroup successive edits", () => {});describe("AudioFxGroup carve visibility", () => {+ /**+ * A carve is a relationship: a bed is carved *against* a voice. The voice is the+ * other end of it, so offering the same control there is offering to carve a+ * track against itself by proxy — and switching it on left a setting that could+ * never do anything.+ */+ it("does not offer carve on a track another track is carving against", () => {+ const bed = document.createElement("audio");+ bed.id = "bed";+ bed.setAttribute("src", "bed.m4a");+ bed.setAttribute("data-fx-carve", JSON.stringify({ source: "vo", strength: 0.25 }));+ document.body.append(bed);+ const voice = document.createElement("audio");+ voice.id = "vo";+ voice.setAttribute("src", "voice.wav");+ document.body.append(voice);++ const host = document.createElement("div");+ document.body.append(host);+ const selection = {+ dataAttributes: {},+ id: "vo",+ element: voice,+ } as unknown as DomEditSelection;+ act(() => {+ createRoot(host).render(+ <AudioFxGroup+ element={selection}+ onSetAttributeQuiet={vi.fn()}+ onSetAttributeLive={vi.fn()}+ />,+ );+ });+ expect(host.querySelector(".hf-fx-carve")).toBeNull();+ });++ it("still offers it on the bed doing the carving", () => {+ const bed = document.createElement("audio");+ bed.id = "bed";+ bed.setAttribute("src", "bed.m4a");+ bed.setAttribute("data-fx-carve", JSON.stringify({ source: "vo", strength: 0.25 }));+ document.body.append(bed);+ const voice = document.createElement("audio");+ voice.id = "vo";+ voice.setAttribute("src", "voice.wav");+ document.body.append(voice);++ const host = document.createElement("div");+ document.body.append(host);+ const selection = {+ dataAttributes: { "fx-carve": JSON.stringify({ source: "vo", strength: 0.25 }) },+ id: "bed",+ element: bed,+ } as unknown as DomEditSelection;+ act(() => {+ createRoot(host).render(+ <AudioFxGroup+ element={selection}+ onSetAttributeQuiet={vi.fn()}+ onSetAttributeLive={vi.fn()}+ />,+ );+ });+ expect(host.querySelector(".hf-fx-carve")).not.toBeNull();+ });+it("offers carve when the composition holds another audio track", () => {const { host } = mount({ "fx-chain": CHAIN });expect(host.querySelector(".hf-fx-carve")).toBeTruthy();@@ -356,3 +784,188 @@ describe("AudioFxGroup deleting an effect", () => {expect(onSetAttributeQuiet.mock.calls.some((c) => c[0] === "data-automation")).toBe(false);});});++describe("AudioFxGroup carve module readouts", () => {+ /**+ * A carve on a bed running 0–10 s, with a lane that ramps its 400 Hz band from+ * no cut to −6 dB across the first five seconds. The stored gain is −1, which is+ * deliberately not a value the lane ever passes through: it stands in for the+ * seed a lane leaves behind, so a readout showing it can only mean the playhead+ * was not consulted.+ */+ const carved = {+ start: "0",+ duration: "10",+ "fx-chain": JSON.stringify({+ version: 1,+ nodes: [+ {+ type: "peaking",+ id: "n1",+ fromCarve: true,+ params: { frequency: 400, gain: -1, q: 1.4 },+ },+ ],+ }),+ automation: JSON.stringify({+ version: 1,+ lanes: [+ {+ target: "fx.n1.gain",+ points: [+ { t: 0, v: 0 },+ { t: 5, v: -6 },+ ],+ },+ ],+ }),+ "fx-carve": JSON.stringify({ source: "vo", strength: 0.25, dynamic: true }),+ };++ /** Park the playhead somewhere, paused — a scrub is the same question as playback. */+ const seek = (time: number) => {+ act(() => {+ usePlayerStore.setState({ currentTime: time, isPlaying: false });+ });+ };++ const gainReadout = (host: HTMLElement): HTMLElement | null => {+ for (const span of Array.from(host.querySelectorAll<HTMLElement>(".hf-fx-carve-member span"))) {+ if (span.textContent?.startsWith("Gain")) return span;+ }+ return null;+ };++ const openModule = (host: HTMLElement) => {+ const head = host.querySelector<HTMLButtonElement>(".hf-fx-carve-module .hf-fx-node-name");+ act(() => head?.click());+ };++ afterEach(() => {+ usePlayerStore.setState({ currentTime: 0, isPlaying: false });+ });++ it("shows the envelope's value at the playhead, not the stored seed", () => {+ seek(2.5);+ const { host } = mount(carved);+ openModule(host);+ const gain = gainReadout(host);+ // Halfway along a 0 → −6 dB ramp.+ expect(gain?.textContent).toContain("-3 dB");+ expect(gain?.hasAttribute("data-automation-live")).toBe(true);+ });++ it("follows the playhead as it moves", () => {+ seek(0);+ const { host } = mount(carved);+ openModule(host);+ expect(gainReadout(host)?.textContent).toContain("0 dB");+ seek(5);+ expect(gainReadout(host)?.textContent).toContain("-6 dB");+ seek(1);+ expect(gainReadout(host)?.textContent).toContain("-1.2 dB");+ });++ it("follows the transport during playback, off the live-time channel", async () => {+ // The RAF loop deliberately keeps every frame out of the store — it notifies+ // `liveTime` instead — so a panel that only watched the store would sit still+ // for the whole take and then jump when playback stopped.+ seek(0);+ const { host } = mount(carved);+ openModule(host);+ act(() => {+ usePlayerStore.setState({ isPlaying: true });+ });+ act(() => liveTime.notify(4));+ // Throttled to 30 Hz rather than rendered per frame, so the readout lands on+ // the next tick and not in this one.+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 60));+ });+ expect(gainReadout(host)?.textContent).toContain("-4.8 dB");++ act(() => liveTime.notify(5));+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 60));+ });+ expect(gainReadout(host)?.textContent).toContain("-6 dB");+ });++ it("reserves the same width whatever the value reads", () => {+ // The readout updates 30 times a second while the transport runs, and a value+ // one character narrower shunts everything after it sideways. So the width comes+ // from what the parameter CAN read, not from what it currently does.+ seek(2.5);+ const { host } = mount(carved);+ openModule(host);+ const widthAt = (): string | undefined =>+ gainReadout(host)?.querySelector<HTMLElement>(".tabular-nums")?.style.minWidth;+ const narrow = widthAt();+ expect(narrow).toBe("8ch"); // -40..40 dB at one decimal: "-12.5 dB"+ seek(5); // -6 dB — two characters shorter than -3 dB was+ expect(gainReadout(host)?.textContent).toContain("-6 dB");+ expect(widthAt()).toBe(narrow);+ });++ it("moves a hand-built effect's own slider and number, not just the carve rack", () => {+ // Every automated value follows its lane, whatever put the effect there. This+ // one is a delay the author added and automated by hand: its control is locked+ // (the lane owns the value), so the fader has no drag to fight and can simply+ // show the truth.+ const { host } = mount({+ start: "0",+ duration: "10",+ "fx-chain": JSON.stringify({+ version: 1,+ nodes: [{ type: "delay", id: "n1", params: { time: 250, feedback: 0.35, mix: 0.4 } }],+ }),+ automation: JSON.stringify({+ version: 1,+ lanes: [+ {+ target: "fx.n1.mix",+ points: [+ { t: 0, v: 0 },+ { t: 4, v: 1 },+ ],+ },+ ],+ }),+ });+ const mixRow = rowFor(host, "Mix");+ const number = mixRow?.querySelector<HTMLInputElement>(".hf-fx-number");+ const slider = mixRow?.querySelector<HTMLInputElement>(".hf-fx-slider");+ expect(number?.disabled).toBe(true); // the lane owns it++ seek(1); // a quarter along a 0 → 1 ramp+ expect(Number(number?.value)).toBeCloseTo(0.25, 2);+ const quarter = Number(slider?.value);++ seek(3);+ expect(Number(number?.value)).toBeCloseTo(0.75, 2);+ expect(Number(slider?.value)).toBeGreaterThan(quarter);+ });++ it("shows the lane's own edge value off the clip, not the stored seed", () => {+ // Past the bed's end, where a lane holds its last value — which is what would+ // play if the playhead came back. The stored -1 dB is a seed the lane replaced+ // and nothing will ever use it, so putting it on screen only made the fader+ // jump when the clip came under the playhead.+ seek(20);+ const { host } = mount(carved);+ openModule(host);+ const gain = gainReadout(host);+ expect(gain?.textContent).toContain("-6 dB"); // the ramp's last point+ expect(gain?.hasAttribute("data-automation-live")).toBe(true);+ expect(gain?.hasAttribute("data-automated")).toBe(true);+ });++ it("holds the lane's first value before the clip starts", () => {+ // Same rule at the other end: a lane opens on its first point, so that is what+ // the fader should read while the playhead is still upstream of the clip.+ seek(-5);+ const { host } = mount(carved);+ openModule(host);+ expect(gainReadout(host)?.textContent).toContain("0 dB");+ });+});diff --git a/packages/studio/src/components/editor/propertyPanelAudioFxGroup.tsx b/packages/studio/src/components/editor/propertyPanelAudioFxGroup.tsxindex 2d56849959..9401d6aae7 100644--- a/packages/studio/src/components/editor/propertyPanelAudioFxGroup.tsx+++ b/packages/studio/src/components/editor/propertyPanelAudioFxGroup.tsx@@ -9,20 +9,30 @@import { useState } from "react";import {+ defaultAudioFxParams,HF_AUDIO_FX_ATTR,+ mintAudioFxNodeId,parseAudioFxChain,serializeAudioFxChain,type HfAudioFxChain,+ type HfAudioFxNode,} from "@hyperframes/core/audio-fx";import {analyseCarveBands,+ analyseCarveDuck,+ analyseCarveDynamics,carveBandsToChain,carveProfile,HF_AUDIO_CARVE_ATTR,normalizeCarveSettings,type HfCarveSettings,} from "@hyperframes/core/audio-carve";-import { fxAutomationTarget, type HfAutomation } from "@hyperframes/core/audio-automation";+import {+ fxAutomationTarget,+ sampleAutomationLane,+ type HfAutomation,+ type HfAutomationLane,+} from "@hyperframes/core/audio-automation";import {automatedTargetsOf,automationAttrValue,@@ -33,6 +43,7 @@ import {withSeededLane,} from "./propertyPanelAutomation";import type { DomEditSelection } from "./domEditingTypes";+import { useLivePlayheadTime } from "../../hooks/useLivePlayheadTime";/*** Rate the carve source is decoded at. Analysis is self-consistent because it@@ -41,6 +52,22 @@ import type { DomEditSelection } from "./domEditingTypes";const DECODE_SAMPLE_RATE = 48000;import { FxSection, type AudioTrackOption } from "./propertyPanelFxSection.js";+/** Where a clip starts on the timeline, in seconds. */+function clipStart(value: string | null | undefined): number {+ const n = Number(value);+ return Number.isFinite(n) ? n : 0;+}++/** Lanes belonging to nodes the carve generated, which a re-run replaces. */+function withoutCarveLanes(automation: HfAutomation, chain: HfAudioFxChain): HfAutomation {+ const prefixes = chain.nodes.filter((n) => n.fromCarve && n.id).map((n) => `fx.${n.id}.`);+ if (prefixes.length === 0) return automation;+ return {+ version: automation.version,+ lanes: automation.lanes.filter((lane) => !prefixes.some((p) => lane.target.startsWith(p))),+ };+}+/*** Bridges the FX panel to the element/attribute world. Chain and carve are* serialised onto the element the way colour grading carries its config, so@@ -81,6 +108,37 @@ export function AudioFxGroup({const automation = readPanelAutomation(element.dataAttributes?.["automation"], chain);const automatedTargets = automatedTargetsOf(automation);+ /**+ * What every automated knob is worth at the playhead, so the rack shows the+ * value the audio is actually using rather than the one the attribute stores.+ *+ * An automated parameter has two values: the number sitting in the chain, which+ * is only a seed once a lane exists, and the number the envelope is on right now.+ * The second is the true one, and a rack that shows the first reads as broken+ * during playback — the carve is visibly working and the readouts do not move.+ *+ * Sampled while paused as well, because the same argument applies to a scrub:+ * the playhead is somewhere, and the envelope has a value there.+ *+ * Sampled off the clip too, which is not obvious. A lane holds its first value+ * backwards and its last value forwards, so before the clip starts it already+ * knows what it will open on — while the stored number is a seed the lane+ * replaced and nothing will ever play. Showing that seed put a value on screen+ * that the automation never uses, and made the fader jump the moment the clip+ * came under the playhead.+ */+ const playhead = useLivePlayheadTime();+ const localTime = playhead - clipStart(element.dataAttributes?.["start"]);+ const liveAutomationValues = ((): Map<string, number> => {+ const values = new Map<string, number>();+ for (const lane of automation.lanes) {+ const range = resolveAutomationRange(lane.target, chain);+ if (!range) continue;+ values.set(lane.target, sampleAutomationLane(lane, localTime, range.scale));+ }+ return values;+ })();+// Written through the live path on purpose. It persists to the source just// like the refreshing one, but skips the preview reload — and a reload// restarts every playing track, which is heard as the audio chopping. The@@ -127,6 +185,18 @@ export function AudioFxGroup({* commit, which does not exist yet.*/const setCarve = async (next: HfCarveSettings | null): Promise<void> => {+ // Envelopes the carve wrote outlive it otherwise, and an automated gain+ // ignores the panel's own depth — so switching dynamic off would leave the+ // filters still following the voice with nothing saying they do.+ if (!next || (carve?.dynamic && !next.dynamic)) {+ const carriedOver = withoutCarveLanes(automation, chain);+ if (carriedOver.lanes.length !== automation.lanes.length) {+ await onSetAttributeQuiet(+ HF_AUDIO_AUTOMATION_ATTR,+ automationAttrValue(carriedOver) || null,+ );+ }+ }if (!next) {const kept = chain.nodes.filter((n) => !n.fromCarve);if (kept.length !== chain.nodes.length) {@@ -137,6 +207,20 @@ export function AudioFxGroup({}}await onSetAttributeQuiet(HF_AUDIO_CARVE_ATTR, next ? JSON.stringify(next) : null);++ // Every setting here describes the filters, so changing one rebuilds them.+ // There is no apply button: a carve naming a voice with no filters behind it+ // is a setting nobody applied, and the panel already knows everything it needs+ // to. Picking the voice is what starts it; strength and dynamic re-derive what+ // is already there. A carve with no source yet has nothing to analyse.+ const changed =+ next &&+ next.source &&+ (!carve ||+ next.source !== carve.source ||+ next.strength !== carve.strength ||+ next.dynamic !== carve.dynamic);+ if (next && changed) await analyse(next);};/** Every lane belonging to a node that is going away. */@@ -158,6 +242,32 @@ export function AudioFxGroup({}})();+ /**+ * Is some other track carving against this one?+ *+ * A carve is a relationship — a bed is carved against a voice — and the voice is+ * the far end of it. Offering the same control there offers to carve a track+ * against itself by proxy, and switching it on left a setting with no source it+ * could legally name. Read off the other elements' own carve attributes, because+ * that is where the relationship is recorded.+ */+ const carvedAgainstBy = ((): string | null => {+ const doc = element.element?.ownerDocument;+ if (!doc || !element.id) return null;+ for (const other of Array.from(doc.querySelectorAll<HTMLElement>(`[${HF_AUDIO_CARVE_ATTR}]`))) {+ if (other.id === element.id) continue;+ try {+ const raw = other.getAttribute(HF_AUDIO_CARVE_ATTR);+ if (raw && normalizeCarveSettings(JSON.parse(raw)).source === element.id) {+ return other.id || "another track";+ }+ } catch {+ // An unreadable carve on some other element says nothing about this one.+ }+ }+ return null;+ })();+const sourceOptions: AudioTrackOption[] = (() => {const doc = element.element?.ownerDocument;if (!doc) return [];@@ -173,16 +283,14 @@ export function AudioFxGroup({* on this one. The bands replace any previous carve output but leave* hand-added effects alone, so re-analysing does not discard other work.*/- const analyse = async (): Promise<void> => {- if (!carve?.source) return;+ const analyse = async (active: HfCarveSettings | null = carve): Promise<void> => {+ if (!active?.source) return;const doc = element.element?.ownerDocument;- const voice = doc?.getElementById(carve.source) as HTMLAudioElement | null;+ const voice = doc?.getElementById(active.source) as HTMLAudioElement | null;const src = voice?.getAttribute("src");if (!src) return;setAnalysing(true);try {- const res = await fetch(new URL(src, doc!.baseURI).href);- const bytes = await res.arrayBuffer();// Decoded in an OfflineAudioContext, not a live one. Opening a second// output device mid-playback makes the running track glitch while the// hardware is reconfigured; an offline context touches no device.@@ -191,24 +299,116 @@ export function AudioFxGroup({(window as unknown as { webkitOfflineAudioContext?: typeof OfflineAudioContext }).webkitOfflineAudioContext;if (!Ctor) return;- const decoder = new Ctor(1, 1, DECODE_SAMPLE_RATE);- const buffer = await decoder.decodeAudioData(bytes);- const bands = analyseCarveBands(- buffer.getChannelData(0),- buffer.sampleRate,- carveProfile(carve.strength),- );+ const decode = async (relative: string): Promise<AudioBuffer> => {+ const res = await fetch(new URL(relative, doc!.baseURI).href);+ return new Ctor(1, 1, DECODE_SAMPLE_RATE).decodeAudioData(await res.arrayBuffer());+ };+ const buffer = await decode(src);+ // Strength is what the author set; these are the numbers it means.+ const profile = carveProfile(active.strength);+ // The bed as well as the voice, when the carve is asked to match levels:+ // "how far over the voice is this bed" cannot be answered by listening to+ // one of them.+ const bedSrc = profile.duckDb > 0 ? element.element?.getAttribute("src") : null;+ const bedBuffer = bedSrc ? await decode(bedSrc).catch(() => null) : null;+ const bands = analyseCarveBands(buffer.getChannelData(0), buffer.sampleRate, profile);const carved = carveBandsToChain(bands);++ // The level half of the carve, measured against the voice it has to sit+ // under. Times come back relative to the voice clip; the gap between the+ // two clips' starts is what aligns them.+ const offset =+ clipStart(voice?.getAttribute("data-start")) - clipStart(element.dataAttributes?.["start"]);+ const duck = bedBuffer+ ? analyseCarveDuck(+ buffer.getChannelData(0),+ bedBuffer.getChannelData(0),+ buffer.sampleRate,+ profile,+ offset,+ )+ : [];+ // Static carve holds one value, so the level match becomes the duck the+ // voice needs while it is actually speaking — the median of it, which+ // ignores both the pauses and any single loudest bar.+ const speaking = duck.filter((p) => p.v < 0).map((p) => p.v);+ const staticDuckDb = speaking.length+ ? (speaking.sort((a, b) => a - b)[Math.floor(speaking.length / 2)] ?? 0)+ : 0;+// Carve output is tagged so a re-run replaces it instead of stacking.const kept = chain.nodes.filter((n) => !n.fromCarve);+ // Ids, minted against the nodes already claiming one, because a dynamic+ // carve automates these filters and a lane addresses its node by id.+ let claimed: HfAudioFxChain = { version: 1, nodes: kept };+ const mint = (node: HfAudioFxNode): HfAudioFxNode => {+ const withId = { ...node, id: mintAudioFxNodeId(claimed), fromCarve: true };+ claimed = { version: 1, nodes: [...claimed.nodes, withId] };+ return withId;+ };+ const carvedNodes: HfAudioFxNode[] = carved.nodes.map(mint);+ // The gain stage sits after the filters, and only exists when the carve was+ // asked to make level room. Dynamic drives it from the envelope; static+ // holds the one value above.+ const duckNode =+ duck.length > 0+ ? mint({+ type: "gain",+ enabled: true,+ params: { ...defaultAudioFxParams("gain"), gain: active.dynamic ? 0 : staticDuckDb },+ })+ : null;const next = {version: 1,- nodes: [...carved.nodes.map((n) => ({ ...n, fromCarve: true })), ...kept],+ nodes: [...carvedNodes, ...(duckNode ? [duckNode] : []), ...kept],};// Live, like every other chain write: the runtime swaps the graph in// place, so a reload would only interrupt the audio to reach the same// filters.- onSetAttributeQuiet(HF_AUDIO_FX_ATTR, serializeAudioFxChain(next));+ //+ // Awaited, because the automation write below is a second read-modify-write+ // against the same file — fired together the later one would drop the+ // earlier — and because a lane naming a node the chain does not have yet is+ // pruned when it is read back.+ await onSetAttributeQuiet(HF_AUDIO_FX_ATTR, serializeAudioFxChain(next));++ /**+ * One carve envelope as a lane on this bed's clock.+ *+ * Everything the analysis returns is timed from the start of the voice, so+ * it shifts by the gap between the two clips; and a lane holds its first+ * value backwards to the start of its own clip, so a bed that begins before+ * the voice needs an explicit "no cut" at zero or it starts out ducked.+ */+ const laneFor = (id: string, points: { t: number; v: number }[]): HfAutomationLane[] => {+ const shifted = points+ .map((p) => ({ t: Number((p.t + offset).toFixed(3)), v: p.v }))+ .filter((p) => p.t >= 0);+ if ((shifted[0]?.t ?? 0) > 0) shifted.unshift({ t: 0, v: 0 });+ return shifted.length > 1+ ? [{ target: fxAutomationTarget(id, "gain"), points: shifted }]+ : [];+ };++ // Dynamic carve: each filter's depth becomes an envelope of the voice's+ // level in that band, so pauses leave the bed alone.+ const lanes: HfAutomationLane[] = active.dynamic+ ? analyseCarveDynamics(buffer.getChannelData(0), buffer.sampleRate, bands).flatMap(+ (dyn, i) => {+ const id = carvedNodes[i]?.id;+ if (!id) return [];+ return laneFor(id, dyn.points);+ },+ )+ : [];+ // The level envelope rides the gain stage, on the same clock as the bands.+ if (active.dynamic && duckNode?.id && duck.length > 0) {+ lanes.push(...laneFor(duckNode.id, duck));+ }+ const carriedOver = withoutCarveLanes(automation, chain);+ if (lanes.length > 0 || carriedOver.lanes.length !== automation.lanes.length) {+ writeAutomation({ version: 1, lanes: [...carriedOver.lanes, ...lanes] });+ }} catch {// Leave the chain as it was; the button simply re-enables.} finally {@@ -220,6 +420,7 @@ export function AudioFxGroup({<FxSectionchain={chain}automatedTargets={automatedTargets}+ liveAutomationValues={liveAutomationValues}onAutomateParam={automateParam}onRemoveParamAutomation={removeParamAutomation}onRemoveNodeAutomation={removeNodeAutomation}@@ -242,7 +443,7 @@ export function AudioFxGroup({onCarveChange={(next) => void setCarve(next)}onCarvePreview={(next) => onSetAttributeLive(HF_AUDIO_CARVE_ATTR, JSON.stringify(next))}sourceOptions={sourceOptions}- onAnalyseCarve={() => void analyse()}+ carvedAgainstBy={carvedAgainstBy}analysing={analysing}/>);diff --git a/packages/studio/src/components/editor/propertyPanelFxControls.tsx b/packages/studio/src/components/editor/propertyPanelFxControls.tsxindex ffc7ffd88c..67f7e07ee9 100644--- a/packages/studio/src/components/editor/propertyPanelFxControls.tsx+++ b/packages/studio/src/components/editor/propertyPanelFxControls.tsx@@ -42,6 +42,12 @@ function display(p: HfAudioFxNumberParam, value: number): string {interface ParamRowProps {param: HfAudioFxParam;value: number | string;+ /**+ * The envelope's value at the playhead, when a lane drives this parameter and+ * the playhead is over the clip. Shown in place of `value`, which by then is+ * only the seed the lane replaced.+ */+ liveValue?: number;/** Fires continuously while dragging — cheap, not persisted. */onChange(key: string, value: number | string): void;/** Fires once when the gesture ends — this is the write that persists. */@@ -100,6 +106,7 @@ export function AutomationToggle({export function FxParamRow({param,value,+ liveValue,onChange,onCommit,disabled,@@ -159,7 +166,11 @@ export function FxParamRow({);}- const shown = dragging ? local : value;+ // An envelope's value at the playhead outranks the one stored in the chain,+ // because it is the one the audio is using — the stored number is only the seed+ // the lane replaced. Safe against the pointer: an automated control is locked+ // (see `locked` below), so there is no drag for this to fight.+ const shown = dragging ? local : (liveValue ?? value);const numeric = typeof shown === "number" ? shown : Number(shown);const current = Number.isFinite(numeric) ? numeric : param.default;@@ -229,6 +240,8 @@ export function FxParamRow({interface FxParamsProps {def: HfAudioFxDef;params: HfAudioFxParamValues;+ /** What automated knobs are worth at the playhead, by parameter key. */+ liveValues?: ReadonlyMap<string, number>;onChange(params: HfAudioFxParamValues): void;onCommit?(params: HfAudioFxParamValues): void;disabled?: boolean;@@ -243,6 +256,7 @@ interface FxParamsProps {export function FxParams({def,params,+ liveValues,onChange,onCommit,disabled,@@ -270,6 +284,7 @@ export function FxParams({key={p.key}param={p}value={params[p.key] ?? p.default}+ liveValue={liveValues?.get(p.key)}onChange={set}onCommit={commit}disabled={disabled}diff --git a/packages/studio/src/components/editor/propertyPanelFxSection.test.tsx b/packages/studio/src/components/editor/propertyPanelFxSection.test.tsxindex 397b6b0793..cd6e5aeea6 100644--- a/packages/studio/src/components/editor/propertyPanelFxSection.test.tsx+++ b/packages/studio/src/components/editor/propertyPanelFxSection.test.tsx@@ -28,8 +28,6 @@ const chainOf = (...types: string[]): HfAudioFxChain => ({nodes: types.map((t) => ({ type: t, enabled: true, params: defaultAudioFxParams(t) })),});-const noop = () => {};-function mount(overrides: Partial<Parameters<typeof FxSection>[0]> = {}) {const onChainChange = vi.fn();const onChainPreview = vi.fn();@@ -42,7 +40,6 @@ function mount(overrides: Partial<Parameters<typeof FxSection>[0]> = {}) {carve={overrides.carve ?? null}onCarveChange={overrides.onCarveChange ?? onCarveChange}sourceOptions={overrides.sourceOptions ?? [{ id: "vo", label: "Voiceover" }]}- onAnalyseCarve={overrides.onAnalyseCarve ?? noop}analysing={overrides.analysing}disabled={overrides.disabled}automatedTargets={overrides.automatedTargets}@@ -200,6 +197,123 @@ describe("FxSection chain", () => {});});+describe("FxSection carve module", () => {+ /**+ * A carve is one thing an author turned on, not the six filters it happens to+ * compile to. Listed individually they read as hand-built effects: removable+ * one at a time, reorderable, each with knobs that the next strength change+ * overwrites without warning.+ */+ const carved = {+ version: 1,+ nodes: [+ { type: "peaking", id: "n1", fromCarve: true, params: { frequency: 400, gain: -6, q: 1.4 } },+ { type: "peaking", id: "n2", fromCarve: true, params: { frequency: 1600, gain: -9, q: 1.4 } },+ { type: "gain", id: "n3", fromCarve: true, params: { gain: -6 } },+ { type: "lowpass", id: "n4", params: { frequency: 8000, q: 0.7, poles: "2" } },+ ],+ } as unknown as HfAudioFxChain;++ it("shows the carve's effects as one module, alongside hand-built ones", () => {+ const { host } = mount({ chain: carved });+ const rows = Array.from(host.querySelectorAll<HTMLElement>(".hf-fx-node"));+ // One row for the carve, one for the low-pass the author added.+ expect(rows).toHaveLength(2);+ expect(host.querySelector(".hf-fx-carve-module")).not.toBeNull();+ expect(host.querySelector(".hf-fx-carve-module")?.textContent).toContain("Voiceover carve");+ });++ it("says what the module contains, since its parts are not listed", () => {+ const { host } = mount({ chain: carved });+ const text = host.querySelector(".hf-fx-carve-module")?.textContent ?? "";+ expect(text).toMatch(/2 bands/);+ expect(text).toMatch(/level/);+ });++ it("removes every carve effect together, never one of them", () => {+ const onChainChange = vi.fn();+ const { host } = mount({ chain: carved, onChainChange });+ const removes = Array.from(+ host.querySelectorAll<HTMLButtonElement>(".hf-fx-carve-module .hf-fx-remove"),+ );+ expect(removes).toHaveLength(1);+ act(() => removes[0]!.click());+ const nodes = onChainChange.mock.calls[0]![0].nodes as { id: string }[];+ expect(nodes.map((n) => n.id)).toEqual(["n4"]);+ });++ it("bypasses the whole module at once", () => {+ const onChainChange = vi.fn();+ const { host } = mount({ chain: carved, onChainChange });+ const bypass = host.querySelector<HTMLButtonElement>(".hf-fx-carve-module .hf-fx-bypass")!;+ act(() => bypass.click());+ const nodes = onChainChange.mock.calls[0]![0].nodes as { id: string; enabled?: boolean }[];+ expect(nodes.filter((n) => n.id !== "n4").every((n) => n.enabled === false)).toBe(true);+ // The author's own effect is not touched.+ expect(nodes.find((n) => n.id === "n4")?.enabled).not.toBe(false);+ });++ it("lists what each effect inside it is set to", () => {+ // Grouped is not hidden: the carve compiles to real filters and an author has+ // to be able to see where they landed. What they cannot do is edit them by+ // hand — strength owns those numbers — so the settings read out rather than+ // offering controls that the next adjustment would overwrite.+ const { host } = mount({ chain: carved });+ const module = host.querySelector<HTMLElement>(".hf-fx-carve-module")!;+ act(() => module.querySelector<HTMLButtonElement>(".hf-fx-node-name")!.click());+ const members = Array.from(module.querySelectorAll<HTMLElement>(".hf-fx-carve-member"));+ expect(members).toHaveLength(3);+ // Named by what tells them apart, the way the timeline lanes name them.+ expect(members.map((m) => m.querySelector(".hf-fx-carve-member-name")?.textContent)).toEqual([+ "Peaking EQ 400 Hz",+ "Peaking EQ 1.6 kHz",+ "Gain",+ ]);+ // And every one of its settings is visible.+ const first = members[0]!.textContent ?? "";+ expect(first).toContain("Gain");+ expect(first).toMatch(/-6(\.0)? dB/);+ expect(first).toMatch(/1\.4/); // Q+ });++ it("reads its settings out rather than offering controls", () => {+ const { host } = mount({ chain: carved });+ const module = host.querySelector<HTMLElement>(".hf-fx-carve-module")!;+ act(() => module.querySelector<HTMLButtonElement>(".hf-fx-node-name")!.click());+ expect(module.querySelectorAll("input")).toHaveLength(0);+ });++ it("says which of them the timeline is driving", () => {+ // A carve in dynamic mode automates every one of these, and that is where the+ // values come from — so the module has to point at the lane rather than look+ // like a static setting.+ const { host } = mount({+ chain: carved,+ automatedTargets: new Set(["fx.n1.gain", "fx.n3.gain"]),+ });+ const module = host.querySelector<HTMLElement>(".hf-fx-carve-module")!;+ act(() => module.querySelector<HTMLButtonElement>(".hf-fx-node-name")!.click());+ const automated = Array.from(module.querySelectorAll("[data-automated]"));+ expect(automated).toHaveLength(2);+ });++ it("keeps the summary readable while collapsed", () => {+ const { host } = mount({ chain: carved });+ const module = host.querySelector<HTMLElement>(".hf-fx-carve-module")!;+ expect(module.querySelectorAll(".hf-fx-carve-member")).toHaveLength(0);+ expect(module.textContent).toContain("2 bands + level");+ });++ it("offers no per-effect controls inside the module", () => {+ // Reordering or editing one band is meaningless: the next strength change+ // rewrites every one of them.+ const { host } = mount({ chain: carved });+ const module = host.querySelector(".hf-fx-carve-module")!;+ expect(module.querySelectorAll(".hf-fx-move")).toHaveLength(0);+ expect(module.querySelectorAll("input[type=range]")).toHaveLength(0);+ });+});+describe("FxSection carve", () => {it("is off by default and is not an entry in the chain", () => {const { host } = mount();@@ -229,16 +343,17 @@ describe("FxSection carve", () => {expect(options).toContain("Narration");});- it("will not analyse until a source is chosen", () => {- const { host } = mount({ carve: { ...DEFAULT_CARVE, source: "" } });- expect(host.querySelector<HTMLButtonElement>(".hf-fx-analyse")!.disabled).toBe(true);+ it("offers no analyse button — picking a voice is the whole gesture", () => {+ // A carve with a source and no filters is a setting nobody applied; the+ // button was a second step for something the panel already knew to do.+ const { host } = mount({ carve: { ...DEFAULT_CARVE, source: "vo" } });+ expect(host.querySelector(".hf-fx-analyse")).toBeNull();+ expect(host.textContent).not.toMatch(/Analyse/i);});- it("analyses once a source is chosen", () => {- const onAnalyseCarve = vi.fn();- const { host } = mount({ carve: { ...DEFAULT_CARVE, source: "vo" }, onAnalyseCarve });- click(host.querySelector(".hf-fx-analyse"));- expect(onAnalyseCarve).toHaveBeenCalledTimes(1);+ it("says when it is working, since there is no button to grey out", () => {+ const { host } = mount({ carve: { ...DEFAULT_CARVE, source: "vo" }, analysing: true });+ expect(host.querySelector(".hf-fx-carve-working")?.textContent).toMatch(/Analysing/i);});it("disables everything when the panel is read-only", () => {diff --git a/packages/studio/src/components/editor/propertyPanelFxSection.tsx b/packages/studio/src/components/editor/propertyPanelFxSection.tsxindex 8e629af84b..3a99c77862 100644--- a/packages/studio/src/components/editor/propertyPanelFxSection.tsx+++ b/packages/studio/src/components/editor/propertyPanelFxSection.tsx@@ -18,11 +18,15 @@ import {type HfAudioFxDef,type HfAudioFxGroup,type HfAudioFxNode,+ type HfAudioFxParam,type HfAudioFxParamValues,} from "@hyperframes/core/audio-fx";import { DEFAULT_CARVE, type HfCarveSettings } from "@hyperframes/core/audio-carve";import { fxAutomationTarget } from "@hyperframes/core/audio-automation";import { FxParams, FxParamRow } from "./propertyPanelFxControls.js";+// Shared with the timeline's lane labels: a band is named by its frequency in+// both places, and two formatters would drift.+import { formatHz } from "../../player/components/automationLaneData";const GROUP_ORDER: HfAudioFxGroup[] = ["filter", "dynamics", "nonlinear", "time"];const GROUP_LABEL: Record<HfAudioFxGroup, string> = {@@ -41,6 +45,7 @@ interface FxNodeRowProps {node: HfAudioFxNode;index: number;automatedTargets?: ReadonlySet<string>;+ liveAutomationValues?: ReadonlyMap<string, number>;onAutomateParam?(nodeId: string, paramKey: string): void;onRemoveParamAutomation?(nodeId: string, paramKey: string): void;open: boolean;@@ -148,6 +153,205 @@ function FxNodeHeader({);}+/**+ * The carve's own effects, as one module.+ *+ * A carve is one thing the author switched on; the peaking filters and the level+ * stage are how it is built. Listed individually they read as hand-built effects+ * — removable one at a time, reorderable, each with knobs the next strength+ * change silently overwrites. So the rack shows the unit, says what is inside it,+ * and offers the two actions that mean anything for a whole module: bypass it,+ * or remove it.+ */+/** What one effect inside the module is called: its own name, plus the band. */+function carveMemberName(node: HfAudioFxNode): string {+ const def = getAudioFxDef(node.type);+ const freq = node.params?.["frequency"];+ const label = def?.label ?? node.type;+ return typeof freq === "number" ? `${label} ${formatHz(freq)}` : label;+}++/** A parameter's value as the rack shows it: rounded to the step, with its unit. */+function formatParamValue(param: HfAudioFxParam, raw: number | string | undefined): string {+ if (param.kind !== "number" || typeof raw !== "number") return String(raw ?? "");+ const places = param.step >= 1 ? 0 : param.step >= 0.1 ? 1 : 2;+ return `${Number(raw.toFixed(places))}${param.unit ? ` ${param.unit}` : ""}`;+}++/**+ * Width to reserve for a parameter's value, in characters.+ *+ * Derived from what the parameter CAN read rather than what it currently reads, so+ * the column never moves: an automated value updates 30 times a second, and+ * `-1 dB` is two characters narrower than `-3.2 dB`, which was enough to shunt+ * everything after it sideways on every frame. `ch` is exact here because the+ * readouts are monospace and already `tabular-nums`.+ */+function paramValueWidthCh(param: HfAudioFxParam): number {+ if (param.kind === "enum") {+ return Math.max(1, ...param.options.map((option) => option.value.length));+ }+ const places = param.step >= 1 ? 0 : param.step >= 0.1 ? 1 : 2;+ const digits = Math.max(+ String(Math.floor(Math.abs(param.min))).length,+ String(Math.floor(Math.abs(param.max))).length,+ );+ const sign = param.min < 0 ? 1 : 0;+ const decimals = places > 0 ? places + 1 : 0;+ const unit = param.unit ? param.unit.length + 1 : 0;+ return sign + digits + decimals + unit;+}++/** One member of the module: what it is, and what every knob is set to. */+function FxCarveMember({+ node,+ automatedTargets,+ liveAutomationValues,+}: {+ node: HfAudioFxNode;+ automatedTargets?: ReadonlySet<string>;+ liveAutomationValues?: ReadonlyMap<string, number>;+}) {+ const def = getAudioFxDef(node.type);+ if (!def) return null;+ const params = node.params ?? defaultAudioFxParams(node.type);+ return (+ <div className="hf-fx-carve-member flex flex-col gap-0.5 py-1 pl-3 pr-1.5">+ <span className="hf-fx-carve-member-name truncate font-mono text-[9px] text-panel-text-1">+ {carveMemberName(node)}+ </span>+ <div className="flex flex-wrap gap-x-3 gap-y-0.5">+ {def.params.map((param) => {+ const target = node.id ? fxAutomationTarget(node.id, param.key) : null;+ const automated = Boolean(target && automatedTargets?.has(target));+ // The envelope's value at the playhead when there is one, which is what+ // the audio is using; the stored number is only the seed behind it.+ const live = target ? liveAutomationValues?.get(target) : undefined;+ const driven = automated && live !== undefined;+ const value = formatParamValue(param, driven ? live : params[param.key]);+ return (+ <span+ key={param.key}+ className="flex items-baseline gap-1 font-mono text-[9px] text-panel-text-4"+ {...(automated ? { "data-automated": "" } : {})}+ {...(driven ? { "data-automation-live": "" } : {})}+ >+ <span className="text-panel-text-4">{param.label}</span>+ <span+ className="tabular-nums text-panel-text-1"+ style={{ minWidth: `${paramValueWidthCh(param)}ch` }}+ >+ {value}+ </span>+ {/* The lane is where an automated value comes from, and where it is+ edited — saying so is the difference between a stale readout and+ a pointer to the thing that owns it. */}+ {automated ? <span className="text-[#3CE6AC]">A</span> : null}+ </span>+ );+ })}+ </div>+ </div>+ );+}++/**+ * The carve's own effects, as one module.+ *+ * A carve is one thing the author switched on; the peaking filters and the level+ * stage are how it is built. Listed individually in the rack they read as+ * hand-built effects — removable one at a time, reorderable, each with knobs the+ * next strength change silently overwrites. So the rack shows the unit, and the+ * unit owns the actions that mean anything for a whole module: bypass, remove.+ *+ * Grouped is not hidden. Opening it lists every effect inside with all of its+ * settings, because an author has to be able to see where the analysis landed —+ * as readouts rather than controls, since strength is what sets them and a knob+ * here would be overwritten by the next adjustment. A value the timeline drives+ * says so, and points at the lane that owns it.+ */+function FxCarveModule({+ nodes,+ automatedTargets,+ liveAutomationValues,+ open,+ disabled,+ onToggleOpen,+ onToggleBypass,+ onRemove,+}: {+ nodes: HfAudioFxNode[];+ automatedTargets?: ReadonlySet<string>;+ liveAutomationValues?: ReadonlyMap<string, number>;+ open: boolean;+ disabled?: boolean;+ onToggleOpen(): void;+ onToggleBypass(): void;+ onRemove(): void;+}) {+ const bands = nodes.filter((n) => n.type === "peaking").length;+ const hasLevel = nodes.some((n) => n.type === "gain");+ const bypassed = nodes.every((n) => n.enabled === false);+ const summary = [`${bands} band${bands === 1 ? "" : "s"}`, ...(hasLevel ? ["level"] : [])].join(+ " + ",+ );+ return (+ <div+ className={`hf-fx-node hf-fx-carve-module rounded-[4px] border border-panel-border-input${+ bypassed ? " opacity-50" : ""+ }`}+ data-fx-node="carve"+ >+ <div className="hf-fx-node-head flex min-h-7 items-center gap-1 px-1.5">+ <button+ type="button"+ className="hf-fx-node-name min-w-0 flex-1 truncate text-left text-[11px] font-semibold text-panel-text-1 hover:text-panel-text-0"+ aria-expanded={open}+ onClick={onToggleOpen}+ >+ Voiceover carve+ </button>+ <span className="hf-fx-carve-summary shrink-0 font-mono text-[9px] text-panel-text-4">+ {summary}+ </span>+ <button+ type="button"+ className="hf-fx-bypass rounded-[3px] border border-panel-border-input px-1.5 py-0.5 font-mono text-[9px] text-panel-text-4 hover:text-panel-text-0 disabled:opacity-40"+ aria-pressed={bypassed}+ title={bypassed ? "Enable carve" : "Bypass carve"}+ disabled={disabled}+ onClick={onToggleBypass}+ >+ {bypassed ? "Off" : "On"}+ </button>+ <button+ type="button"+ className="hf-fx-remove px-1 font-mono text-[11px] text-panel-text-4 hover:text-red-400 disabled:opacity-40"+ title="Remove carve"+ disabled={disabled}+ onClick={onRemove}+ >+ ×+ </button>+ </div>+ {open ? (+ // Divided rows rather than boxes: these are parts of one module, and a+ // border around each would read as the separate effects this replaced.+ <div className="hf-fx-carve-members divide-y divide-panel-border-input/60 border-t border-panel-border-input">+ {nodes.map((node, i) => (+ <FxCarveMember+ key={node.id ?? `${node.type}-${i}`}+ node={node}+ automatedTargets={automatedTargets}+ liveAutomationValues={liveAutomationValues}+ />+ ))}+ </div>+ ) : null}+ </div>+ );+}+/*** Which of an effect's knobs already have a lane.*@@ -174,6 +378,7 @@ function FxNodeParams({index,disabled,automatedTargets,+ liveAutomationValues,onUpdate,onPreview,onAutomateParam,@@ -184,16 +389,29 @@ function FxNodeParams({index: number;disabled: boolean;automatedTargets?: ReadonlySet<string>;+ liveAutomationValues?: ReadonlyMap<string, number>;onUpdate(index: number, patch: Partial<HfAudioFxNode>): void;onPreview(index: number, params: HfAudioFxParamValues): void;onAutomateParam?(nodeId: string, paramKey: string): void;onRemoveParamAutomation?(nodeId: string, paramKey: string): void;}) {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.+ const liveValues = ((): Map<string, number> | undefined => {+ if (!nodeId || !liveAutomationValues?.size) return undefined;+ const byKey = new Map<string, number>();+ for (const param of def.params) {+ const live = liveAutomationValues.get(fxAutomationTarget(nodeId, param.key));+ if (live !== undefined) byKey.set(param.key, live);+ }+ return byKey;+ })();return (<FxParamsdef={def}params={node.params ?? defaultAudioFxParams(node.type)}+ liveValues={liveValues}disabled={disabled}onChange={(params: HfAudioFxParamValues) => onPreview(index, params)}onCommit={(params: HfAudioFxParamValues) => onUpdate(index, { params })}@@ -213,6 +431,7 @@ function FxNodeRow({node,index,automatedTargets,+ liveAutomationValues,onAutomateParam,onRemoveParamAutomation,open,@@ -251,6 +470,7 @@ function FxNodeRow({index={index}disabled={Boolean(disabled) || bypassed}automatedTargets={automatedTargets}+ liveAutomationValues={liveAutomationValues}onUpdate={onUpdate}onPreview={onPreview}onAutomateParam={onAutomateParam}@@ -265,6 +485,15 @@ export interface FxSectionProps {chain: HfAudioFxChain;/** Targets this track already automates, as `fx.<nodeId>.<param>` strings. */automatedTargets?: ReadonlySet<string>;+ /**+ * What each automated target is worth at the playhead, by the same key.+ *+ * An automated parameter's stored number is only the seed the lane replaced, so+ * a rack that shows it stands still while the carve is audibly working. Absent,+ * or missing a key, means there is no playhead over this clip and the stored+ * value is the honest one.+ */+ liveAutomationValues?: ReadonlyMap<string, number>;/** Add a lane for one effect parameter, seeded at its current value. */onAutomateParam?(nodeId: string, paramKey: string): void;/** Delete one effect parameter's lane. */@@ -281,10 +510,13 @@ export interface FxSectionProps {/** Continuous updates while a carve slider is dragged. Without this every* pointermove patched the source file and resynced the selection. */onCarvePreview?(carve: HfCarveSettings): void;+ /**+ * Set when another track's carve listens to this one, naming it. The carve block+ * is then not offered here at all: this track is the voice, not the bed.+ */+ carvedAgainstBy?: string | null;/** Other audio elements that could act as the carve source. */sourceOptions: AudioTrackOption[];- /** Re-run analysis against the current source audio. */- onAnalyseCarve?(): void;analysing?: boolean;disabled?: boolean;}@@ -292,16 +524,17 @@ export interface FxSectionProps {export function FxSection({chain,automatedTargets,+ liveAutomationValues,onAutomateParam,onRemoveParamAutomation,onRemoveNodeAutomation,onChainChange,onChainPreview,carve,+ carvedAgainstBy,onCarveChange,onCarvePreview,sourceOptions,- onAnalyseCarve,analysing,disabled,}: FxSectionProps) {@@ -310,7 +543,10 @@ export function FxSection({const previewCarve = onCarvePreview ?? onCarveChange;// Nothing to carve against means nothing to show — see the block below.- const showCarve = sourceOptions.length > 0 || carve !== null;+ // Not offered on the voice another track is already carving against — that+ // track is the far end of someone else's relationship, and a carve of its own+ // could only name a source it must not.+ const showCarve = !carvedAgainstBy && (sourceOptions.length > 0 || carve !== null);const [adding, setAdding] = useState(false);const [openNode, setOpenNode] = useState<number | null>(0);@@ -368,6 +604,24 @@ export function FxSection({[chain.nodes, mutate, onRemoveNodeAutomation],);+ const [carveOpen, setCarveOpen] = useState(false);+ const carveNodes = useMemo(() => chain.nodes.filter((n) => n.fromCarve), [chain.nodes]);++ /** Remove the carve's effects together, with the envelopes they carried. */+ const removeCarve = useCallback(() => {+ for (const node of carveNodes) {+ if (node.id) onRemoveNodeAutomation?.(node.id);+ }+ mutate(chain.nodes.filter((n) => !n.fromCarve));+ setOpenNode(null);+ }, [carveNodes, chain.nodes, mutate, onRemoveNodeAutomation]);++ /** Bypass or enable every carve effect at once — the module is the unit. */+ const toggleCarveBypass = useCallback(() => {+ const bypassed = carveNodes.every((n) => n.enabled === false);+ mutate(chain.nodes.map((n) => (n.fromCarve ? { ...n, enabled: bypassed } : n)));+ }, [carveNodes, chain.nodes, mutate]);+const moveNode = useCallback((index: number, delta: number) => {const target = index + delta;@@ -389,24 +643,46 @@ export function FxSection({No effects on this track.</p>) : (- chain.nodes.map((node, i) => (- <FxNodeRow- key={`${node.type}-${i}`}- node={node}- index={i}- automatedTargets={automatedTargets}- onAutomateParam={onAutomateParam}- onRemoveParamAutomation={onRemoveParamAutomation}- open={openNode === i}- last={i === chain.nodes.length - 1}- disabled={disabled}- onToggleOpen={() => setOpenNode(openNode === i ? null : i)}- onUpdate={updateNode}- onMove={moveNode}- onRemove={removeNode}- onPreview={previewNode}- />- ))+ chain.nodes.map((node, i) => {+ if (node.fromCarve) {+ // The module stands in for the whole run of carve nodes, drawn once+ // at the first of them.+ const first = chain.nodes.findIndex((n) => n.fromCarve);+ if (i !== first) return null;+ return (+ <FxCarveModule+ key="carve-module"+ nodes={carveNodes}+ automatedTargets={automatedTargets}+ liveAutomationValues={liveAutomationValues}+ open={carveOpen}+ disabled={disabled}+ onToggleOpen={() => setCarveOpen((was) => !was)}+ onToggleBypass={toggleCarveBypass}+ onRemove={removeCarve}+ />+ );+ }+ return (+ <FxNodeRow+ key={`${node.type}-${i}`}+ node={node}+ index={i}+ automatedTargets={automatedTargets}+ liveAutomationValues={liveAutomationValues}+ onAutomateParam={onAutomateParam}+ onRemoveParamAutomation={onRemoveParamAutomation}+ open={openNode === i}+ last={i === chain.nodes.length - 1}+ disabled={disabled}+ onToggleOpen={() => setOpenNode(openNode === i ? null : i)}+ onUpdate={updateNode}+ onMove={moveNode}+ onRemove={removeNode}+ onPreview={previewNode}+ />+ );+ }))}</div>@@ -484,6 +760,12 @@ export function FxSection({))}</select></label>+ {/* One knob for the whole effect. Depth, band count, width, the+ intelligibility weighting and both level-match numbers move+ together anyway — a gentle carve is shallow in few bands with+ little ducking, a hard one is deeper in more with more — so the+ panel sets the strength and `carveProfile` derives the six+ numbers the analysis works in. */}<FxParamRowparam={{kind: "number",@@ -492,23 +774,40 @@ export function FxSection({unit: "",min: 0,max: 1,- step: 0.01,+ step: 0.05,default: DEFAULT_CARVE.strength,- hint: "How hard to carve. The six numbers the analysis actually uses — depth, band count, width and the rest — all move together from this one control.",+ hint: "How hard to carve: deeper cuts, in more bands, and more room made by dropping the bed's level under the voice. At 0 it carves frequencies only. Moving this re-applies an existing carve; the button is for the first one, or after changing the voice track.",}}value={carve.strength}disabled={disabled}onChange={(_k, v) => previewCarve({ ...carve, strength: Number(v) })}onCommit={(_k, v) => onCarveChange({ ...carve, strength: Number(v) })}/>- <button- type="button"- className="hf-fx-analyse mt-1 w-full rounded-[3px] bg-panel-surface py-1 text-[10px] text-panel-text-1 hover:text-panel-text-0 disabled:opacity-40"- disabled={disabled || analysing || !carve.source || !onAnalyseCarve}- onClick={() => onAnalyseCarve?.()}- >- {analysing ? "Analysing…" : "Analyse and apply"}- </button>+ {/* A static carve holds its cuts for the whole clip, pauses+ included. Dynamic hands every value to an envelope of the voice's+ own level, so the bed is only worked on while there is something+ to make room for. Written as ordinary automation, which is why the+ lanes show up in the timeline and can be edited afterwards. */}+ <label className="hf-fx-row flex min-h-6 items-center gap-2">+ <span className="hf-fx-label w-[86px] flex-shrink-0 truncate text-[10px] text-panel-text-4">+ Dynamic+ </span>+ <input+ type="checkbox"+ className="hf-fx-carve-dynamic h-3 w-3 accent-panel-accent"+ checked={carve.dynamic}+ disabled={disabled}+ onChange={(e) => onCarveChange({ ...carve, dynamic: e.target.checked })}+ />+ <span className="min-w-0 flex-1 truncate text-[9px] text-panel-text-4">+ follows the voice, flat where it is silent+ </span>+ </label>+ {analysing ? (+ <p className="hf-fx-carve-working py-1 text-center text-[10px] text-panel-text-4">+ Analysing…+ </p>+ ) : null}</>) : null}</div>diff --git a/packages/studio/src/hooks/useAutomationSelectionKeyboard.test.tsx b/packages/studio/src/hooks/useAutomationSelectionKeyboard.test.tsxindex 6fb1230447..87fb8523df 100644--- a/packages/studio/src/hooks/useAutomationSelectionKeyboard.test.tsx+++ b/packages/studio/src/hooks/useAutomationSelectionKeyboard.test.tsx@@ -20,8 +20,8 @@ import type { TimelineElement } from "../player/store/timelineElement";* A selection box spanning the lane's whole value axis.** What almost every test here is about is the time span — which breakpoints a- * Delete or a copy covers. Giving these an unbounded axis keeps the fixture- * out of the way of that.+ * Delete or a copy covers. The box's value bounds have their own tests; giving+ * these an unbounded axis keeps them testing the one thing they name.*/function wholeAxis<T extends { t0: number; t1: number }>(sel: T): T & { v0: number; v1: number } {return { ...sel, v0: Number.NEGATIVE_INFINITY, v1: Number.POSITIVE_INFINITY };@@ -117,7 +117,11 @@ describe("useAutomationSelectionKeyboard", () => {return { onCommit };};- it("Delete empties the selected range and pins anchors", () => {+ it("Delete removes every breakpoint the selection covers", () => {+ // Deleted, not emptied. Pinning anchors at the selection's edges keeps the+ // envelope either side from moving, which is right for a shape insert or a+ // paste — but answering "delete these points" with two NEW points at the edges+ // reads as the delete not having worked.usePlayerStore.setState({ elements: [bgmElement], selectedElementId: "bgm" });usePlayerStore.getState()@@ -126,7 +130,69 @@ describe("useAutomationSelectionKeyboard", () => {key("Delete");const written = onCommit.mock.calls.at(-1)?.[0];const points = written?.lanes?.[0]?.points ?? [];- expect(points.map((p: { t: number }) => p.t)).toEqual([0, 1, 3, 4]);+ // The fixture lane is 0, 2, 4: only t=2 was inside.+ expect(points.map((p: { t: number }) => p.t)).toEqual([0, 4]);+ });++ it("Delete leaves a point the box's value bounds exclude", () => {+ // The box spans the whole clip but only its top, so Delete takes the one+ // breakpoint up there and nothing else. A time range could not express this.+ usePlayerStore.setState({ elements: [bgmElement], selectedElementId: "bgm" });+ usePlayerStore.getState().setAutomationSelection({+ elementKey: "bgm",+ target: "volume",+ t0: 0,+ t1: 4,+ v0: 0.9,+ v1: 1,+ });+ const { onCommit } = setup({});+ key("Delete");+ const written = onCommit.mock.calls.at(-1)?.[0];+ const points = written?.lanes?.[0]?.points ?? [];+ // Fixture is (0, v=1), (2, v=0.5), (4, v=0): only the first was in the box.+ expect(points.map((p: { t: number }) => p.t)).toEqual([2, 4]);+ });++ it("Delete takes points sitting exactly on the selection's edges", () => {+ // Endpoint-inclusive, matching the copy path: a point the selection was dragged+ // over is inside it, edge or not. Every range operation leaves a breakpoint+ // exactly on an edge, so excluding them would leave those behind every time.+ usePlayerStore.setState({ elements: [bgmElement], selectedElementId: "bgm" });+ usePlayerStore+ .getState()+ .setAutomationSelection(wholeAxis({ elementKey: "bgm", target: "volume", t0: 2, t1: 4 }));+ const { onCommit } = setup({});+ key("Delete");+ const points = onCommit.mock.calls.at(-1)?.[0]?.lanes?.[0]?.points ?? [];+ expect(points.map((p: { t: number }) => p.t)).toEqual([0]);+ });++ it("Delete over a stretch with no breakpoints writes nothing at all", () => {+ // A no-op rather than a write: emptying a span that had nothing in it used to+ // push an undo entry that changed nothing but the anchors it invented.+ usePlayerStore.setState({ elements: [bgmElement], selectedElementId: "bgm" });+ usePlayerStore+ .getState()+ .setAutomationSelection(wholeAxis({ elementKey: "bgm", target: "volume", t0: 2.5, t1: 3.5 }));+ const { onCommit } = setup({});+ const e = new KeyboardEvent("keydown", { key: "Delete", bubbles: true, cancelable: true });+ act(() => void document.dispatchEvent(e));+ expect(onCommit).not.toHaveBeenCalled();+ expect(e.defaultPrevented).toBe(false);+ });++ it("Delete clears the lane when the selection covers all of it", () => {+ usePlayerStore.setState({ elements: [bgmElement], selectedElementId: "bgm" });+ usePlayerStore+ .getState()+ .setAutomationSelection(wholeAxis({ elementKey: "bgm", target: "volume", t0: 0, t1: 6 }));+ const { onCommit } = setup({});+ key("Delete");+ const written = onCommit.mock.calls.at(-1)?.[0];+ // withLane drops a lane with no points left, so the attribute goes empty and+ // the clip is back to its plain data-volume.+ expect(written?.lanes ?? []).toEqual([]);});it("Escape clears the selection", () => {@@ -194,8 +260,10 @@ describe("useAutomationSelectionKeyboard", () => {target: "volume",t0: 5,t1: 7,- v0: VOLUME_RANGE.min,- v1: VOLUME_RANGE.max,+ // Full height: everything the paste landed is selected, so Delete straight+ // after undoes it in one press.+ v0: 0,+ v1: 1,});});@@ -231,8 +299,10 @@ describe("useAutomationSelectionKeyboard", () => {target: "volume",t0: 4,t1: 6,- v0: VOLUME_RANGE.min,- v1: VOLUME_RANGE.max,+ // Full height: everything the paste landed is selected, so Delete straight+ // after undoes it in one press.+ v0: 0,+ v1: 1,});});@@ -267,8 +337,10 @@ describe("useAutomationSelectionKeyboard", () => {target: "volume",t0: 4,t1: 6,- v0: VOLUME_RANGE.min,- v1: VOLUME_RANGE.max,+ // Full height: everything the paste landed is selected, so Delete straight+ // after undoes it in one press.+ v0: 0,+ v1: 1,});});diff --git a/packages/studio/src/hooks/useAutomationSelectionKeyboard.ts b/packages/studio/src/hooks/useAutomationSelectionKeyboard.tsindex 8dfb9704ac..5e73ab52f8 100644--- a/packages/studio/src/hooks/useAutomationSelectionKeyboard.ts+++ b/packages/studio/src/hooks/useAutomationSelectionKeyboard.ts@@ -1,8 +1,8 @@/*** Keyboard surface for the active automation selection: Escape clears,- * Delete/Backspace empties the range (anchors pinned, envelope outside- * untouched), Cmd/Ctrl+C copies it, Cmd/Ctrl+V pastes at the selection's- * start (or the playhead) onto the selected clip's lane. Sibling of+ * Delete/Backspace deletes every breakpoint inside the selection box, Cmd/Ctrl+C+ * copies its span, Cmd/Ctrl+V pastes at the selection's start (or the playhead) onto the+ * selected clip's lane. Sibling of* useKeyframeKeyboard and copies its contract: capture phase so playback* shortcuts cannot swallow keys we act on, inert while any text input has* focus, and a key is only consumed when it does something.@@ -16,7 +16,7 @@import { useEffect } from "react";import { usePlayerStore, type TimelineElement } from "../player/store/playerStore";import { laneFor, withLane } from "../player/components/automationLaneGeometry";-import { replaceRange } from "../player/components/automationLaneSelection";+import { pointInSelection, replaceRange } from "../player/components/automationLaneSelection";import {copyRange,isLastPasteSpan,@@ -87,11 +87,22 @@ function resolveSelectionContext(}/**- * The write that empties the active selection, or null when there is nothing- * to do: the clip is gone, its lane is read-only, the target no longer- * resolves to a range, or the lane already has no points in it. Split out of- * the keydown handler so each stays under the complexity a single branch of- * keyboard dispatch should carry.+ * The write that deletes the breakpoints inside the active selection, or null when+ * there is nothing to do: the clip is gone, its lane is read-only, the target no+ * longer resolves to a range, or the selection covers no breakpoints.+ *+ * Deletes them outright rather than emptying the span behind anchor points. Anchors+ * are what `replaceRange` exists for, and they are right for a shape insert or a+ * paste — the envelope either side of the edit must not move. But Delete over a+ * selection is the author saying "these points, gone", and answering that with two+ * NEW points at the selection's edges reads as the delete not having worked. The+ * envelope between the surviving neighbours re-interpolates, which is what deleting+ * a breakpoint means everywhere else in the lane (right-clicking one does exactly+ * this).+ *+ * Both axes of the selection box, edges included: what Delete removes is exactly+ * what the lane drew a ring around. A point at the right time but outside the box's+ * value bounds stays — which is the whole reason the box has them.*/function resolveDeleteWrite(state: PlayerState,@@ -99,14 +110,12 @@ function resolveDeleteWrite(sel: AutomationSelection,): { onCommit(next: HfAutomation): void; next: HfAutomation } | null {const ctx = resolveSelectionContext(state, lanes, sel);- if (!ctx || ctx.lane.points.length === 0) return null;- const points = replaceRange({- lane: ctx.lane,- range: ctx.range,- t0: sel.t0,- t1: sel.t1,- inner: [],- });+ if (!ctx) return null;+ const points = ctx.lane.points.filter((p) => !pointInSelection(p, sel));+ // Nothing inside is nothing to do — and it must stay a no-op rather than+ // writing, or Delete over a smooth stretch would push an undo entry that+ // changed nothing.+ if (points.length === ctx.lane.points.length) return null;return {onCommit: ctx.binding.onCommit,next: withLane(ctx.binding.automation, { target: sel.target, points }),@@ -246,9 +255,9 @@ function handlePaste(paste.binding.onCommit(withLane(paste.binding.automation, { target: paste.target, points }));// Select the pasted span — the only feedback that it landed — and mark it, so// an immediate second Cmd+V recognises this selection as the paste's own and- // chains right after it instead of overwriting it. Full-height box over the- // pasted span: this path only ever reads t0/t1, so the box's value bounds are- // cosmetic — but the parameter's own range keeps it a sensible box to draw.+ // chains right after it instead of overwriting it.+ // Full-height box over the pasted span: everything that landed is selected, so+ // Delete straight after a paste undoes it in one press.const mark = {elementKey: paste.elementKey,target: paste.target,diff --git a/packages/studio/src/hooks/useDomEditAttributeCommits.ts b/packages/studio/src/hooks/useDomEditAttributeCommits.tsindex 7b7a96de93..7d72bd9620 100644--- a/packages/studio/src/hooks/useDomEditAttributeCommits.ts+++ b/packages/studio/src/hooks/useDomEditAttributeCommits.ts@@ -394,7 +394,19 @@ export function useDomEditAttributeCommits({},onError: (error) => reportDomEditPersistFailure(domEditSelection, [op], error, showToast),shouldResync: () => isLatestCommit(),- resync: () => refreshDomEditSelectionFromPreview(domEditSelection),+ resync: () => {+ refreshDomEditSelectionFromPreview(domEditSelection);+ // The player store keeps its own copy of each element's attributes, and+ // that copy is what the timeline's automation lanes draw from. Nothing+ // else refreshes it: a commit patches the preview document and the file,+ // and resyncs the dom-edit SELECTION for the panel. So every writer that+ // did not also update the store by hand — the FX panel's automate and+ // un-automate buttons, the keyboard Delete, a paste — changed the file and+ // the audio while the lane went on drawing what it had, until a reload.+ // One sink here rather than a sync in each writer, because three of them+ // shipped without one.+ syncStoredAutomationFromPreview(previewIframeRef.current?.contentDocument ?? null);+ },});},[diff --git a/packages/studio/src/hooks/useDomEditCommits.test.tsx b/packages/studio/src/hooks/useDomEditCommits.test.tsxindex cf548aaf76..0dac41195f 100644--- a/packages/studio/src/hooks/useDomEditCommits.test.tsx+++ b/packages/studio/src/hooks/useDomEditCommits.test.tsx@@ -1338,6 +1338,44 @@ describe("useDomEditCommits attribute persist handling", () => {}});+ it("applies a preview-only write without persisting it", async () => {+ // What a drag needs from every pointermove: the preview and the audio graph+ // follow, the file does not. Persisting each move filled the undo stack with+ // fragments of one gesture — and because those writes race, a follow-up's+ // "before" often was not the previous entry's "after", so history refused to+ // coalesce them and undo took back a few milliseconds of the drag.+ const fetchSpy = stubPatchFetch({ ok: true, changed: true, matched: true });+ const { iframe, element } = createPreviewElement();+ const rendered = renderDomEditCommits(createSelection(element), iframe);++ try {+ await act(async () => {+ await rendered.hook.handleDomAttributeLiveCommit("volume", "0.7", undefined, {+ previewOnly: true,+ });+ });+ expect(element.getAttribute("data-volume")).toBe("0.7");+ expect(fetchSpy).not.toHaveBeenCalled();+ } finally {+ rendered.cleanup();+ }+ });++ it("still persists a live write that does not ask to be preview-only", async () => {+ const fetchSpy = stubPatchFetch({ ok: true, changed: true, matched: true });+ const { iframe, element } = createPreviewElement();+ const rendered = renderDomEditCommits(createSelection(element), iframe);++ try {+ await act(async () => {+ await rendered.hook.handleDomAttributeLiveCommit("volume", "0.7");+ });+ expect(fetchSpy).toHaveBeenCalled();+ } finally {+ rendered.cleanup();+ }+ });+it("keeps a data-attribute commit on success", async () => {stubPatchFetch({ok: true,diff --git a/packages/studio/src/hooks/useLivePlayheadTime.ts b/packages/studio/src/hooks/useLivePlayheadTime.tsnew file mode 100644index 0000000000..72c0d2972b--- /dev/null+++ b/packages/studio/src/hooks/useLivePlayheadTime.ts@@ -0,0 +1,49 @@+/**+ * The playhead in composition seconds, live while the transport runs.+ *+ * The RAF loop deliberately does not push every frame through the store — it+ * notifies `liveTime` instead, so the playhead can move without re-rendering the+ * app. A panel that wants to follow it therefore has to subscribe itself, and+ * throttle: 30 Hz reads as continuous and costs an order of magnitude less than a+ * render per frame.+ *+ * Paused, the store is the truth — a seek or a scrub lands there — so this returns+ * that instead, which is what lets a readout follow the playhead while it is being+ * dragged as well as while it is playing.+ */+import { useEffect, useRef, useState } from "react";+import { liveTime, usePlayerStore } from "../player";++/** Long enough to be much cheaper than a frame, short enough to read as motion. */+const THROTTLE_MS = 33;++export function useLivePlayheadTime(): number {+ const storeTime = usePlayerStore((s) => s.currentTime);+ const isPlaying = usePlayerStore((s) => s.isPlaying);+ const liveRef = useRef(storeTime);+ const [, forceRender] = useState(0);++ // Paused, the ref tracks the store so the first frame of playback is never a+ // stale value from the last time the transport ran.+ if (!isPlaying) liveRef.current = storeTime;++ useEffect(() => {+ if (!isPlaying) return;+ let timerId: ReturnType<typeof setTimeout> | 0 = 0;+ const unsubscribe = liveTime.subscribe((t) => {+ liveRef.current = t;+ if (!timerId) {+ timerId = setTimeout(() => {+ timerId = 0;+ forceRender((v) => v + 1);+ }, THROTTLE_MS);+ }+ });+ return () => {+ unsubscribe();+ if (timerId) clearTimeout(timerId);+ };+ }, [isPlaying]);++ return isPlaying ? liveRef.current : storeTime;+}diff --git a/packages/studio/src/hooks/usePreviewPersistence.ts b/packages/studio/src/hooks/usePreviewPersistence.tsindex 608220eda2..ee7039231f 100644--- a/packages/studio/src/hooks/usePreviewPersistence.ts+++ b/packages/studio/src/hooks/usePreviewPersistence.ts@@ -14,6 +14,7 @@ import {import { trackStudioEvent } from "../utils/studioTelemetry";import { applyUndoRestoreToPreview, type UndoRestoreFile } from "../utils/gsapUndoRestore";import { usePlayerStore } from "../player";+import { syncStoredAutomationFromPreview } from "../player/lib/automationStoreSync";/** The restore payload the undo/redo preview-sync consumes (from the history store). */interface HistoryPreviewRestore {@@ -207,7 +208,13 @@ export function usePreviewPersistence({player.setElements([]);player.setSelectedElementId(null);player.setTimelineReady(false);+ return;}+ // A soft restore patched the reverted attributes onto the live preview, but the+ // player store keeps its own copy and that copy is what the automation lanes+ // draw — so without this an undone envelope edit stayed invisible until a+ // reload. The full path above clears the store and waits for discovery instead.+ syncStoredAutomationFromPreview(previewIframeRef.current?.contentDocument ?? null);},[previewIframeRef, activeCompPathRef, reloadPreview],);diff --git a/packages/studio/src/player/components/automationLaneData.ts b/packages/studio/src/player/components/automationLaneData.tsindex e62b8b7324..c1c8c850c7 100644--- a/packages/studio/src/player/components/automationLaneData.ts+++ b/packages/studio/src/player/components/automationLaneData.ts@@ -131,7 +131,7 @@ function orderLanes(lanes: HfAutomationLane[], chain: HfAudioFxChain | null): Hf}/** A frequency as an author reads it: 400 Hz, 1.6 kHz, 10 kHz. */-function formatHz(freq: number): string {+export function formatHz(freq: number): string {if (freq < 1000) return `${Math.round(freq)} Hz`;const k = freq / 1000;return `${k >= 10 ? Math.round(k) : Number(k.toFixed(1))} kHz`;