Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(core): make audio automation survive being rescheduled (#3208)
Vance Ingalls69face9dc6a8
diff --git a/packages/core/src/audio/audioFxAutomation.test.ts b/packages/core/src/audio/audioFxAutomation.test.tsindex d8748f9f45..c6c92cecf1 100644--- a/packages/core/src/audio/audioFxAutomation.test.ts+++ b/packages/core/src/audio/audioFxAutomation.test.ts@@ -2,6 +2,7 @@import { describe, expect, it } from "vitest";import {cancelParamLane,+ clearParamLane,scheduleChainAutomation,scheduleParamLane,volumeLane,@@ -63,12 +64,33 @@ const ramp: HfAutomationLane = {],};+const curvedRamp: HfAutomationLane = {+ target: "volume",+ points: [+ { t: 0, v: 0, curve: 1 },+ { t: 2, v: 1 },+ ],+};++/** Schedule `curvedRamp` and return the fake param it wrote to — the setup+ * three tests below share, each checking something different about the+ * curve it produces. */+function scheduleCurved(): { target: FxParamTarget; param: FakeParam } {+ const { target, param } = fake();+ scheduleParamLane([target], curvedRamp, "linear", at(0));+ return { target, param };+}+describe("scheduleParamLane", () => {it("seeds the current value, then ramps to each later point", () => {const { target, param } = fake();scheduleParamLane([target], ramp, "linear", at(0));expect(param.calls).toEqual([- { op: "cancel", time: 10 },+ // Cleared from zero, not held: holding leaves the span of a running curve+ // booked, and Chrome refuses the next curve — or a plain `.value` write —+ // that lands inside it. The seed below restores the value in the same pass,+ // so clearing costs nothing audible.+ { op: "cancel", time: 0 },// Before the first point the envelope holds that point's value.{ op: "set", value: 0.2, time: 10 },{ op: "ramp", value: 0.8, time: 13 },@@ -87,7 +109,7 @@ describe("scheduleParamLane", () => {const { target, param } = fake();scheduleParamLane([target], ramp, "linear", at(9));expect(param.calls).toEqual([- { op: "cancel", time: 10 },+ { op: "cancel", time: 0 },{ op: "set", value: 0.8, time: 10 },]);});@@ -122,19 +144,36 @@ describe("scheduleParamLane", () => {at(0),);expect(param.calls).toEqual([- { op: "cancel", time: 10 },+ { op: "cancel", time: 0 },{ op: "set", value: 0.4, time: 10 },]);});it("samples a curved segment rather than ramping through the bend", () => {+ const { param } = scheduleCurved();+ const curve = param.calls.find((c) => c.op === "curve");+ expect(curve).toBeTruthy();+ if (curve?.op !== "curve") throw new Error("expected a curve");+ expect(curve.time).toBe(10);+ expect(curve.duration).toBe(2);+ expect(curve.values[0]).toBeCloseTo(0, 6);+ expect(curve.values[curve.values.length - 1]).toBeCloseTo(1, 6);+ // Curved, so the midpoint is not halfway.+ expect(curve.values[Math.floor(curve.values.length / 2)]).toBeLessThan(0.4);+ });++ it("samples a segment bent by a via point, not just one bent by `curve`", () => {+ // Both express the same thing — a segment that is not a straight line — and+ // the via form is what the timeline writes when a bend is dragged. Read as+ // straight, the whole bend was played as a linear ramp: the envelope drawn in+ // the lane and the envelope heard were different shapes.const { target, param } = fake();scheduleParamLane([target],{target: "volume",points: [- { t: 0, v: 0, curve: 1 },+ { t: 0, v: 0, viaX: 0.5, viaY: 0.9 },{ t: 2, v: 1 },],},@@ -142,14 +181,10 @@ describe("scheduleParamLane", () => {at(0),);const curve = param.calls.find((c) => c.op === "curve");- expect(curve).toBeTruthy();+ expect(curve, "a via-bent segment must be sampled, not ramped").toBeTruthy();if (curve?.op !== "curve") throw new Error("expected a curve");- expect(curve.time).toBe(10);- expect(curve.duration).toBe(2);- expect(curve.values[0]).toBeCloseTo(0, 6);- expect(curve.values[curve.values.length - 1]).toBeCloseTo(1, 6);- // Curved, so the midpoint is not halfway.- expect(curve.values[Math.floor(curve.values.length / 2)]).toBeLessThan(0.4);+ // Through the via point: 90% of the way up at the halfway mark.+ expect(curve.values[Math.floor(curve.values.length / 2)]).toBeGreaterThan(0.8);});it("samples a log-scaled sweep, which a linear ramp would get wrong", () => {@@ -180,19 +215,7 @@ describe("scheduleParamLane", () => {});it("does not seed on top of a curve that starts at the same instant", () => {- const { target, param } = fake();- scheduleParamLane(- [target],- {- target: "volume",- points: [- { t: 0, v: 0, curve: 1 },- { t: 2, v: 1 },- ],- },- "linear",- at(0),- );+ const { param } = scheduleCurved();// A value curve may not overlap another event, so there is no set at 10.expect(param.calls.filter((c) => c.op === "set")).toEqual([]);expect(param.calls[1]?.op).toBe("curve");@@ -232,6 +255,238 @@ describe("scheduleParamLane", () => {});});+/**+ * An AudioParam with Chrome's own overlap rule, and its own cancel semantics.+ *+ * The distinction that matters: `cancelScheduledValues(t)` drops events at or+ * after `t` but leaves a value curve that is already running — the spec only+ * special-cases an in-progress curve for `cancelAndHoldAtTime`, which truncates+ * it. Schedule a curve inside one that is still live and the browser throws.+ */+class OverlapAwareParam {+ curves: { time: number; duration: number }[] = [];+ value = 0;+ setValueAtTime(): void {}+ linearRampToValueAtTime(): void {}+ setValueCurveAtTime(_values: Float32Array, time: number, duration: number): void {+ const clash = this.curves.find((c) => time < c.time + c.duration && time + duration > c.time);+ if (clash) {+ throw new Error(+ `Failed to execute 'setValueCurveAtTime' on 'AudioParam': ` ++ `setValueCurveAtTime(..., ${time}, ${duration}) overlaps ` ++ `setValueCurveAtTime(..., ${clash.time}, ${clash.duration})`,+ );+ }+ this.curves.push({ time, duration });+ }+ cancelScheduledValues(time: number): void {+ // Events at or after the cancel; a curve already under way is untouched.+ this.curves = this.curves.filter((c) => c.time < time);+ }+ cancelAndHoldAtTime(time: number): void {+ this.curves = this.curves+ .filter((c) => c.time < time)+ .map((c) => ({ time: c.time, duration: Math.min(c.duration, time - c.time) }));+ }+}++describe("rescheduling over a curve that is still playing", () => {+ const bent: HfAutomationLane = {+ target: "volume",+ points: [+ { t: 0, v: 1, curve: 1 },+ { t: 8, v: 0.2, curve: 1 },+ { t: 12, v: 1 },+ ],+ };++ it("takes over from an in-progress curve instead of throwing", () => {+ // Two schedule passes a few milliseconds apart is ordinary: an attribute edit+ // lands, the graph is re-parameterised, and the envelope is re-aimed at the+ // live playhead. The second pass has to displace the curve the first one+ // started, which `cancelScheduledValues` does not do for a curve that is+ // already running — the browser then refuses the new curve outright.+ const param = new OverlapAwareParam();+ const target = { param: param as unknown as AudioParam };+ scheduleParamLane([target], bent, "linear", at(0, 1, 9.109333));+ expect(() =>+ scheduleParamLane([target], bent, "linear", at(0.005334, 1, 9.114667)),+ ).not.toThrow();+ });++ it("survives a burst of reschedules, as a dragged knob produces", () => {+ const param = new OverlapAwareParam();+ const target = { param: param as unknown as AudioParam };+ for (let i = 0; i < 12; i++) {+ const when = 9.1 + i * 0.005;+ expect(() =>+ scheduleParamLane([target], bent, "linear", at(i * 0.005, 1, when)),+ ).not.toThrow();+ }+ });+});++describe("a curve the browser refuses", () => {+ /**+ * A param that rejects any curve overlapping one it has been given, and — like+ * Chrome — keeps counting a held curve's original span. Holding stops what is+ * audible; it does not free the slot for overlap checking.+ */+ class UnforgivingParam {+ curves: { time: number; duration: number }[] = [];+ ramps: { time: number; value: number }[] = [];+ sets: { time: number; value: number }[] = [];+ value = 0;+ setValueAtTime(value: number, time: number): void {+ this.sets.push({ time, value });+ }+ linearRampToValueAtTime(value: number, time: number): void {+ this.ramps.push({ time, value });+ }+ setValueCurveAtTime(_v: Float32Array, time: number, duration: number): void {+ const clash = this.curves.find((c) => time < c.time + c.duration && time + duration > c.time);+ if (clash) {+ throw new Error(+ `Failed to execute 'setValueCurveAtTime' on 'AudioParam': ` ++ `setValueCurveAtTime(..., ${time}, ${duration}) overlaps ` ++ `setValueCurveAtTime(..., ${clash.time}, ${clash.duration})`,+ );+ }+ this.curves.push({ time, duration });+ }+ // Measured against Chrome, in a live running context and in an offline one+ // suspended mid-curve: either cancel frees the span of a curve already under+ // way, so only a write with no cancel at all is refused.+ cancelScheduledValues(time: number): void {+ this.curves = this.curves.filter((c) => c.time + c.duration < time);+ }+ cancelAndHoldAtTime(time: number): void {+ this.cancelScheduledValues(time);+ }+ }++ const bent: HfAutomationLane = {+ target: "volume",+ points: [+ { t: 0, v: 1, curve: 1 },+ { t: 0.25, v: 0.4, curve: 1 },+ { t: 0.6, v: 1, curve: 1 },+ { t: 1.2, v: 0.3 },+ ],+ };++ it("reschedules mid-playback with its curves intact", () => {+ // Applying a carve while the transport runs reschedules into curves that are+ // already playing — one render quantum apart is the common case. Cancelling+ // the parameter first is what lets the new pass keep its shape instead of+ // being refused; this does not discriminate the strength of the cancel, which+ // the no-cancel test below is for.+ const param = new UnforgivingParam();+ const target = { param: param as unknown as AudioParam };+ scheduleParamLane([target], bent, "linear", at(0, 1, 1492.016));+ const first = param.curves.length;+ expect(() =>+ scheduleParamLane([target], bent, "linear", at(0.005333, 1, 1492.021333)),+ ).not.toThrow();+ expect(param.curves.length).toBeGreaterThan(0);+ // Curves, not ramps: nothing had to be degraded.+ expect(param.ramps).toHaveLength(0);+ expect(first).toBeGreaterThan(0);+ });++ it("still degrades to a ramp where the span cannot be freed at all", () => {+ // The last line of defence, for a hypothetical param that refuses to give the+ // span up. No engine has been measured behaving this way; it stands in for the+ // unexplained curve-over-curve refusals reported from the field. The envelope+ // loses a bend rather than the exception escaping and abandoning the rest.+ class ImmovableParam extends UnforgivingParam {+ override cancelScheduledValues(): void {+ // Nothing is ever freed.+ }+ }+ const param = new ImmovableParam();+ const target = { param: param as unknown as AudioParam };+ scheduleParamLane([target], bent, "linear", at(0, 1, 100));+ expect(() =>+ scheduleParamLane([target], bent, "linear", at(0.005333, 1, 100.005333)),+ ).not.toThrow();+ expect(param.ramps.length).toBeGreaterThan(0);+ });+});++describe("a curve that starts at this very instant", () => {+ /**+ * Chrome's behaviour at the boundary, which is where this bit: holding at a+ * time does not free a curve that *begins* at that time, so both a fresh curve+ * and a plain `.value` write at the same instant are refused. Only a cancel+ * clears it.+ */+ class BoundaryParam {+ curves: { time: number; duration: number }[] = [];+ #value = 0;+ constructor(private clock: { currentTime: number }) {}+ get value(): number {+ return this.#value;+ }+ set value(v: number) {+ const t = this.clock.currentTime;+ const clash = this.curves.find((c) => t >= c.time && t <= c.time + c.duration);+ if (clash) {+ throw new Error(+ `Failed to set the 'value' property on 'AudioParam': setValueAtTime(${v}, ${t}) ` ++ `overlaps setValueCurveAtTime(..., ${clash.time}, ${clash.duration})`,+ );+ }+ this.#value = v;+ }+ setValueAtTime(v: number): void {+ this.#value = v;+ }+ linearRampToValueAtTime(): void {}+ setValueCurveAtTime(_v: Float32Array, time: number, duration: number): void {+ this.curves.push({ time, duration });+ }+ // As Chrome behaves: either cancel frees a running curve's span.+ cancelScheduledValues(time: number): void {+ this.curves = this.curves.filter((c) => c.time + c.duration < time);+ }+ cancelAndHoldAtTime(time: number): void {+ this.cancelScheduledValues(time);+ }+ }++ const bent: HfAutomationLane = {+ target: "volume",+ points: [+ { t: 0, v: 1, curve: 1 },+ { t: 0.04, v: 0.2, curve: 1 },+ { t: 4, v: 1 },+ ],+ };++ it("clears the booked span so the next pass can schedule at all", () => {+ const clock = { currentTime: 91.069 };+ const param = new BoundaryParam(clock);+ const target = { param: param as unknown as AudioParam };+ scheduleParamLane([target], bent, "linear", at(0, 1, 91.069));+ expect(() => scheduleParamLane([target], bent, "linear", at(0, 1, 91.069))).not.toThrow();+ });++ it("leaves the parameter writable, which is what a chain edit does next", () => {+ // The re-parameterise after an edit writes every knob straight onto its param.+ // Landing inside a span the scheduler booked at this instant is the error the+ // console kept reporting, with the gain stage's own unity value in it.+ const clock = { currentTime: 91.069 };+ const param = new BoundaryParam(clock);+ const target = { param: param as unknown as AudioParam };+ scheduleParamLane([target], bent, "linear", at(0, 1, 91.069));+ clearParamLane([target]);+ expect(() => {+ (param as unknown as { value: number }).value = 1;+ }).not.toThrow();+ });+});+describe("cancelParamLane", () => {it("holds the value the envelope had reached rather than snapping back", () => {const { target, param } = fake();diff --git a/packages/core/src/audio/audioFxAutomation.ts b/packages/core/src/audio/audioFxAutomation.tsindex 766c14ece8..94e7cca6b2 100644--- a/packages/core/src/audio/audioFxAutomation.ts+++ b/packages/core/src/audio/audioFxAutomation.ts@@ -14,6 +14,7 @@ import {sampleAutomationLane,type HfAutomation,type HfAutomationLane,+ type HfAutomationPoint,} from "../audioAutomation.js";import { parseAutomationTarget, VOLUME_TARGET } from "../audioAutomation.js";import type { HfAudioFxChain } from "../audioFx.js";@@ -46,16 +47,23 @@ type Op =| { kind: "curve"; time: number; duration: number; values: Float32Array };/**- * A segment is a straight line only when nothing bends it: no curvature on the- * point it leaves, a linear parameter scale, and no unit mapping that could be- * non-linear. Everything else is sampled.+ * A segment is a straight line only when nothing bends it: no curvature and no+ * via point on the point it leaves, a linear parameter scale, and no unit+ * mapping that could be non-linear. Everything else is sampled.+ *+ * Both bend forms have to be checked. `curve` is an exponent; a via point names+ * an interior point the segment passes through, and it is what the timeline+ * writes when a bend is dragged. Testing only the exponent read every dragged+ * bend as straight and played it as a linear ramp — the lane drew one shape and+ * the ear got another.*/function isStraight(- curve: number | undefined,+ point: Pick<HfAutomationPoint, "curve" | "viaX" | "viaY">,scale: "linear" | "log",map: FxParamTarget["map"],): boolean {- return !curve && scale === "linear" && !map;+ const bent = Boolean(point.curve) || (point.viaX !== undefined && point.viaY !== undefined);+ return !bent && scale === "linear" && !map;}function curvePointCount(duration: number): number {@@ -86,7 +94,7 @@ function segmentOp(const duration = toTime - fromTime;if (duration <= 0) return null;- if (isStraight(a.curve, scale, map)) {+ if (isStraight(a, scale, map)) {return { kind: "ramp", time: toTime, value: apply(b.v) };}// Sample from wherever the segment is entered, which is mid-segment when the@@ -128,11 +136,66 @@ function planOps(return ops;}+/**+ * Hand the plan to the AudioParam, degrading a curve the browser will not take.+ *+ * A value curve may not overlap another, and this has been seen refused in the+ * field while rescheduling mid-playback — two passes landing a render quantum+ * apart, which is what applying a carve while the transport runs does. Every+ * caller here cancels the parameter first, and measured against Chrome that is+ * enough to free even a curve already under way, so the mechanism behind those+ * reports is not understood and does not reproduce. This catch is the backstop+ * for it: unhandled, the exception reached the console and abandoned every+ * remaining segment of the envelope.+ *+ * A ramp to the same destination is always accepted, since it books no span. The+ * segment loses its bend until the next full reschedule, which is a far better+ * failure than the rest of the envelope never being scheduled at all.+ */function emit(param: AudioParam, ops: readonly Op[]): void {for (const op of ops) {if (op.kind === "set") param.setValueAtTime(op.value, op.time);else if (op.kind === "ramp") param.linearRampToValueAtTime(op.value, op.time);- else param.setValueCurveAtTime(op.values, op.time, op.duration);+ else {+ try {+ param.setValueCurveAtTime(op.values, op.time, op.duration);+ } catch {+ const end = op.values[op.values.length - 1] ?? 0;+ param.linearRampToValueAtTime(end, op.time + op.duration);+ }+ }+ }+}++/**+ * Drop every event booked on a parameter, including a curve already under way.+ *+ * Anything landing inside a running curve is refused — a fresh curve, or the+ * plain `.value` write that re-parameterising a chain performs — so the param has+ * to be cancelled first. Measured against Chrome, any cancel frees the span; this+ * takes the strongest form on purpose, because curve-over-curve refusals were+ * reported from the field with a cancel at the new schedule time already in place+ * and have never reproduced. Cancelling from zero cannot leave a stale event+ * behind whatever that mechanism is.+ *+ * Safe on these parameters because this scheduler is their only writer: they+ * belong to effect nodes it built, and the caller re-seeds the value in the same+ * breath, so nothing clicks.+ */+export function clearParamLane(targets: readonly FxParamTarget[]): void {+ for (const target of targets) target.param.cancelScheduledValues(0);+}++/** Stop an envelope, leaving the parameter wherever it currently sits. */+export function cancelParamLane(targets: readonly FxParamTarget[], from: number): void {+ for (const target of targets) {+ // Keep the value the ramp had reached rather than snapping back to the+ // last explicitly-set one, which would click.+ if (typeof target.param.cancelAndHoldAtTime === "function") {+ target.param.cancelAndHoldAtTime(from);+ } else {+ target.param.cancelScheduledValues(from);+ }}}@@ -150,7 +213,11 @@ export function scheduleParamLane(): void {if (lane.points.length === 0) return;for (const target of targets) {- target.param.cancelScheduledValues(timing.scheduledAt);+ // Cleared from zero rather than from this instant: a reschedule mid-playback+ // lands inside the previous pass's still-running curve, and the field reports+ // of that being refused had a cancel at this instant already in place. The+ // plan below re-seeds the value here, so clearing costs nothing audible.+ clearParamLane([target]);if (isConstantLane(lane)) {const value = (target.map ?? identity)(lane.points[0]!.v);target.param.setValueAtTime(value, timing.scheduledAt);@@ -160,19 +227,6 @@ export function scheduleParamLane(}}-/** Stop an envelope, leaving the parameter wherever it currently sits. */-export function cancelParamLane(targets: readonly FxParamTarget[], from: number): void {- for (const target of targets) {- // Keep the value the ramp had reached rather than snapping back to the- // last explicitly-set one, which would click.- if (typeof target.param.cancelAndHoldAtTime === "function") {- target.param.cancelAndHoldAtTime(from);- } else {- target.param.cancelScheduledValues(from);- }- }-}-/** One built effect, paired with the chain node id lanes address it by. */export interface AutomatableNode {id?: string;diff --git a/packages/core/src/audio/audioFxGraph.test.ts b/packages/core/src/audio/audioFxGraph.test.tsindex 6339ba5f23..9c54f12bc9 100644--- a/packages/core/src/audio/audioFxGraph.test.ts+++ b/packages/core/src/audio/audioFxGraph.test.ts@@ -342,6 +342,39 @@ describe("levels and per-channel state", () => {});});+describe("gain stage", () => {+ /**+ * A level control the chain owns, so a carve can make broadband room for a+ * voice without touching the track's own volume lane — which belongs to the+ * author, and which a carve re-run would otherwise have to overwrite.+ */+ it("sets a GainNode from a value in dB", () => {+ const c = ctx();+ buildFxNode(c as unknown as BaseAudioContext, "gain", { gain: -6 });+ const node = c.created.find((x) => x.kind === "gain");+ expect(node).toBeTruthy();+ expect(node!.gain.value).toBeCloseTo(0.501, 3);+ });++ it("passes unity through at 0 dB", () => {+ const c = ctx();+ buildFxNode(c as unknown as BaseAudioContext, "gain", { gain: 0 });+ expect(c.created.find((x) => x.kind === "gain")!.gain.value).toBeCloseTo(1, 6);+ });++ it("maps an automation lane's dB into the AudioParam's linear units", () => {+ // The lane is authored in the knob's own unit — dB, like every other gain in+ // the registry — but a GainNode's param is a linear multiplier. Without the+ // mapping, a lane point of -12 would schedule a gain of -12: a phase flip+ // twelve times too loud, not a cut.+ const handle = buildFxNode(ctx() as unknown as BaseAudioContext, "gain", { gain: 0 });+ const target = handle.automation?.gain?.[0];+ expect(target?.map).toBeTypeOf("function");+ expect(target!.map!(-12)).toBeCloseTo(0.251, 3);+ expect(target!.map!(0)).toBeCloseTo(1, 6);+ });+});+describe("automatable parameters", () => {/*** The registry's `automatable` flag is what the panel and the scheduler bothdiff --git a/packages/core/src/audio/audioFxGraph.ts b/packages/core/src/audio/audioFxGraph.tsindex 8c2ce8dfb1..9e5172f82d 100644--- a/packages/core/src/audio/audioFxGraph.ts+++ b/packages/core/src/audio/audioFxGraph.ts@@ -117,6 +117,26 @@ function simple(*/const USES_Q: ReadonlySet<BiquadFilterType> = new Set(["peaking", "highpass", "lowpass"]);+/** dB on the knob, a linear multiplier on the AudioParam. */+const dbToLinear = (db: number): number => Math.pow(10, db / 20);++/**+ * A plain level stage.+ *+ * Every other gain in the registry sits on a BiquadFilterNode, whose `gain`+ * param is already in dB. A GainNode's is a linear multiplier, so both the+ * initial value and anything an automation lane schedules have to be converted —+ * which is what `FxParamTarget.map` is for.+ */+const gainStage: Builder = (ctx, p) => {+ const g = ctx.createGain();+ const apply = (v: HfAudioFxParamValues): void => {+ g.gain.value = dbToLinear(n(v.gain));+ };+ apply(p);+ return simple(g, apply, { gain: [{ param: g.gain, map: dbToLinear }] });+};+function biquad(type: BiquadFilterType, useGain: boolean): Builder {return (ctx, p) => {const f = ctx.createBiquadFilter();@@ -394,6 +414,7 @@ const convolver: Builder = (ctx, p) => {};const BUILDERS: Record<string, Builder> = {+ "gain-node": gainStage,"biquad-peaking": biquad("peaking", true),"biquad-lowshelf": biquad("lowshelf", true),"biquad-highshelf": biquad("highshelf", true),diff --git a/packages/core/src/audioAutomation.test.ts b/packages/core/src/audioAutomation.test.tsindex 4a59caae8a..b73ef35cd9 100644--- a/packages/core/src/audioAutomation.test.ts+++ b/packages/core/src/audioAutomation.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from "vitest";import {applyCurve,+ shapeProgress,fxAutomationTarget,isConstantLane,parseAutomation,@@ -10,6 +11,7 @@ import {sampleAutomationCurve,sampleAutomationLane,serializeAutomation,+ steadyViaPoint,VOLUME_RANGE,type HfAutomationLane,} from "./audioAutomation.js";@@ -152,6 +154,54 @@ describe("normalisation", () => {};expect(parseAutomation(serializeAutomation(source))).toEqual(source);});++ it("round-trips a via point, and keeps it as a pair", () => {+ const source = {+ version: 1,+ lanes: [+ lane([+ // A via point with no `curve` at all: the bend is entirely described by+ // where the segment goes. It has to survive on its own, or a bend+ // dragged near a breakpoint silently straightens on the next load.+ { t: 0, v: 0.8, viaX: 0.7, viaY: 0.6 },+ { t: 2, v: 0.2, curve: 0.5, viaX: 0.3, viaY: 0.44 },+ { t: 3, v: 0.5 },+ ]),+ ],+ };+ expect(parseAutomation(serializeAutomation(source))).toEqual(source);+ });++ it("drops a via point that says nothing, and clamps one off the segment", () => {+ const parsed = parseAutomation(+ JSON.stringify({+ version: 1,+ lanes: [+ {+ target: "volume",+ points: [+ // Half a via point describes no shape; taking one coordinate on its+ // own would leave the segment's shape depending on which half+ // survived a hand edit.+ { t: 0, v: 0.5, viaX: 0.4 },+ // On the diagonal: this IS the straight line, so storing it would+ // claim a bend the segment does not have.+ { t: 1, v: 0.6, viaX: 0.4, viaY: 0.4 },+ // Outside the segment entirely: pulled back to the steady region+ // rather than describing a shape no curve can draw.+ { t: 2, v: 0.7, viaX: 5, viaY: -3 },+ { t: 3, v: 1 },+ ],+ },+ ],+ }),+ );+ const points = parsed.lanes[0]!.points;+ expect(points[0]).not.toHaveProperty("viaX");+ expect(points[1]).not.toHaveProperty("viaX");+ expect(points[2]!.viaX).toBeCloseTo(0.999, 6);+ expect(points[2]!.viaY).toBeCloseTo(0.001, 6);+ });});describe("resolveAutomation", () => {@@ -230,6 +280,227 @@ describe("sampling", () => {expect(applyCurve(0.5, 0)).toBe(0.5);});+ it("leaves a legacy curve-only point sampling exactly as it always did", () => {+ for (const x of [0, 0.1, 0.25, 0.5, 0.75, 0.9, 1]) {+ expect(shapeProgress(x, { curve: 0.5 })).toBe(Math.pow(x, Math.pow(2, 1)));+ }+ expect(shapeProgress(0.5, {})).toBe(0.5);+ });++ it("passes exactly through any via point, however deep or off-centre", () => {+ // The contract the drag depends on: the pointer's position IS the shape. No+ // depth cap and no position cap — an earlier version held bends to a maximum+ // slope, which capped how far the line could be pulled and, worse, could clamp a+ // bend onto the straight line and flatten it mid-drag.+ for (const [vx, vy] of [+ [0.5, 0.7],+ [0.5, 0.95],+ [0.2, 0.8],+ [0.1, 0.9],+ [0.05, 0.95],+ [0.9, 0.15],+ [0.3, 0.05],+ [0.95, 0.55],+ ] as const) {+ expect(shapeProgress(vx, { viaX: vx, viaY: vy })).toBeCloseTo(vy, 6);+ }+ });++ it("puts the curve's furthest point from straight exactly at the via point", () => {+ // "The cursor is the apex": not near it, at it. The conic passes through the via+ // point at its own midparameter, and its two halves are symmetric in parameter,+ // so the deepest departure from the straight line lands there by construction.+ for (const [vx, vy] of [+ [0.1, 0.9],+ [0.2, 0.8],+ [0.5, 0.95],+ [0.8, 0.3],+ [0.9, 0.15],+ [0.95, 0.55],+ ] as const) {+ let deepest = 0;+ let at = 0;+ for (let k = 1; k < 1000; k++) {+ const x = k / 1000;+ const gap = Math.abs(shapeProgress(x, { viaX: vx, viaY: vy }) - x);+ if (gap > deepest) {+ deepest = gap;+ at = x;+ }+ }+ expect(at).toBeCloseTo(vx, 2);+ expect(deepest).toBeCloseTo(Math.abs(vy - vx), 2);+ }+ });++ it("reaches a bend far deeper than a plain quadratic could", () => {+ // A plain quadratic needs its control point at 2Q - M, which leaves the segment+ // once the via point is past the middle half — so it cannot pass through a deep+ // point at all. The conic's weight is what buys the reach.+ expect(shapeProgress(0.1, { viaX: 0.1, viaY: 0.9 })).toBeCloseTo(0.9, 6);+ expect(shapeProgress(0.05, { viaX: 0.05, viaY: 0.95 })).toBeCloseTo(0.95, 6);+ });++ it("never returns NaN for a via point dragged past the segment edge", () => {+ // A via point pulled out to (5, -3) clamps to (0.999, 0.001) — exactly on the+ // steady region's edge, where `edge - viaX` is 0 and the conic's weight used+ // to divide out to Infinity, then NaN a few steps later. NaN reaching+ // setValueCurveAtTime silences the node for the rest of the render.+ for (const x of [0, 0.1, 0.25, 0.5, 0.75, 0.9, 1]) {+ const y = shapeProgress(x, { viaX: 5, viaY: -3 });+ expect(Number.isFinite(y)).toBe(true);+ }+ });++ it("never flattens a bend that is pulled harder", () => {+ // The regression. Holding a bend's depth inside the steady region by clamping+ // its coordinates one at a time snapped the curve flat mid-drag: near the ends+ // of a segment almost every legal value sits on ONE side of the straight line,+ // so a bend pulled the other way got clamped onto the line itself and vanished.+ // Pulling further has to keep bending the way the pointer asked, always.+ for (const viaX of [0.1, 0.3, 0.5, 0.7, 0.9]) {+ for (const viaY of [0.9, 0.6, 0.45, 0.3, 0.05, -0.5, 1.5]) {+ if (Math.abs(viaY - viaX) < 0.02) continue;+ const via = steadyViaPoint(viaX, viaY);+ expect(via).not.toBeNull();+ if (!via) continue;+ // Same side of the straight line as the pointer asked for.+ expect(Math.sign(via.viaY - via.viaX)).toBe(Math.sign(viaY - viaX));+ // And a bend worth seeing, not a hair off straight.+ expect(Math.abs(via.viaY - via.viaX)).toBeGreaterThan(0.01);+ }+ }+ });++ it("stays a steady curve through the via point, with no corner to see", () => {+ // A shape built from two curves meeting AT the via point can only be as smooth+ // as that join, and keeping such a join monotone forces its tangent down to a+ // fraction of the slope the curve arrives with — which reads as a sharp corner+ // exactly where the pointer is. One conic arc has no join: slope is continuous+ // by construction, so the ratio across the via point stays near 1 even for the+ // extreme bends where a spliced curve kinked hardest.+ const slopeAt = (x: number, viaX: number, viaY: number): number => {+ const h = 1e-4;+ return (+ (shapeProgress(x + h, { viaX, viaY }) - shapeProgress(x - h, { viaX, viaY })) / (2 * h)+ );+ };+ for (const [viaX, viaY] of [+ [0.1, 0.9],+ [0.9, 0.1],+ [0.15, 0.6],+ [0.8, 0.95],+ [0.5, 0.95],+ [0.5, 0.05],+ ] as const) {+ const before = slopeAt(viaX - 0.02, viaX, viaY);+ const after = slopeAt(viaX + 0.02, viaX, viaY);+ expect(before).toBeGreaterThan(0);+ expect(after).toBeGreaterThan(0);+ // Within a factor of 2.2 across a 4% window either side — that much is real+ // curvature on a tight bend. Two cubics spliced at the via point measured+ // 27.6 on the first of these, and 2.4-3.6 on the gentler ones.+ const ratio = before > after ? before / after : after / before;+ expect(ratio).toBeLessThan(2.2);+ }+ });++ it("never changes slope abruptly anywhere along the segment", () => {+ // The same property swept rather than probed at the via point, so a corner+ // introduced anywhere else would fail too.+ for (const [viaX, viaY] of [+ [0.2, 0.8],+ [0.85, 0.35],+ [0.5, 0.9],+ [0.1, 0.9],+ [0.9, 0.08],+ ] as const) {+ let previous: number | null = null;+ for (let k = 2; k < 98; k++) {+ const x = k / 100;+ const h = 1e-3;+ const slope =+ (shapeProgress(x + h, { viaX, viaY }) - shapeProgress(x - h, { viaX, viaY })) / (2 * h);+ if (previous !== null) {+ const ratio = slope > previous ? slope / previous : previous / slope;+ // 1% of the segment at a time: a steady curve changes slope gradually.+ // The spliced version measured 2.2 here, and 14.5 with the via point+ // dragged into a corner.+ expect(ratio).toBeLessThan(1.7);+ }+ previous = slope;+ }+ }+ });++ it("keeps the segment pinned at both breakpoints", () => {+ for (const [vx, vy] of [+ [0.2, 0.7],+ [0.85, 0.3],+ ] as const) {+ expect(shapeProgress(0, { viaX: vx, viaY: vy })).toBeCloseTo(0, 9);+ expect(shapeProgress(1, { viaX: vx, viaY: vy })).toBeCloseTo(1, 9);+ }+ });++ it("stays monotone for every via point, so a render never sags mid-segment", () => {+ // Not cosmetic: a segment is baked into setValueCurveAtTime, and progress+ // that dipped backwards is a rising fader audibly dropping. This is the+ // property the Fritsch-Carlson tangent limit is there to guarantee, so it is+ // swept rather than spot-checked.+ for (let ix = 1; ix < 20; ix++) {+ for (let iy = 1; iy < 20; iy++) {+ const viaX = ix / 20;+ const viaY = iy / 20;+ let previous = -Infinity;+ for (let k = 0; k <= 60; k++) {+ const y = shapeProgress(k / 60, { viaX, viaY });+ expect(y).toBeGreaterThanOrEqual(previous - 1e-9);+ previous = y;+ }+ }+ }+ });++ it("puts the bend where the via point is, not always on the same side", () => {+ // The complaint this replaced: every upward bend a single exponent could draw+ // deviated most in the first fifth of the segment. Now the peak deviation+ // tracks the via point across the whole span.+ const apexOf = (viaX: number, viaY: number): number => {+ let best = 0;+ let at = 0;+ for (let k = 1; k < 100; k++) {+ const x = k / 100;+ const gap = Math.abs(shapeProgress(x, { viaX, viaY }) - x);+ if (gap > best) {+ best = gap;+ at = x;+ }+ }+ return at;+ };+ // Near, not exactly at: the deviation is smooth through the knot, so its peak+ // can sit slightly inside. What matters is that it tracks the via point+ // across the whole segment instead of parking in the first fifth.+ for (const viaX of [0.3, 0.4, 0.5, 0.6, 0.7]) {+ expect(Math.abs(apexOf(viaX, viaX + 0.06) - viaX)).toBeLessThan(0.12);+ }+ expect(apexOf(0.3, 0.36)).toBeLessThan(apexOf(0.7, 0.76));+ });++ it("bends either way from the same via progress", () => {+ const at = (viaY: number) =>+ sampleAutomationLane(+ lane([+ { t: 0, v: 0, viaX: 0.7, viaY },+ { t: 1, v: 1 },+ ]),+ 0.7,+ );+ expect(at(0.56)).toBeCloseTo(0.56, 6);+ expect(at(0.73)).toBeCloseTo(0.73, 6);+ });+it("walks a dense lane by bisection, not by scanning", () => {const points = Array.from({ length: 200 }, (_, i) => ({ t: i, v: i % 2 }));const dense = lane(points);diff --git a/packages/core/src/audioAutomation.ts b/packages/core/src/audioAutomation.tsindex f6363f5426..a47edf13fe 100644--- a/packages/core/src/audioAutomation.ts+++ b/packages/core/src/audioAutomation.ts@@ -35,6 +35,25 @@ export interface HfAutomationPoint {* straight line; positive holds low then rises late, negative rises early.*/curve?: number;+ /**+ * An interior point the segment *leaving* this point passes through, in+ * normalised segment space: `viaX` is progress 0..1 between the two+ * breakpoints, `viaY` is how far the value has travelled by then. Both are+ * needed for either to mean anything; without them the segment falls back to+ * `curve` above, so everything authored before this existed reads unchanged.+ *+ * Two numbers rather than one because `curve` answers only "how hard", and an+ * exponent cannot say "and where". Every upward bend a single exponent can+ * draw has its deepest deviation in the first fifth of the segment, whatever+ * the author aimed at, and an exponent steep enough to reach a point near+ * either end runs past the ±1 the model accepts — so a bend dragged near the+ * right-hand breakpoint bulged on the left and then stopped following the+ * pointer at all. Naming the point the curve goes through makes both the+ * height and the position of the bend the author's to choose, and takes the+ * saturation with it: any interior point is reachable exactly.+ */+ viaX?: number;+ viaY?: number;}export interface HfAutomationLane {@@ -153,6 +172,67 @@ function clampCurve(v: unknown): number {return Math.min(1, Math.max(-1, n));}+/**+ * A via point, or null when there isn't a usable one.+ *+ * Only two things disqualify one: a coordinate outside the segment, which names a+ * point the curve does not travel through, and a point ON the straight line, which+ * is a straight line — storing that would claim a bend the segment does not have.+ *+ * Depth is deliberately NOT limited. An earlier version held bends to a maximum+ * slope so a segment could never leave a breakpoint steeply, and it was wrong twice+ * over: it capped how far a curve could be pulled, and clamping the two coordinates+ * separately could land a bend exactly on the straight line and flatten it mid-drag.+ * A steep departure is a smooth curve doing what it was asked; what must never+ * happen is a crease, and that is the sampler's job below, not a limit here.+ */+function clampVia(rawX: unknown, rawY: unknown): { x: number; y: number } | null {+ const x = numberOrNull(rawX);+ const y = numberOrNull(rawY);+ if (x === null || y === null) return null;+ const inside = (n: number): number => Math.min(0.999, Math.max(0.001, n));+ const cx = inside(x);+ const cy = inside(y);+ if (Math.abs(cx - cy) < 1e-6) return null;+ return { x: cx, y: cy };+}++/**+ * The via point a segment will actually be drawn with, given one that was asked+ * for — pulled into the steady region, or null when it describes no bend.+ *+ * Exported so an editor can write what the model will honour rather than what the+ * pointer happened to ask for. Without it a lane's attribute claims a shape the+ * renderer quietly declines to draw, and the two only agree once the file makes a+ * round trip.+ */+export function steadyViaPoint(+ viaX: number | undefined,+ viaY: number | undefined,+): { viaX: number; viaY: number } | null {+ const via = clampVia(viaX, viaY);+ return via ? { viaX: via.x, viaY: via.y } : null;+}++/**+ * The shape fields a point carries, cleaned: whichever of `curve` and the via+ * pair survive, each omitted when it describes nothing.+ *+ * The via pair is kept or dropped together. Half a via point says nothing, and+ * letting one coordinate through would leave the segment's shape depending on+ * which half survived a hand edit.+ */+function shapeFields(+ p: HfAutomationPoint | undefined,+): Pick<HfAutomationPoint, "curve" | "viaX" | "viaY"> {+ const curve = clampCurve(p?.curve);+ const via = clampVia(p?.viaX, p?.viaY);+ return {+ ...(curve ? { curve } : {}),+ ...(via ? { viaX: via.x, viaY: via.y } : {}),+ };+}+/*** Clean one point, or reject it.*@@ -167,8 +247,7 @@ function cleanPoint(const v = numberOrNull(p?.v);if (t === null || v === null) return null;const clamped = range ? Math.min(range.max, Math.max(range.min, v)) : v;- const curve = clampCurve(p?.curve);- return { t: Math.max(0, t), v: clamped, ...(curve ? { curve } : {}) };+ return { t: Math.max(0, t), v: clamped, ...shapeFields(p) };}/**@@ -281,6 +360,7 @@ export function serializeAutomation(automation: HfAutomation): string {t: p.t,v: p.v,...(p.curve ? { curve: p.curve } : {}),+ ...(p.viaX !== undefined && p.viaY !== undefined ? { viaX: p.viaX, viaY: p.viaY } : {}),})),})),});@@ -298,6 +378,99 @@ export function applyCurve(x: number, curve: number | undefined): number {return Math.pow(x, Math.pow(2, 2 * curve));}+/**+ * The conic that carries a segment through its via point: control point and weight+ * of a rational quadratic Bezier from (0,0) to (1,1).+ *+ * A rational quadratic at its own midparameter is `(P0 + 2wC + P1) / (2 + 2w)`, so+ * demanding that equal the via point `Q` fixes the control point for any weight:+ * `C = Q + (Q - M) / w`, with `M` the straight midpoint. The curve therefore passes+ * exactly through `Q` whatever the weight, and — because it does so at the+ * midparameter, with the two halves symmetric in parameter — its furthest departure+ * from the straight line is at `Q` too. The pointer is the apex, by construction.+ *+ * The weight is what buys reach. A plain quadratic (`w = 1`) needs its control point+ * at `2Q - M`, which leaves the segment as soon as `Q` is past the middle half — so+ * a plain quadratic simply cannot pass through a deep or off-centre point. Raising+ * the weight draws the control point back toward `Q`, so take the smallest weight+ * that keeps `C` inside the segment: inside is what makes progress monotone, and+ * smallest-that-fits is the broadest curve available through that point.+ *+ * Deep bends therefore come out tight and steep near the breakpoint they lean on.+ * That is the shape being asked for, and it stays a single smooth arc while doing+ * it — no join, no inflection, no crease.+ */+function viaConic(viaX: number, viaY: number): { cx: number; cy: number; w: number } {+ const dx = viaX - 0.5;+ const dy = viaY - 0.5;+ const edge = 0.999;+ // Per axis, `C` stays inside when the weight is at least the pull divided by the+ // room left in the pull's own direction. A via point clamped to `edge` itself+ // leaves zero room — `edge - viaX` is exactly 0 — which would divide out to+ // Infinity and carry NaN into every downstream sample. Capped rather than left+ // unbounded: past this weight the arc already reads as touching the via point,+ // so the cap costs no visible reach.+ const MAX_WEIGHT = 1e6;+ const needX = dx > 0 ? dx / (edge - viaX) : dx < 0 ? -dx / (viaX - (1 - edge)) : 0;+ const needY = dy > 0 ? dy / (edge - viaY) : dy < 0 ? -dy / (viaY - (1 - edge)) : 0;+ const w = Math.min(MAX_WEIGHT, Math.max(1, needX, needY));+ return { cx: viaX + dx / w, cy: viaY + dy / w, w };+}++/**+ * Progress through a segment that passes through its via point: one conic arc, from+ * breakpoint to breakpoint.+ *+ * One curve, not two joined at the via point, because anything joined there can only+ * be as smooth as the join — and keeping such a join monotone forces its tangent+ * down to a fraction of the slope the curve arrives with, creasing the segment+ * exactly where the pointer is. A conic has no join and no inflection: its slope+ * moves one way from end to end, which is what makes it read as one curve rather+ * than a shape with features in it.+ */+function shapeVia(x: number, viaX: number, viaY: number): number {+ const { cx, cy, w } = viaConic(viaX, viaY);+ // Both coordinates are quadratics over one shared denominator, so `x(t) = x`+ // rearranges into an ordinary quadratic in `t`: closed form, and the same answer on+ // every machine, which a render that has to match its own preview depends on.+ const spread = 2 - 2 * w;+ const a = x * spread - 1 + 2 * w * cx;+ const b = -x * spread - 2 * w * cx;+ const t = conicParam(a, b, x);+ const rest = 1 - t;+ const denominator = rest * rest + 2 * w * t * rest + t * t;+ if (!(denominator > 0)) return x;+ return (2 * w * cy * t * rest + t * t) / denominator;+}++/** The root of `a*t^2 + b*t + c` that lies on the arc the segment travels. */+function conicParam(a: number, b: number, c: number): number {+ if (Math.abs(a) < 1e-12) return Math.abs(b) < 1e-12 ? c : -c / b;+ const root = Math.sqrt(Math.max(0, b * b - 4 * a * c));+ const first = (-b + root) / (2 * a);+ const second = (-b - root) / (2 * a);+ const onArc = (t: number): boolean => t >= -1e-9 && t <= 1 + 1e-9;+ if (onArc(first)) return Math.min(1, Math.max(0, first));+ if (onArc(second)) return Math.min(1, Math.max(0, second));+ return c;+}++/**+ * The progress a segment leaving `point` has reached at normalised `x`.+ *+ * A via point wins when it is there, since it says strictly more than an+ * exponent can. Everything authored before via points existed carries only+ * `curve` and takes the exponent path unchanged.+ */+export function shapeProgress(+ x: number,+ point: { curve?: number | undefined; viaX?: number | undefined; viaY?: number | undefined },+): number {+ const via = clampVia(point.viaX, point.viaY);+ if (via) return shapeVia(Math.min(1, Math.max(0, x)), via.x, via.y);+ return applyCurve(x, point.curve);+}+function lerpValue(a: number, b: number, x: number, scale: "linear" | "log"): number {// A frequency sweep interpolated linearly spends almost all its time in the// top octave. Log-scaled parameters interpolate in log space so a 200 Hz to@@ -338,7 +511,7 @@ export function sampleAutomationLane(const b = pts[hi]!;const span = b.t - a.t;if (span <= 0) return b.v;- return lerpValue(a.v, b.v, applyCurve((t - a.t) / span, a.curve), scale);+ return lerpValue(a.v, b.v, shapeProgress((t - a.t) / span, a), scale);}/** True when the lane is a single value, i.e. worth setting once and not scheduling. */diff --git a/packages/core/src/audioCarve.test.ts b/packages/core/src/audioCarve.test.tsindex 5778a1731d..cbd337520c 100644--- a/packages/core/src/audioCarve.test.ts+++ b/packages/core/src/audioCarve.test.ts@@ -1,11 +1,18 @@import { describe, expect, it } from "vitest";+import { MAX_AUTOMATION_POINTS, sampleAutomationLane } from "./audioAutomation.js";import {analyseCarveBands,+ analyseCarveDuck,+ analyseCarveDynamics,carveBandsToChain,+ carveProfile,DEFAULT_CARVE,normalizeCarveSettings,} from "./audioCarve.js";+/** The profile the panel's default strength produces — what the separate controls defaulted to. */+const PROFILE = carveProfile(DEFAULT_CARVE.strength);+const SR = 48000;/** A tone-plus-harmonics stand-in for a voice, centred on `f0`. */@@ -25,28 +32,99 @@ function voiceLike(f0: number, seconds = 0.5): Float32Array {describe("normalizeCarveSettings", () => {it("fills defaults and clamps nonsense", () => {expect(normalizeCarveSettings(undefined)).toEqual(DEFAULT_CARVE);- const v = normalizeCarveSettings({ maxCutDb: 500, bands: 99, q: 0, intelligibilityBias: -3 });- expect(v.maxCutDb).toBe(24);- expect(v.bands).toBe(6);- expect(v.q).toBe(0.3);- expect(v.intelligibilityBias).toBe(0);+ expect(normalizeCarveSettings({ strength: 40 }).strength).toBe(1);+ expect(normalizeCarveSettings({ strength: -3 }).strength).toBe(0);+ expect(normalizeCarveSettings({ strength: Number.NaN }).strength).toBe(DEFAULT_CARVE.strength);+ });++ it("reads a carve written before the controls collapsed into one", () => {+ // Depth is the number that said most about intent, so it maps back onto the+ // strength that reproduces it rather than being dropped.+ expect(normalizeCarveSettings({ maxCutDb: 6, bands: 3, q: 1.4 }).strength).toBe(0.25);+ expect(carveProfile(normalizeCarveSettings({ maxCutDb: 6 }).strength).maxCutDb).toBe(6);+ expect(normalizeCarveSettings({ maxCutDb: 10 }).strength).toBe(0.5);+ expect(normalizeCarveSettings({ maxCutDb: 24 }).strength).toBe(1);+ });++ it("keeps an explicit strength over a legacy depth", () => {+ expect(normalizeCarveSettings({ strength: 0.25, maxCutDb: 10 }).strength).toBe(0.25);+ });+});++describe("carveProfile", () => {+ it("lands on the old defaults at the strength the panel starts at", () => {+ // The separate controls shipped 6 dB, 3 bands, Q 1.4, bias 0.7, and the duck+ // pair defaulted to 6/9 — a project carved before the collapse must sound the+ // same after it. That point is a quarter of the way up, since the knob's range+ // was later doubled above it.+ expect(DEFAULT_CARVE.strength).toBe(0.25);+ expect(PROFILE).toEqual({+ maxCutDb: 6,+ bands: 3,+ q: 1.4,+ intelligibilityBias: 0.7,+ duckDb: 6,+ headroomDb: 9,+ });+ });++ it("moves every number the same direction, monotonically", () => {+ const steps = [0, 0.25, 0.5, 0.75, 1].map(carveProfile);+ for (let i = 1; i < steps.length; i++) {+ const a = steps[i - 1]!;+ const b = steps[i]!;+ expect(b.maxCutDb).toBeGreaterThan(a.maxCutDb);+ expect(b.bands).toBeGreaterThanOrEqual(a.bands);+ expect(b.q).toBeGreaterThan(a.q);+ expect(b.duckDb).toBeGreaterThan(a.duckDb);+ expect(b.headroomDb).toBeGreaterThan(a.headroomDb);+ }+ });++ it("carves frequencies only at zero, and goes hard at the top", () => {+ expect(carveProfile(0).duckDb).toBe(0);+ expect(carveProfile(0).bands).toBe(1);+ expect(carveProfile(1).maxCutDb).toBe(18);+ expect(carveProfile(1).bands).toBe(6);+ expect(carveProfile(1).duckDb).toBe(24);+ // The bias is a 0..1 weight, so the top of the knob is all the way over+ // rather than past it.+ expect(carveProfile(1).intelligibilityBias).toBe(1);+ });++ it("puts the old top of the knob at the halfway mark", () => {+ // The range was doubled because full strength could not sit a bed under a+ // loud voice. Everything the knob used to reach is now the bottom half.+ expect(carveProfile(0.5)).toEqual({+ maxCutDb: 10,+ bands: 4,+ q: 1.7,+ intelligibilityBias: 0.8,+ duckDb: 12,+ headroomDb: 12,+ });+ });++ it("clamps a strength outside the knob's own range", () => {+ expect(carveProfile(9)).toEqual(carveProfile(1));+ expect(carveProfile(-9)).toEqual(carveProfile(0));});});describe("analyseCarveBands", () => {it("returns nothing for silence-length input", () => {- expect(analyseCarveBands(new Float32Array(0), SR, DEFAULT_CARVE)).toEqual([]);+ expect(analyseCarveBands(new Float32Array(0), SR, PROFILE)).toEqual([]);});it("returns the requested number of bands, ascending, all cuts", () => {- const bands = analyseCarveBands(voiceLike(250), SR, { ...DEFAULT_CARVE, bands: 3 });+ const bands = analyseCarveBands(voiceLike(250), SR, { ...PROFILE, bands: 3 });expect(bands).toHaveLength(3);expect(bands.map((b) => b.freq)).toEqual([...bands.map((b) => b.freq)].sort((a, b) => a - b));for (const b of bands) expect(b.gainDb).toBeLessThan(0);});it("never cuts deeper than the configured maximum", () => {- const bands = analyseCarveBands(voiceLike(400), SR, { ...DEFAULT_CARVE, maxCutDb: 5 });+ const bands = analyseCarveBands(voiceLike(400), SR, { ...PROFILE, maxCutDb: 5 });for (const b of bands) expect(Math.abs(b.gainDb)).toBeLessThanOrEqual(5);});@@ -121,7 +199,7 @@ describe("analyseCarveBands", () => {// not where the voice is loudest. DEFAULT_CARVE is what a user gets from// clicking "Analyse and apply", so the default has to do this — a knob that// only works at its extreme does not work.- const bands = analyseCarveBands(tiltedVoice(), SR, { ...DEFAULT_CARVE, bands: 3 });+ const bands = analyseCarveBands(tiltedVoice(), SR, { ...PROFILE, bands: 3 });expect(bands.map((b) => b.freq).some((f) => f >= 1000)).toBe(true);});@@ -151,7 +229,7 @@ describe("analyseCarveBands", () => {}return out;})();- const one = { ...DEFAULT_CARVE, bands: 1 };+ const one = { ...PROFILE, bands: 1 };expect(analyseCarveBands(twoTone, SR, { ...one, intelligibilityBias: 0 })[0]!.freq).toBe(250);expect(analyseCarveBands(twoTone, SR, one)[0]!.freq).toBe(1600);});@@ -180,3 +258,203 @@ describe("carveBandsToChain", () => {expect(carveBandsToChain([]).nodes).toEqual([]);});});++describe("analyseCarveDuck", () => {+ const SR8 = 8000;++ /** Steady tone at a given amplitude — stands in for a bed or a voice. */+ function tone(amp: number, seconds: number, f = 300, sr = SR8): Float32Array {+ const out = new Float32Array(Math.floor(sr * seconds));+ for (let i = 0; i < out.length; i++) out[i] = amp * Math.sin(2 * Math.PI * f * (i / sr));+ return out;+ }++ /** Silence, then speech-level tone, then silence. */+ function voiceWithPause(amp: number, seconds: number, from: number, to: number): Float32Array {+ const out = new Float32Array(Math.floor(SR8 * seconds));+ for (let i = 0; i < out.length; i++) {+ const t = i / SR8;+ out[i] = t >= from && t < to ? amp * Math.sin(2 * Math.PI * 700 * t) : 0;+ }+ return out;+ }++ const at = (points: { t: number; v: number }[], t: number): number =>+ sampleAutomationLane({ target: "fx.n1.gain", points }, t);++ const settings = (over: Partial<typeof PROFILE> = {}) => ({+ ...PROFILE,+ duckDb: 12,+ headroomDb: 9,+ ...over,+ });++ it("leaves the bed alone where the voice is silent", () => {+ // The whole point of a follower: no voice, nothing to make room for. Before+ // the first word it is exactly flat; afterwards it eases back rather than+ // snapping, so the tail is checked by the release cases below.+ const duck = analyseCarveDuck(voiceWithPause(0.5, 16, 3, 6), tone(0.5, 16), SR8, settings(), 0);+ expect(at(duck, 1)).toBe(0);+ // A window is half a second wide and its value is stamped at its centre, so+ // the duck begins up to half a window before the first word — checked clear+ // of that rather than right against it.+ expect(at(duck, 2)).toBe(0);+ // Back to inaudible by the end of a long tail rather than held down for the+ // clip; the envelope's last point is pinned at exactly no cut.+ expect(at(duck, 15)).toBeCloseTo(0, 1);+ expect(duck.at(-1)?.v).toBe(0);+ });++ it("ducks a loud bed under a quiet voice", () => {+ // Bed 12 dB above the voice with 9 dB of headroom asked for: the bed has to+ // come down by about 21 dB, which the cap holds at 12.+ const duck = analyseCarveDuck(+ voiceWithPause(0.12, 8, 2, 7),+ tone(0.5, 8),+ SR8,+ settings({ duckDb: 24 }),+ 0,+ );+ expect(at(duck, 4.5)).toBeLessThan(-15);+ });++ it("barely touches a bed already sitting under the voice", () => {+ const duck = analyseCarveDuck(voiceWithPause(0.8, 8, 2, 7), tone(0.05, 8), SR8, settings(), 0);+ expect(at(duck, 4.5)).toBeGreaterThan(-1);+ });++ it("lets the bed come back slowly after the voice stops", () => {+ // A bed that jumps back to full the instant a word ends is heard as the+ // effect switching off. It has to ease back over seconds — and the envelope's+ // own step is ~0.3s on a long voice, so a release near that lands the whole+ // recovery inside one step, which is exactly the flip this pins against.+ const voice = voiceWithPause(0.5, 14, 2, 6);+ const duck = analyseCarveDuck(voice, tone(0.5, 14), SR8, settings({ duckDb: 12 }), 0);+ const atSpeech = at(duck, 5.5);+ expect(atSpeech).toBeLessThan(-6);++ // Still most of the way down a third of a second after the last word...+ expect(at(duck, 6.3)).toBeLessThan(atSpeech * 0.6);+ // ...noticeably recovered by a second and a half...+ expect(at(duck, 7.5)).toBeGreaterThan(atSpeech * 0.5);+ // ...and within a hair of flat a few seconds later, rather than held down.+ expect(at(duck, 11)).toBeGreaterThan(-0.6);+ });++ it("finishes the release past the last word instead of snapping at the end", () => {+ // A lane's last point has to be no cut, or the bed stays dipped for the rest+ // of the clip. Jumping there from full duck is the same flip the slow release+ // exists to prevent, just moved to the end of the narration — so the envelope+ // keeps decaying past the voice and pins once it is inaudible.+ const voice = voiceWithPause(0.5, 8, 1, 7.9);+ const duck = analyseCarveDuck(voice, tone(0.5, 12), SR8, settings({ duckDb: 12 }), 0);+ const steps = duck.slice(1).map((p, i) => Math.abs(p.v - duck[i]!.v));+ expect(Math.max(...steps.slice(-4))).toBeLessThan(2);+ // Still ducked a moment after the voice stops, and flat well after.+ expect(at(duck, 8.2)).toBeLessThan(-2);+ expect(duck.at(-1)?.v).toBe(0);+ expect(duck.at(-1)!.t).toBeGreaterThan(8);+ });++ it("comes back up more slowly than it ducks", () => {+ // Asymmetric on purpose: the cut has to be there by the time a word is+ // audible, and gone slowly enough that the bed does not pump between+ // sentences.+ const voice = voiceWithPause(0.5, 14, 4, 8);+ const duck = analyseCarveDuck(voice, tone(0.5, 14), SR8, settings({ duckDb: 12 }), 0);+ const floor = Math.min(...duck.map((p) => p.v));+ const toHalfDown = duck.find((p) => p.v <= floor * 0.5)?.t ?? Infinity;+ const backToHalfUp =+ [...duck].reverse().find((p) => p.v <= floor * 0.5)?.t ?? Number.NEGATIVE_INFINITY;+ const attackSpan = toHalfDown - 4;+ const releaseSpan = backToHalfUp - 8;+ expect(releaseSpan).toBeGreaterThan(attackSpan * 2);+ });++ it("never exceeds the configured maximum", () => {+ const duck = analyseCarveDuck(+ voiceWithPause(0.02, 8, 2, 7),+ tone(0.9, 8),+ SR8,+ settings({ duckDb: 6 }),+ 0,+ );+ expect(Math.min(...duck.map((p) => p.v))).toBeGreaterThanOrEqual(-6);+ });++ it("reads the bed at the offset between the two clips", () => {+ // The bed starts before the voice, so voice-local 0 is bed-local `offset`.+ // Given a bed that is loud only in its first half, a voice that starts 4s+ // into it must see the quiet half and duck less than the same voice at 0.+ const bed = new Float32Array(Math.floor(SR8 * 8));+ for (let i = 0; i < bed.length; i++) {+ const t = i / SR8;+ bed[i] = (t < 4 ? 0.9 : 0.02) * Math.sin(2 * Math.PI * 300 * t);+ }+ const voice = voiceWithPause(0.3, 4, 0.5, 3.5);+ const aligned = analyseCarveDuck(voice, bed, SR8, settings({ duckDb: 24 }), 0);+ const shifted = analyseCarveDuck(voice, bed, SR8, settings({ duckDb: 24 }), 4);+ expect(at(aligned, 2)).toBeLessThan(at(shifted, 2));+ });++ it("returns nothing without a voice, and stays inside the point budget", () => {+ expect(analyseCarveDuck(new Float32Array(0), tone(0.5, 2), SR8, settings(), 0)).toEqual([]);+ const long = analyseCarveDuck(+ voiceWithPause(0.4, 200, 5, 195),+ tone(0.5, 200),+ SR8,+ settings(),+ 0,+ );+ expect(long.length).toBeLessThanOrEqual(MAX_AUTOMATION_POINTS);+ });+});++describe("analyseCarveDynamics", () => {+ const BAND = { freq: 1000, gainDb: -8, q: 1.4 };++ /** Silence, then a 1 kHz burst, then silence again. */+ function burst(sampleRate: number, seconds: number, from: number, to: number): Float32Array {+ const out = new Float32Array(Math.floor(sampleRate * seconds));+ for (let i = 0; i < out.length; i++) {+ const t = i / sampleRate;+ out[i] = t >= from && t < to ? 0.7 * Math.sin(2 * Math.PI * 1000 * t) : 0;+ }+ return out;+ }++ const at = (points: { t: number; v: number }[], t: number): number =>+ sampleAutomationLane({ target: "fx.n1.gain", points }, t);++ it("holds the filter flat where the voice is silent and cuts where it speaks", () => {+ const [lane] = analyseCarveDynamics(burst(SR, 6, 2, 4), SR, [BAND]);+ expect(lane!.freq).toBe(1000);+ expect(at(lane!.points, 0.7)).toBeCloseTo(0, 1);+ expect(at(lane!.points, 3)).toBeLessThan(-6);+ expect(at(lane!.points, 5.3)).toBeCloseTo(0, 1);+ });++ it("pins both ends of the envelope to no cut", () => {+ const [lane] = analyseCarveDynamics(burst(SR, 6, 2, 4), SR, [BAND]);+ const points = lane!.points;+ expect(points[0]).toMatchObject({ t: 0, v: 0 });+ expect(points.at(-1)!.v).toBe(0);+ // Held past the end, so the bed comes back up rather than staying dipped.+ expect(points.at(-1)!.t).toBeGreaterThanOrEqual(5.9);+ });++ it("never exceeds the point budget a lane can hold", () => {+ const long = burst(8000, 200, 10, 190);+ const [lane] = analyseCarveDynamics(long, 8000, [BAND]);+ expect(lane!.points.length).toBeLessThanOrEqual(MAX_AUTOMATION_POINTS);+ expect(lane!.points.length).toBeGreaterThan(2);+ });++ it("returns one envelope per band, and nothing for no input", () => {+ const sig = burst(SR, 3, 0.5, 2.5);+ expect(analyseCarveDynamics(sig, SR, [BAND, { freq: 2500, gainDb: -4, q: 1.4 }])).toHaveLength(+ 2,+ );+ expect(analyseCarveDynamics(new Float32Array(0), SR, [BAND])).toEqual([]);+ });+});diff --git a/packages/core/src/audioCarve.ts b/packages/core/src/audioCarve.tsindex 386aadf64b..1844010518 100644--- a/packages/core/src/audioCarve.ts+++ b/packages/core/src/audioCarve.ts@@ -32,44 +32,125 @@ export interface HfCarveBand {q: number;}+/**+ * What the author sets: which voice to listen to, how hard to work, and whether+ * the work follows the voice moment to moment.+ *+ * One number for the strength of the effect, not six for its mechanism. The+ * mechanism has six numbers — how deep to cut, how many bands, how wide, how far+ * to favour intelligibility over raw energy, how far the level may drop, how far+ * under the voice to aim — and every one of them was a control nobody could set+ * without knowing what the analysis does with it. They move together anyway: a+ * gentle carve is a shallow cut in few bands with little ducking, a hard one is+ * deeper in more bands with more. `carveProfile` is that relationship, written+ * once.+ */export interface HfCarveSettings {/** Element id of the voice track to analyse. */source: string;+ /** How hard to carve, 0..1. */+ strength: number;+ /**+ * Follow the voice rather than sitting at a fixed depth.+ *+ * A static carve holds its cuts for the whole clip, including every pause — the+ * bed is thinned where there is nothing to make room for. Dynamic turns every+ * value into an envelope of the voice's own level, so silence leaves the bed+ * alone and a loud passage pushes the carve to full depth.+ */+ dynamic: boolean;+}++/** The numbers the analysis actually works in, all derived from `strength`. */+export interface HfCarveProfile {/** Deepest cut applied to the strongest band. */maxCutDb: number;/** How many bands to dip. */bands: number;q: number;/**- * Weight selection toward intelligibility rather than raw voice energy.+ * Weight band selection toward intelligibility rather than raw voice energy.** Ranking purely by voice power lands on the fundamental almost every time,- * because that is where a voice is loudest — but masking that actually hurts- * a voiceover happens higher up, and dipping 160 Hz mostly just thins the- * bed. Weighting pushes selection toward 1-3 kHz where intelligibility lives.+ * because that is where a voice is loudest — but masking that actually hurts a+ * voiceover happens higher up, and dipping 160 Hz mostly just thins the bed.*/intelligibilityBias: number;+ /** How far the bed's whole level may come down to make room, in dB. */+ duckDb: number;+ /** How far under the voice the bed should sit while the voice speaks, in dB. */+ headroomDb: number;}export const DEFAULT_CARVE: HfCarveSettings = {source: "",- maxCutDb: 6,- bands: 3,- q: 1.4,- intelligibilityBias: 0.7,+ // A quarter, because the knob's range was doubled and this is the point on the+ // new scale that produces what the panel has always defaulted to. Switching+ // carve on sounds the same as it did; the extra range is above, not under.+ strength: 0.25,+ dynamic: false,};-export function normalizeCarveSettings(raw: Partial<HfCarveSettings> | undefined): HfCarveSettings {- const clamp = (v: unknown, lo: number, hi: number, dflt: number): number => {+/**+ * Strength as the six numbers the analysis needs.+ *+ * Each is a straight line from "barely there" to as far as the effect goes. The+ * slopes are twice what they first were: the top of the knob was not strong+ * enough to sit a bed under a loud voice, so what used to be full strength is now+ * the halfway point and everything above it is new range. Quarter strength is+ * therefore where the separate controls' own defaults land, which is what the+ * panel defaults to.+ */+export function carveProfile(strength: number): HfCarveProfile {+ const s = Number.isFinite(strength) ? Math.min(1, Math.max(0, strength)) : 0.5;+ return {+ // 2 dB is audible-but-subtle. Past about 10 the hole starts being heard as+ // the effect rather than as room for the voice — which is a price worth+ // paying at the top of the knob, and why the range now runs past it.+ maxCutDb: Number((2 + s * 16).toFixed(2)),+ // One band carves the single worst collision; six is every candidate band+ // speech meaningfully occupies.+ bands: Math.max(1, Math.min(6, Math.round(1 + s * 6))),+ // Wider at low strength so a gentle carve is a tilt rather than a notch.+ q: Number((1.1 + s * 1.2).toFixed(2)),+ // Always weighted toward where masking hurts; at the top, entirely.+ intelligibilityBias: Number(Math.min(1, 0.6 + s * 0.4).toFixed(2)),+ // No level ducking at all at zero: the carve is then purely spectral.+ duckDb: Number((s * 24).toFixed(2)),+ // How far under the voice to aim. Deeper targets at higher strength.+ headroomDb: Number((6 + s * 12).toFixed(2)),+ };+}++/**+ * Read carve settings from an attribute.+ *+ * Projects written before the collapse to one knob carry the six mechanism+ * numbers instead; their depth is the one that says most about intent, so it maps+ * back onto strength rather than being dropped. Everything else about such a+ * carve is re-derived, which is the point of having one control.+ */+export function normalizeCarveSettings(+ raw: Partial<HfCarveSettings & HfCarveProfile> | undefined,+): HfCarveSettings {+ const num = (v: unknown): number | null => {const n = typeof v === "number" ? v : Number(v);- return Number.isFinite(n) ? Math.min(hi, Math.max(lo, n)) : dflt;+ return Number.isFinite(n) ? n : null;};+ const strength = num(raw?.strength);+ const legacyDepth = num(raw?.maxCutDb);+ const resolved =+ strength !== null+ ? strength+ : legacyDepth !== null+ ? // The inverse of the depth line in `carveProfile`, so the 6 dB default+ // reads back as the strength that produces 6 dB.+ (legacyDepth - 2) / 16+ : DEFAULT_CARVE.strength;return {source: typeof raw?.source === "string" ? raw.source : "",- maxCutDb: clamp(raw?.maxCutDb, 0, 24, DEFAULT_CARVE.maxCutDb),- bands: Math.round(clamp(raw?.bands, 1, 6, DEFAULT_CARVE.bands)),- q: clamp(raw?.q, 0.3, 8, DEFAULT_CARVE.q),- intelligibilityBias: clamp(raw?.intelligibilityBias, 0, 1, DEFAULT_CARVE.intelligibilityBias),+ strength: Math.min(1, Math.max(0, resolved)),+ dynamic: raw?.dynamic === true,};}@@ -206,7 +287,7 @@ function intelligibilityPenaltyDb(center: number, bias: number): number {export function analyseCarveBands(voice: Float32Array,sampleRate: number,- settings: HfCarveSettings,+ profile: HfCarveProfile,): HfCarveBand[] {if (voice.length === 0) return [];const { freqs, power } = powerSpectrum(voice, sampleRate);@@ -222,12 +303,12 @@ export function analyseCarveBands(scoreDb:bandPowerAt > 0? 10 * Math.log10(bandPowerAt) -- intelligibilityPenaltyDb(center, settings.intelligibilityBias)+ intelligibilityPenaltyDb(center, profile.intelligibilityBias): Number.NEGATIVE_INFINITY,};}).sort((a, b) => b.scoreDb - a.scoreDb);- const selected = scored.slice(0, Math.max(1, settings.bands)).filter((b) => b.hasEnergy);+ const selected = scored.slice(0, Math.max(1, profile.bands)).filter((b) => b.hasEnergy);if (selected.length === 0) return [];const topDb = selected[0]!.scoreDb;@@ -237,14 +318,266 @@ export function analyseCarveBands(// under the strongest gets half its cut — read off the dB difference.const relative = Math.pow(10, (scoreDb - topDb) / 10);const depth = Math.min(- settings.maxCutDb,- Math.max(settings.maxCutDb / 2, settings.maxCutDb * relative),+ profile.maxCutDb,+ Math.max(profile.maxCutDb / 2, profile.maxCutDb * relative),);- return { freq: center, gainDb: -Number(depth.toFixed(2)), q: settings.q };+ return { freq: center, gainDb: -Number(depth.toFixed(2)), q: profile.q };}).sort((a, b) => a.freq - b.freq);}+/**+ * How far below a band's own loudest moment counts as nothing to carve. A voice+ * 30 dB down on its peak is a room tone or a breath, not speech, and the bed+ * should be flat there.+ */+const DYNAMIC_RANGE_DB = 30;++/**+ * Envelope follower time constants, in seconds. Asymmetric on purpose, the way+ * a ducker is: the cut has to be there by the time a word is audible, and has to+ * leave slowly enough that the bed does not pump between syllables.+ */+const ATTACK_S = 0.05;+const RELEASE_S = 0.25;++/**+ * Release for the level envelope, which is far slower than the filters' own.+ *+ * A notch closing quickly is inaudible — nothing about the bed's loudness+ * changes. The whole bed coming back is not: at a filter's 0.25s the music+ * jumped to full the instant a word ended, and what you hear then is the effect+ * switching off rather than a mix breathing. Slower than any gap inside a+ * sentence, so it rides through the pauses between words and only recovers+ * between sentences.+ *+ * It also has to be well clear of the envelope's own step. A long voice is+ * measured about every 0.3s, so a release anywhere near that puts the entire+ * recovery inside one step — a jump, whatever the constant claims.+ */+const DUCK_RELEASE_S = 1.6;++/**+ * Windows an envelope may spend. Held under `MAX_AUTOMATION_POINTS` with room+ * for the two end points, because `normalizeAutomation` truncates an over-budget+ * lane rather than thinning it — losing the tail would leave the last cut held+ * for the rest of the bed, which is the one failure this feature must not have.+ */+const POINT_BUDGET = 400;++/** Below this a cut is inaudible, so it is recorded as no cut at all. */+const SNAP_DB = 0.2;++/**+ * Smallest move worth its own breakpoint. Coarse enough that a lane stays+ * editable by hand — a syllable-rate envelope at the analysis hop draws a point+ * every 85 ms, which is a wall of handles nobody can grab — and fine enough that+ * the shape is unchanged, since the segments either side interpolate.+ */+const STEP_DB = 0.5;++/**+ * Thin a raw per-frame envelope down to the points where its value actually+ * moved by `stepDb`, anchoring the run each drop ends.+ *+ * Segments interpolate, so dropping a run of equal values does not hold them —+ * it draws a straight line from wherever the last kept point was, which turned+ * a silent stretch before the run into a slow slide into it. Keeping the last+ * value of the run pins the plateau flat and puts the whole move where it+ * belongs. Shared by the two envelope builders below, which differ only in how+ * `raw` gets built.+ */+function simplifyStepPoints(+ raw: readonly { t: number; v: number }[],+ stepDb: number,+): { t: number; v: number }[] {+ const points: { t: number; v: number }[] = [{ t: 0, v: 0 }];+ let lastKept = 0;+ let keptIndex = -1;+ raw.forEach((pt, i) => {+ if (i !== raw.length - 1 && Math.abs(pt.v - lastKept) < stepDb) return;+ if (i > 0 && keptIndex !== i - 1) points.push(raw[i - 1]!);+ points.push(pt);+ lastKept = pt.v;+ keptIndex = i;+ });+ return points;+}++export interface HfCarveDynamics {+ /** The band this envelope drives, matching a band from `analyseCarveBands`. */+ freq: number;+ /** Gain in dB over time, in seconds from the start of the *voice* clip. */+ points: { t: number; v: number }[];+}++/**+ * Turn each carved band into an envelope that follows the voice's level in that+ * same band.+ *+ * The depth from `analyseCarveBands` becomes the envelope's ceiling rather than a+ * constant: full depth where that band is at its loudest in the voice, flat where+ * the voice is silent, scaled in dB between the two. Written as automation on the+ * filters' gain, so playback and render both already know how to follow it.+ *+ * Times are relative to the voice clip, since that is what was measured. A caller+ * placing these on another element shifts them by the gap between the two clips'+ * starts. This assumes the voice plays from its own beginning at its `data-start`+ * — a clip with a media offset would need that added.+ */+export function analyseCarveDynamics(+ voice: Float32Array,+ sampleRate: number,+ bands: HfCarveBand[],+): HfCarveDynamics[] {+ if (voice.length === 0 || bands.length === 0) return [];++ const window = new Float32Array(FRAME);+ for (let i = 0; i < FRAME; i++) window[i] = 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / (FRAME - 1));++ // One window per emitted point, so the hop is what keeps the lane in budget.+ const hop = Math.max(FRAME, Math.ceil(voice.length / POINT_BUDGET));+ const bins = FRAME / 2 + 1;+ const freqs: number[] = [];+ for (let k = 0; k < bins; k++) freqs.push((k * sampleRate) / FRAME);++ const times: number[] = [];+ const perBand = bands.map(() => [] as number[]);+ for (let start = 0; start < voice.length; start += hop) {+ const re = new Float64Array(FRAME);+ const im = new Float64Array(FRAME);+ for (let i = 0; i < FRAME; i++) re[i] = (voice[start + i] ?? 0) * window[i]!;+ fft(re, im);+ const power: number[] = [];+ for (let k = 0; k < bins; k++) power.push(re[k]! * re[k]! + im[k]! * im[k]!);+ times.push((start + FRAME / 2) / sampleRate);+ bands.forEach((band, b) => perBand[b]!.push(bandPower(freqs, power, band.freq)));+ }++ const duration = voice.length / sampleRate;+ const attack = 1 - Math.exp(-(hop / sampleRate) / ATTACK_S);+ const release = 1 - Math.exp(-(hop / sampleRate) / RELEASE_S);++ return bands.map((band, b) => {+ const powers = perBand[b]!;+ const peak = Math.max(...powers);+ let level = 0;+ const raw: { t: number; v: number }[] = [];+ powers.forEach((p, i) => {+ // Relative to this band's own loudest moment, so a quiet band still gets a+ // full envelope rather than a permanently shallow one.+ const target =+ p > 0 && peak > 0 ? Math.max(0, 1 + (10 * Math.log10(p / peak)) / DYNAMIC_RANGE_DB) : 0;+ level += (target > level ? attack : release) * (target - level);+ const scaled = band.gainDb * level;+ const v = Math.abs(scaled) < SNAP_DB ? 0 : Number(scaled.toFixed(1));+ raw.push({ t: Number(times[i]!.toFixed(3)), v });+ });+ const points = simplifyStepPoints(raw, STEP_DB);+ // The last point's value is held for the rest of the bed, so it has to be+ // no cut and it has to be at the end of the voice.+ points.push({ t: Number(Math.max(duration, points.at(-1)!.t).toFixed(3)), v: 0 });+ return { freq: band.freq, points };+ });+}++/** Level in dB of one window, or -Infinity for silence. */+function windowDb(samples: Float32Array, from: number, count: number): number {+ let sum = 0;+ let n = 0;+ for (let i = from; i < from + count; i++) {+ const s = samples[i];+ if (s === undefined) break;+ sum += s * s;+ n += 1;+ }+ if (n === 0) return Number.NEGATIVE_INFINITY;+ const rms = Math.sqrt(sum / n);+ return rms > 0 ? 20 * Math.log10(rms) : Number.NEGATIVE_INFINITY;+}++/**+ * The level envelope that keeps a bed under a voice.+ *+ * The spectral carve makes room in the frequency domain, which does nothing+ * about a bed that is simply louder than the voice: the notches sit in the right+ * places while the level goes on winning. This measures both tracks over the+ * same windows and returns the gain the bed needs to sit `headroomDb` under the+ * voice — no more than `duckDb`, and nothing at all where the voice is not+ * speaking, so pauses stay open rather than being held down.+ *+ * Times are in seconds from the start of the *voice* clip; `offsetSeconds` is+ * how far into the bed the voice's start falls, so the two are read at the same+ * moment of the composition even when the clips begin at different times.+ */+export function analyseCarveDuck(+ voice: Float32Array,+ bed: Float32Array,+ sampleRate: number,+ profile: HfCarveProfile,+ offsetSeconds: number,+): { t: number; v: number }[] {+ if (voice.length === 0 || profile.duckDb <= 0) return [];++ const hop = Math.max(FRAME, Math.ceil(voice.length / POINT_BUDGET));+ const bedOffset = Math.round(offsetSeconds * sampleRate);++ const voiceDbs: number[] = [];+ const bedDbs: number[] = [];+ const times: number[] = [];+ for (let start = 0; start < voice.length; start += hop) {+ voiceDbs.push(windowDb(voice, start, FRAME));+ bedDbs.push(windowDb(bed, start + bedOffset, FRAME));+ times.push((start + FRAME / 2) / sampleRate);+ }++ // Speaking, rather than merely non-zero: a room tone 30 dB under the voice's+ // own peak is not something to duck for, and gating on it is what keeps the+ // bed up through pauses.+ const voicePeak = Math.max(...voiceDbs);+ const speakingFloor = voicePeak - DYNAMIC_RANGE_DB;++ const attack = 1 - Math.exp(-(hop / sampleRate) / ATTACK_S);+ const release = 1 - Math.exp(-(hop / sampleRate) / DUCK_RELEASE_S);++ let level = 0;+ const raw: { t: number; v: number }[] = [];+ voiceDbs.forEach((vDb, i) => {+ const bDb = bedDbs[i] ?? Number.NEGATIVE_INFINITY;+ // How far over the line the bed is, right now.+ const over = vDb > speakingFloor && Number.isFinite(bDb) ? bDb - (vDb - profile.headroomDb) : 0;+ const target = Math.min(profile.duckDb, Math.max(0, over));+ level += (target > level ? attack : release) * (target - level);+ const v = level < SNAP_DB ? 0 : -Number(level.toFixed(1));+ raw.push({ t: Number(times[i]!.toFixed(3)), v });+ });++ // Let the release finish past the last word. A lane's final point has to be no+ // cut — otherwise the bed stays dipped for the rest of the clip — but jumping+ // there from a full duck is the same flip the slow release exists to prevent,+ // moved to the end of the narration. So the decay carries on at its own rate+ // beyond the voice until it is inaudible, and only then pins.+ const hopSeconds = hop / sampleRate;+ let tailTime = times.at(-1) ?? 0;+ while (level >= SNAP_DB) {+ level += release * -level;+ tailTime += hopSeconds;+ raw.push({+ t: Number(tailTime.toFixed(3)),+ v: level < SNAP_DB ? 0 : -Number(level.toFixed(1)),+ });+ }++ const points = simplifyStepPoints(raw, STEP_DB);+ // Pin the end at no cut, unless the release already got there — a second point+ // at the same time and value is just noise in the lane.+ const duration = voice.length / sampleRate;+ const last = points.at(-1)!;+ const endTime = Number(Math.max(duration, last.t).toFixed(3));+ if (!(last.v === 0 && last.t >= endTime)) points.push({ t: endTime, v: 0 });+ return points;+}+/** Carve bands as an ordinary FX chain of peaking filters. */export function carveBandsToChain(bands: HfCarveBand[]): HfAudioFxChain {const nodes: HfAudioFxNode[] = bands.map((b) => ({diff --git a/packages/core/src/audioFx.ts b/packages/core/src/audioFx.tsindex 2eb2db83d4..1e38c4f298 100644--- a/packages/core/src/audioFx.ts+++ b/packages/core/src/audioFx.ts@@ -136,6 +136,16 @@ const poles: HfAudioFxEnumParam = {* a value that survives `normalizeAudioFxParams` is always safe to realise.*/export const HF_AUDIO_FX: readonly HfAudioFxDef[] = [+ {+ id: "gain",+ label: "Gain",+ group: "dynamics",+ description: "Raise or lower the whole signal. Automate it to duck under something else.",+ // Cuts go deep, boosts stay modest: this is a level stage for making room,+ // and a chain that can add 40 dB clips long before it is useful.+ params: [gainDb(-60, 12, 0)],+ web: "gain-node",+ },{id: "peaking",label: "Peaking EQ",diff --git a/packages/core/src/runtime/audioFx.test.ts b/packages/core/src/runtime/audioFx.test.tsindex 46ac76139f..9774515810 100644--- a/packages/core/src/runtime/audioFx.test.ts+++ b/packages/core/src/runtime/audioFx.test.ts@@ -1,6 +1,7 @@// @vitest-environment happy-domimport { describe, expect, it } from "vitest";import { attachElementFxChain } from "./audioFx.js";+import { defaultAudioFxParams, HF_AUDIO_FX } from "../audioFx.js";/*** The DSP is proven in a real browser by the engine's render tests. What needs@@ -187,6 +188,122 @@ describe("attachElementFxChain", () => {expect(before.disconnected).toBe(true);});+ const violations: string[] = [];++ /**+ * An AudioParam with the browser's own scheduling rule: writing `.value`+ * while a value curve covers the current time throws, because setting the+ * property is a `setValueAtTime` at that instant and a curve may not overlap+ * another event. Chrome words it exactly as this does.+ */+ class SchedParam {+ curves: { time: number; duration: number }[] = [];+ sets: number[] = [];+ #value = 0;+ constructor(private clock: { currentTime: number }) {}+ get value(): number {+ return this.#value;+ }+ set value(v: number) {+ const t = this.clock.currentTime;+ const covering = this.curves.find((c) => t >= c.time && t <= c.time + c.duration);+ if (covering) {+ // Recorded as well as thrown: the throw happens inside a+ // MutationObserver callback, where nothing rethrows it into the test —+ // which is exactly why this only ever showed up as an uncaught error+ // in the preview console.+ const message =+ `Failed to set the 'value' property on 'AudioParam': setValueAtTime(${v}, ${t}) ` ++ `overlaps setValueCurveAtTime(..., ${covering.time}, ${covering.duration})`;+ violations.push(message);+ throw new Error(message);+ }+ this.#value = v;+ }+ setValueAtTime(v: number, t: number): void {+ this.sets.push(t);+ this.#value = v;+ }+ linearRampToValueAtTime(v: number): void {+ this.#value = v;+ }+ setValueCurveAtTime(_v: Float32Array, time: number, duration: number): void {+ this.curves.push({ time, duration });+ }+ cancelScheduledValues(from: number): void {+ this.curves = this.curves.filter((c) => c.time + c.duration < from);+ }+ cancelAndHoldAtTime(from: number): void {+ this.cancelScheduledValues(from);+ }+ }++ it("edits a chain whose parameters an envelope is mid-curve on", async () => {+ // The level stage a carve adds is automated, so a chain edit lands while a+ // curve is running. Writing the new value straight onto the param throws+ // NotSupportedError, which surfaced in the console as the preview refusing+ // every edit after the first.+ const clock = { currentTime: 0 };+ class SchedNode extends Node {+ override frequency = new SchedParam(clock) as unknown as { value: number };+ override Q = new SchedParam(clock) as unknown as { value: number };+ override gain = new SchedParam(clock) as unknown as { value: number };+ }+ class SchedCtx extends Ctx {+ get currentTime(): number {+ return clock.currentTime;+ }+ override createGain(): Node {+ return new SchedNode();+ }+ override createBiquadFilter(): Node {+ return new SchedNode();+ }+ }+ // A gain stage, because its dB-to-linear mapping is what makes the+ // scheduler emit a value curve instead of a ramp — and a curve is what a+ // `.value` write may not land inside.+ const chainWith = (freq: number) => ({+ version: 1,+ nodes: [+ { type: "gain", id: "n1", params: { gain: 0 } },+ { type: "peaking", id: "n2", params: { frequency: freq, gain: -6, q: 1 } },+ ],+ });+ const node = audioEl(chainWith(1000));+ // A bent segment, so the scheduler emits a curve rather than a ramp.+ node.setAttribute(+ "data-automation",+ JSON.stringify({+ version: 1,+ lanes: [+ {+ target: "fx.n1.gain",+ points: [+ { t: 0, v: 0 },+ { t: 8, v: -12 },+ ],+ },+ ],+ }),+ );+ attachElementFxChain(+ new SchedCtx() as unknown as BaseAudioContext,+ node,+ new Node() as never,+ new Node() as never,+ { scheduledAt: 0, elapsed: 0, rate: 1 },+ );++ // Mid-curve, which is when the edit has to survive.+ clock.currentTime = 3;+ node.setAttribute("data-fx-chain", JSON.stringify(chainWith(1200)));+ await settle();++ expect(violations).toEqual([]);+ expect(node.getAttribute("data-fx-chain")).toContain("1200");+ });+it("keeps playing dry when an edit leaves the chain unreadable", async () => {const src = new Node();const dst = new Node();@@ -205,4 +322,370 @@ describe("attachElementFxChain", () => {handle!.dispose();expect((src.connections[0] as Node).disconnected).toBe(true);});++ /**+ * A limiter, a compressor, a gate and a bitcrush are AudioWorklet processors,+ * and a worklet node cannot be constructed before its module has registered. So+ * a chain containing one plays dry for a moment and swaps in when registration+ * resolves — and that path used to end there: no automation scheduled, no+ * observer watching the attribute. Adding a compressor to a carved bed+ * therefore killed the carve's envelopes and froze every later edit until the+ * composition reloaded.+ */+ describe("a chain that needs worklets before it can be built", () => {+ /**+ * Constructs only once the module has registered on that context, which is+ * what Chrome does — and the whole reason this path exists. A stub that always+ * succeeds hides the bug: the build then works even when nothing registered.+ */+ class WorkletNodeStub extends Node {+ port = { postMessage: () => {} };+ constructor(ctx: { workletsReady?: boolean }, name: string) {+ super("worklet");+ if (!ctx.workletsReady) {+ throw new Error(`AudioWorkletNode: processor "${name}" is not registered`);+ }+ }+ }++ /** A param that records whether an envelope was ever scheduled onto it. */+ class RecordingParam {+ scheduled = false;+ value = 0;+ setValueAtTime(): void {+ this.scheduled = true;+ }+ linearRampToValueAtTime(): void {+ this.scheduled = true;+ }+ setValueCurveAtTime(): void {+ this.scheduled = true;+ }+ cancelScheduledValues(): void {}+ cancelAndHoldAtTime(): void {}+ }++ /**+ * A context whose worklet module registers when asked, and which hands out+ * filters whose gain reports being automated.+ */+ class WorkletCtx extends Ctx {+ currentTime = 0;+ workletsReady = false;+ audioWorklet = {+ addModule: async () => {+ this.workletsReady = true;+ },+ };+ biquads: { gain: RecordingParam }[] = [];+ override createBiquadFilter() {+ const node = new Node("biquad") as unknown as Node & { gain: RecordingParam };+ node.gain = new RecordingParam();+ this.biquads.push(node);+ return node as unknown as Node;+ }+ }++ const carved = {+ version: 1,+ nodes: [+ {+ type: "peaking",+ id: "n1",+ fromCarve: true,+ params: { frequency: 1000, gain: -6, q: 1.4 },+ },+ { type: "compressor", id: "n2", params: {} },+ ],+ };+ const lane = JSON.stringify({+ version: 1,+ lanes: [+ {+ target: "fx.n1.gain",+ points: [+ { t: 0, v: 0 },+ { t: 4, v: -6 },+ ],+ },+ ],+ });++ const audioEl = (): HTMLElement => {+ const node = document.createElement("audio");+ node.setAttribute("data-fx-chain", JSON.stringify(carved));+ node.setAttribute("data-automation", lane);+ document.body.append(node);+ return node;+ };+ const settle = async () => {+ await Promise.resolve();+ await Promise.resolve();+ await new Promise((r) => setTimeout(r, 0));+ };++ it("schedules the carve's envelopes once the processors land", async () => {+ const original = (globalThis as { AudioWorkletNode?: unknown }).AudioWorkletNode;+ (globalThis as { AudioWorkletNode?: unknown }).AudioWorkletNode = WorkletNodeStub;+ try {+ const worklets = new WorkletCtx();+ const src = new Node();+ const dst = new Node();+ const node = audioEl();+ attachElementFxChain(+ worklets as unknown as BaseAudioContext,+ node,+ src as never,+ dst as never,+ {+ scheduledAt: 0,+ elapsed: 0,+ rate: 1,+ },+ );+ // Dry to begin with, which is the whole reason for this path.+ expect(src.connections).toContain(dst);+ await settle();+ // Now routed through the chain — and the envelope is playing, which is+ // what "the carve still works" means.+ expect(src.connections.at(-1)).not.toBe(dst);+ const filter = worklets.biquads[0];+ expect(filter, "the carve's filter was never built").toBeTruthy();+ expect(filter!.gain.scheduled).toBe(true);+ } finally {+ (globalThis as { AudioWorkletNode?: unknown }).AudioWorkletNode = original;+ }+ });++ it("keeps the carve alive when a compressor is added to a playing track", async () => {+ // The reported case, and the worse of the two paths: adding a worklet effect+ // to an already-attached chain rebuilt it, the build threw because nothing+ // on that path had registered the module, and the catch wired the source+ // straight to its gain — dropping the carve's filters along with the+ // compressor. Both symptoms, one cause.+ const original = (globalThis as { AudioWorkletNode?: unknown }).AudioWorkletNode;+ (globalThis as { AudioWorkletNode?: unknown }).AudioWorkletNode = WorkletNodeStub;+ try {+ const worklets = new WorkletCtx();+ const src = new Node();+ const dst = new Node();+ // Starts with the carve only: no worklets, so it attaches immediately.+ const node = document.createElement("audio");+ node.setAttribute(+ "data-fx-chain",+ JSON.stringify({+ version: 1,+ nodes: [+ {+ type: "peaking",+ id: "n1",+ fromCarve: true,+ params: { frequency: 1000, gain: -6, q: 1.4 },+ },+ ],+ }),+ );+ node.setAttribute("data-automation", lane);+ document.body.append(node);+ attachElementFxChain(+ worklets as unknown as BaseAudioContext,+ node,+ src as never,+ dst as never,+ { scheduledAt: 0, elapsed: 0, rate: 1 },+ );+ expect(worklets.biquads[0]!.gain.scheduled).toBe(true);++ // Now add the compressor, as the panel's "Add effect" does.+ node.setAttribute("data-fx-chain", JSON.stringify(carved));+ await settle();++ // Still routed through a chain rather than dry, the carve's filter rebuilt,+ // and its envelope scheduled onto the new one.+ expect(src.connections.at(-1)).not.toBe(dst);+ const rebuilt = worklets.biquads.at(-1)!;+ expect(rebuilt.gain.scheduled).toBe(true);+ } finally {+ (globalThis as { AudioWorkletNode?: unknown }).AudioWorkletNode = original;+ }+ });++ it("follows the attribute after the late build, as any other chain does", async () => {+ const original = (globalThis as { AudioWorkletNode?: unknown }).AudioWorkletNode;+ (globalThis as { AudioWorkletNode?: unknown }).AudioWorkletNode = WorkletNodeStub;+ try {+ const worklets = new WorkletCtx() as unknown as BaseAudioContext;+ const src = new Node();+ const dst = new Node();+ const node = audioEl();+ attachElementFxChain(worklets, node, src as never, dst as never, {+ scheduledAt: 0,+ elapsed: 0,+ rate: 1,+ });+ await settle();+ const before = src.connections.at(-1);+ node.setAttribute(+ "data-fx-chain",+ JSON.stringify({+ version: 1,+ nodes: [{ type: "lowpass", id: "n9", params: { frequency: 900, q: 1, poles: "2" } }],+ }),+ );+ await settle();+ expect(src.connections.at(-1)).not.toBe(before);+ } finally {+ (globalThis as { AudioWorkletNode?: unknown }).AudioWorkletNode = original;+ }+ });+ });++ /**+ * Every effect in the registry, one at a time.+ *+ * The limiter/compressor bug was not really about worklets: it was a build that+ * threw inside `attach`, whose catch wires the source straight to its gain —+ * dropping every other effect in the chain, the carve's filters included. Any+ * effect whose construction can fail has the same shape, so this asserts the two+ * things that were broken for all fourteen: the chain reaches the signal path,+ * and an envelope on it gets scheduled.+ */+ describe("every registry effect, in the signal path", () => {+ class RecordingParam {+ scheduled = false;+ value = 0;+ setValueAtTime(): void {+ this.scheduled = true;+ }+ linearRampToValueAtTime(): void {+ this.scheduled = true;+ }+ setValueCurveAtTime(): void {+ this.scheduled = true;+ }+ cancelScheduledValues(): void {}+ cancelAndHoldAtTime(): void {}+ }+ class RecordingNode extends Node {+ override frequency = new RecordingParam() as unknown as { value: number };+ override Q = new RecordingParam() as unknown as { value: number };+ override gain = new RecordingParam() as unknown as { value: number };+ override delayTime = new RecordingParam() as unknown as { value: number };+ port = { postMessage: () => {} };+ }+ class RichCtx extends Ctx {+ currentTime = 0;+ workletsReady = false;+ made: RecordingNode[] = [];+ audioWorklet = {+ addModule: async () => {+ this.workletsReady = true;+ },+ };+ private make(): Node {+ const node = new RecordingNode("node");+ this.made.push(node);+ return node as unknown as Node;+ }+ override createGain() {+ return this.make();+ }+ override createBiquadFilter() {+ return this.make();+ }+ override createIIRFilter() {+ return this.make();+ }+ override createDelay() {+ return this.make();+ }+ override createOscillator() {+ return this.make();+ }+ override createWaveShaper() {+ return this.make();+ }+ override createConvolver() {+ return this.make();+ }+ }+ class WorkletNode extends RecordingNode {+ constructor(ctx: { workletsReady?: boolean }, name: string) {+ super("worklet");+ if (!ctx.workletsReady) {+ throw new Error(`AudioWorkletNode: processor "${name}" is not registered`);+ }+ }+ }+ const settle = async () => {+ await Promise.resolve();+ await Promise.resolve();+ await new Promise((r) => setTimeout(r, 0));+ };++ for (const def of HF_AUDIO_FX) {+ const automatable = def.params.find((p) => p.kind === "number" && p.automatable);++ it(`routes ${def.id} and plays its envelope`, async () => {+ const original = (globalThis as { AudioWorkletNode?: unknown }).AudioWorkletNode;+ (globalThis as { AudioWorkletNode?: unknown }).AudioWorkletNode = WorkletNode;+ try {+ const ctxRich = new RichCtx();+ const src = new Node();+ const dst = new Node();+ const node = document.createElement("audio");+ node.setAttribute(+ "data-fx-chain",+ JSON.stringify({+ version: 1,+ nodes: [{ type: def.id, id: "n1", params: defaultAudioFxParams(def.id) }],+ }),+ );+ if (automatable && automatable.kind === "number") {+ node.setAttribute(+ "data-automation",+ JSON.stringify({+ version: 1,+ lanes: [+ {+ target: `fx.n1.${automatable.key}`,+ points: [+ { t: 0, v: automatable.default },+ { t: 4, v: automatable.max },+ ],+ },+ ],+ }),+ );+ }+ document.body.append(node);+ attachElementFxChain(+ ctxRich as unknown as BaseAudioContext,+ node,+ src as never,+ dst as never,+ { scheduledAt: 0, elapsed: 0, rate: 1 },+ );+ await settle();++ // Not dry: the effect is between the source and its gain.+ expect(src.connections.at(-1), `${def.id} was left out of the path`).not.toBe(dst);+ if (automatable) {+ const scheduled = ctxRich.made.some((n) =>+ [n.frequency, n.Q, n.gain, n.delayTime].some(+ (p) => (p as unknown as RecordingParam).scheduled,+ ),+ );+ // A worklet exposes no AudioParams, so a lane on one has nowhere to+ // write — that is by design and the scheduler skips it.+ if (!def.web.startsWith("worklet-")) {+ expect(scheduled, `${def.id}'s envelope was never scheduled`).toBe(true);+ }+ }+ } finally {+ (globalThis as { AudioWorkletNode?: unknown }).AudioWorkletNode = original;+ }+ });+ }+ });});diff --git a/packages/core/src/runtime/audioFx.ts b/packages/core/src/runtime/audioFx.tsindex dd9b7b7dcb..835aec965c 100644--- a/packages/core/src/runtime/audioFx.ts+++ b/packages/core/src/runtime/audioFx.ts@@ -19,6 +19,7 @@ import {} from "../audioAutomation.js";import {cancelParamLane,+ clearParamLane,scheduleChainAutomation,type AutomationTiming,} from "../audio/audioFxAutomation.js";@@ -103,41 +104,15 @@ export function attachElementFxChain(): { dispose(): void } | null {const { chain } = readChain(el);- // An AudioWorkletNode cannot be constructed before its processor is- // registered — it throws, and the whole chain is lost. So when the chain- // needs worklets and the module has not landed yet, play dry and swap the- // graph in once registration resolves.- if (chainNeedsWorklets(chain) && !audioFxWorkletsReady(ctx)) {- source.connect(destination);- let cancelled = false;- let pending: FxChainHandle | null = null;- void ensureAudioFxWorklets(ctx)- .then(() => {- if (cancelled) return;- try {- const late = buildFxChain(ctx, chain);- source.disconnect(destination);- source.connect(late.input);- late.output.connect(destination);- pending = late;- } catch {- // Still unbuildable; the dry connection already stands.- }- })- .catch(() => undefined);- return {- dispose: () => {- cancelled = true;- pending?.dispose();- },- };- }-// Null means the source runs straight into its gain: an empty chain, or one// that could not be realised. Mutable because a structural edit swaps the// whole graph rather than re-parameterising it.let handle: FxChainHandle | null = null;let automated: FxParamTarget[] = [];+ let disposed = false;+ /** Bumped per attach, so a worklet wait that resolves late cannot revive a+ * chain the element has since moved on from. */+ let workletGeneration = 0;/** Take the current graph out of the path, leaving the source connected dry. */const detach = (): void => {@@ -166,6 +141,28 @@ export function attachElementFxChain(source.connect(destination);return;}+ // An AudioWorkletNode cannot be constructed before its processor is+ // registered — it throws, and the whole chain is lost. So a chain holding a+ // limiter, compressor, gate or bitcrush plays dry until the module lands and+ // then takes the ordinary rebuild path.+ //+ // That wait used to return early from the whole function, which left the+ // track with no automation scheduled and no observer on the attribute: adding+ // a compressor to a carved bed killed the carve's envelopes and froze every+ // later edit until the composition reloaded. Rebuilding through the same path+ // an edit uses is what keeps those two working.+ if (chainNeedsWorklets(next) && !audioFxWorkletsReady(ctx)) {+ source.connect(destination);+ const generation = ++workletGeneration;+ void ensureAudioFxWorklets(ctx)+ .then(() => {+ // Stale if the element was disposed or the chain changed while waiting.+ if (disposed || generation !== workletGeneration) return;+ rebuild(readChain(el).chain);+ })+ .catch(() => undefined);+ return;+ }try {const built = buildFxChain(ctx, next);source.connect(built.input);@@ -235,6 +232,13 @@ export function attachElementFxChain() {observer = new MutationObserver(() => {const next = readChain(el);+ // Clear the booked envelopes before touching the graph. `update` writes each+ // knob straight onto its AudioParam, and a write landing inside a running+ // curve is refused with NotSupportedError unless the param is cancelled+ // first — so an edit made while one was playing threw instead of applying,+ // and the console filled with uncaught errors. The reschedule below puts the+ // envelope back from the current playhead.+ if (automated.length > 0) clearParamLane(automated);// `update` reports false when the change is structural rather than a new// set of values, which is the signal to swap the graph.if (!handle || !handle.update(next.chain)) rebuild(next.chain);@@ -248,6 +252,7 @@ export function attachElementFxChain(return {dispose: () => {+ disposed = true;observer?.disconnect();if (automated.length > 0) {cancelParamLane(automated, typeof ctx.currentTime === "number" ? ctx.currentTime : 0);diff --git a/packages/producer/src/services/render/stages/audioStage.ts b/packages/producer/src/services/render/stages/audioStage.tsindex 89739aede6..ac243dd825 100644--- a/packages/producer/src/services/render/stages/audioStage.ts+++ b/packages/producer/src/services/render/stages/audioStage.ts@@ -24,6 +24,7 @@ import {type AudioProcessingFailure,} from "@hyperframes/engine";import type { CompositionMetadata } from "../shared.js";+import type { ProducerLogger } from "../../../logger.js";export interface AudioStageInput {projectDir: string;@@ -36,6 +37,8 @@ export interface AudioStageInput {audios: CompositionMetadata["audios"];abortSignal: AbortSignal | undefined;assertNotAborted: () => void;+ /** Where a per-track failure's detail goes. Optional so tests need not pass one. */+ log?: ProducerLogger;}export interface AudioStageResult {@@ -56,7 +59,7 @@ export interface AudioStageResult {}export async function runAudioStage(input: AudioStageInput): Promise<AudioStageResult> {- const { projectDir, workDir, compiledDir, duration, audios, abortSignal, assertNotAborted } =+ const { projectDir, workDir, compiledDir, duration, audios, abortSignal, assertNotAborted, log } =input;const stage3Start = Date.now();@@ -103,7 +106,23 @@ export async function runAudioStage(input: AudioStageInput): Promise<AudioStageR// error) used to be discarded here — the caller only saw hasAudio flip to// false with no explanation, so a real audio failure looked identical to// "no audio was authored" and shipped a silent video-only render.- if (!hasAudio) audioError = audioResult.error ?? "audio mix failed for an unknown reason";+ if (!hasAudio) {+ audioError = audioResult.error ?? "audio mix failed for an unknown reason";+ // Each failure's `detail` names the element and what went wrong with it,+ // and it was going nowhere: the render printed the warning code and+ // dropped everything that said why, so an audio failure could only be+ // diagnosed by re-running the mixer by hand outside the pipeline.+ for (const failure of audioResult.failures ?? []) {+ log?.warn("Audio track failed", {+ elementId: failure.elementId,+ stage: failure.stage,+ reason: failure.reason,+ owner: failure.owner,+ retryable: failure.retryable,+ detail: failure.detail,+ });+ }+ }}const audioProcessMs = Date.now() - stage3Start;diff --git a/packages/producer/src/services/renderOrchestrator.ts b/packages/producer/src/services/renderOrchestrator.tsindex e5d67c6d06..762dde215c 100644--- a/packages/producer/src/services/renderOrchestrator.ts+++ b/packages/producer/src/services/renderOrchestrator.ts@@ -2532,6 +2532,7 @@ async function executeRenderPipeline(input: {audios: composition.audios,abortSignal: executionSignal,assertNotAborted,+ log,}),);const { audioOutputPath, hasAudio } = audioResult;diff --git a/packages/studio/src/components/editor/PropertyPanel.test.tsx b/packages/studio/src/components/editor/PropertyPanel.test.tsxindex 82098f3774..a1a3c7a01a 100644--- a/packages/studio/src/components/editor/PropertyPanel.test.tsx+++ b/packages/studio/src/components/editor/PropertyPanel.test.tsx@@ -238,7 +238,11 @@ async function renderPanel(// renderPanel resetModules()+dynamic-imports PropertyPanel (needed for a fresh// flag read); transforming the full section graph uncached can exceed the 5s// default under heavy parallel full-suite load, so give these a wider margin.-const RENDER_TIMEOUT_MS = 20_000;+// 20s itself has now been observed timing out in CI's full-monorepo run (the+// same suite passes in well under 2s standalone) — widened again rather than+// re-tuned down to a number that will just need doing again next time CI adds+// load.+const RENDER_TIMEOUT_MS = 45_000;// Find the collapsed accordion row whose title matches and click it open.function openFlatGroup(host: HTMLElement, title: string) {diff --git a/packages/studio/src/components/editor/propertyPanelAudioFxGroup.test.tsx b/packages/studio/src/components/editor/propertyPanelAudioFxGroup.test.tsxindex de4153689b..e176af0cf3 100644--- a/packages/studio/src/components/editor/propertyPanelAudioFxGroup.test.tsx+++ b/packages/studio/src/components/editor/propertyPanelAudioFxGroup.test.tsx@@ -246,7 +246,7 @@ describe("AudioFxGroup carve", () => {act(() => carveToggle(host).click());const write = onSetAttributeQuiet.mock.calls.find((c) => c[0] === "data-fx-carve");expect(write).toBeTruthy();- expect(JSON.parse(String(write![1])).bands).toBeGreaterThan(0);+ expect(JSON.parse(String(write![1])).strength).toBeGreaterThan(0);});});diff --git a/packages/studio/src/components/editor/propertyPanelAudioFxGroup.tsx b/packages/studio/src/components/editor/propertyPanelAudioFxGroup.tsxindex 0a04892e97..2d56849959 100644--- a/packages/studio/src/components/editor/propertyPanelAudioFxGroup.tsx+++ b/packages/studio/src/components/editor/propertyPanelAudioFxGroup.tsx@@ -17,6 +17,7 @@ import {import {analyseCarveBands,carveBandsToChain,+ carveProfile,HF_AUDIO_CARVE_ATTR,normalizeCarveSettings,type HfCarveSettings,@@ -192,7 +193,11 @@ export function AudioFxGroup({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, carve);+ const bands = analyseCarveBands(+ buffer.getChannelData(0),+ buffer.sampleRate,+ carveProfile(carve.strength),+ );const carved = carveBandsToChain(bands);// Carve output is tagged so a re-run replaces it instead of stacking.const kept = chain.nodes.filter((n) => !n.fromCarve);diff --git a/packages/studio/src/components/editor/propertyPanelFxSection.tsx b/packages/studio/src/components/editor/propertyPanelFxSection.tsxindex 56b7b09132..8e629af84b 100644--- a/packages/studio/src/components/editor/propertyPanelFxSection.tsx+++ b/packages/studio/src/components/editor/propertyPanelFxSection.tsx@@ -487,51 +487,19 @@ export function FxSection({<FxParamRowparam={{kind: "number",- key: "maxCutDb",- label: "Depth",- unit: "dB",- min: 0,- max: 24,- step: 0.5,- default: DEFAULT_CARVE.maxCutDb,- }}- value={carve.maxCutDb}- disabled={disabled}- onChange={(_k, v) => previewCarve({ ...carve, maxCutDb: Number(v) })}- onCommit={(_k, v) => onCarveChange({ ...carve, maxCutDb: Number(v) })}- />- <FxParamRow- param={{- kind: "number",- key: "bands",- label: "Bands",- unit: "",- min: 1,- max: 6,- step: 1,- default: DEFAULT_CARVE.bands,- }}- value={carve.bands}- disabled={disabled}- onChange={(_k, v) => previewCarve({ ...carve, bands: Number(v) })}- onCommit={(_k, v) => onCarveChange({ ...carve, bands: Number(v) })}- />- <FxParamRow- param={{- kind: "number",- key: "intelligibilityBias",- label: "Speech bias",+ key: "strength",+ label: "Strength",unit: "",min: 0,max: 1,- step: 0.05,- default: DEFAULT_CARVE.intelligibilityBias,- hint: "At 0 the deepest cuts follow raw voice energy, which lands on the fundamental. Higher weights selection toward 1-3 kHz, where a bed actually masks a voice.",+ step: 0.01,+ 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.",}}- value={carve.intelligibilityBias}+ value={carve.strength}disabled={disabled}- onChange={(_k, v) => previewCarve({ ...carve, intelligibilityBias: Number(v) })}- onCommit={(_k, v) => onCarveChange({ ...carve, intelligibilityBias: Number(v) })}+ onChange={(_k, v) => previewCarve({ ...carve, strength: Number(v) })}+ onCommit={(_k, v) => onCarveChange({ ...carve, strength: Number(v) })}/><buttontype="button"diff --git a/packages/studio/src/hooks/useAutomationSelectionKeyboard.test.tsx b/packages/studio/src/hooks/useAutomationSelectionKeyboard.test.tsxindex f8ab1a3d76..6fb1230447 100644--- a/packages/studio/src/hooks/useAutomationSelectionKeyboard.test.tsx+++ b/packages/studio/src/hooks/useAutomationSelectionKeyboard.test.tsx@@ -16,6 +16,17 @@ import type {} from "../player/components/useAutomationLanes";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.+ */+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 };+}+/** Minimal valid fixture — TimelineElement only requires these five fields. */const bgmElement: TimelineElement = {id: "bgm",@@ -110,7 +121,7 @@ describe("useAutomationSelectionKeyboard", () => {usePlayerStore.setState({ elements: [bgmElement], selectedElementId: "bgm" });usePlayerStore.getState()- .setAutomationSelection({ elementKey: "bgm", target: "volume", t0: 1, t1: 3 });+ .setAutomationSelection(wholeAxis({ elementKey: "bgm", target: "volume", t0: 1, t1: 3 }));const { onCommit } = setup({});key("Delete");const written = onCommit.mock.calls.at(-1)?.[0];@@ -121,7 +132,7 @@ describe("useAutomationSelectionKeyboard", () => {it("Escape clears the selection", () => {usePlayerStore.getState()- .setAutomationSelection({ elementKey: "bgm", target: "volume", t0: 1, t1: 3 });+ .setAutomationSelection(wholeAxis({ elementKey: "bgm", target: "volume", t0: 1, t1: 3 }));setup({});key("Escape");expect(usePlayerStore.getState().automationSelection).toBeNull();@@ -130,7 +141,7 @@ describe("useAutomationSelectionKeyboard", () => {it("is inert while a text input has focus", () => {usePlayerStore.getState()- .setAutomationSelection({ elementKey: "bgm", target: "volume", t0: 1, t1: 3 });+ .setAutomationSelection(wholeAxis({ elementKey: "bgm", target: "volume", t0: 1, t1: 3 }));const { onCommit } = setup({});const input = document.createElement("input");document.body.append(input);@@ -145,7 +156,7 @@ describe("useAutomationSelectionKeyboard", () => {usePlayerStore.setState({ elements: [bgmElement], selectedElementId: "bgm" });usePlayerStore.getState()- .setAutomationSelection({ elementKey: "bgm", target: "volume", t0: 2, t1: 4 });+ .setAutomationSelection(wholeAxis({ elementKey: "bgm", target: "volume", t0: 2, t1: 4 }));setup({});combo("c");const entry = readClipboard(null);@@ -165,7 +176,7 @@ describe("useAutomationSelectionKeyboard", () => {});usePlayerStore.getState()- .setAutomationSelection({ elementKey: "bgm", target: "volume", t0: 2, t1: 4 });+ .setAutomationSelection(wholeAxis({ elementKey: "bgm", target: "volume", t0: 2, t1: 4 }));const { onCommit } = setup({});combo("c");expect(readClipboard(null)?.span).toBe(2);@@ -183,6 +194,8 @@ describe("useAutomationSelectionKeyboard", () => {target: "volume",t0: 5,t1: 7,+ v0: VOLUME_RANGE.min,+ v1: VOLUME_RANGE.max,});});@@ -196,7 +209,7 @@ describe("useAutomationSelectionKeyboard", () => {});usePlayerStore.getState()- .setAutomationSelection({ elementKey: "bgm", target: "volume", t0: 2, t1: 4 });+ .setAutomationSelection(wholeAxis({ elementKey: "bgm", target: "volume", t0: 2, t1: 4 }));const { onCommit } = setup({});combo("c");@@ -218,6 +231,8 @@ describe("useAutomationSelectionKeyboard", () => {target: "volume",t0: 4,t1: 6,+ v0: VOLUME_RANGE.min,+ v1: VOLUME_RANGE.max,});});@@ -230,7 +245,7 @@ describe("useAutomationSelectionKeyboard", () => {usePlayerStore.setState({ elements: [bgmElement], selectedElementId: "bgm" });usePlayerStore.getState()- .setAutomationSelection({ elementKey: "bgm", target: "volume", t0: 2, t1: 4 });+ .setAutomationSelection(wholeAxis({ elementKey: "bgm", target: "volume", t0: 2, t1: 4 }));const { onCommit } = setup({});combo("c");expect(readClipboard(null)?.span).toBe(2);@@ -238,7 +253,7 @@ describe("useAutomationSelectionKeyboard", () => {// A 0.1s-wide selection right near the clip's 6s end.usePlayerStore.getState()- .setAutomationSelection({ elementKey: "bgm", target: "volume", t0: 5.5, t1: 5.6 });+ .setAutomationSelection(wholeAxis({ elementKey: "bgm", target: "volume", t0: 5.5, t1: 5.6 }));combo("v");const written = onCommit.mock.calls.at(-1)?.[0];const times = (written?.lanes?.[0]?.points ?? []).map((p: { t: number }) => p.t);@@ -252,6 +267,8 @@ describe("useAutomationSelectionKeyboard", () => {target: "volume",t0: 4,t1: 6,+ v0: VOLUME_RANGE.min,+ v1: VOLUME_RANGE.max,});});@@ -264,7 +281,7 @@ describe("useAutomationSelectionKeyboard", () => {usePlayerStore.setState({ elements: [bgmElement], selectedElementId: "bgm" });usePlayerStore.getState()- .setAutomationSelection({ elementKey: "bgm", target: "volume", t0: 2, t1: 4 });+ .setAutomationSelection(wholeAxis({ elementKey: "bgm", target: "volume", t0: 2, t1: 4 }));const { onCommit } = setup({ commitTargetKey: "some-other-clip" });const e = combo("v");expect(e.defaultPrevented).toBe(false);@@ -282,7 +299,7 @@ describe("useAutomationSelectionKeyboard", () => {});usePlayerStore.getState()- .setAutomationSelection({ elementKey: "bgm", target: "volume", t0: 2, t1: 4 });+ .setAutomationSelection(wholeAxis({ elementKey: "bgm", target: "volume", t0: 2, t1: 4 }));const { onCommit } = setup({});combo("c");usePlayerStore.getState().clearAutomationSelection();@@ -302,7 +319,7 @@ describe("useAutomationSelectionKeyboard", () => {usePlayerStore.setState({ elements: [bgmElement], selectedElementId: "bgm" });usePlayerStore.getState()- .setAutomationSelection({ elementKey: "bgm", target: "volume", t0: 1, t1: 2 });+ .setAutomationSelection(wholeAxis({ elementKey: "bgm", target: "volume", t0: 1, t1: 2 }));setup({ automation: { version: 1, lanes: [{ target: "volume", points: [] }] } });const e = combo("c");@@ -315,7 +332,7 @@ describe("useAutomationSelectionKeyboard", () => {usePlayerStore.setState({ elements: [bgmElement], selectedElementId: "bgm" });usePlayerStore.getState()- .setAutomationSelection({ elementKey: "bgm", target: "volume", t0: 2, t1: 4 });+ .setAutomationSelection(wholeAxis({ elementKey: "bgm", target: "volume", t0: 2, t1: 4 }));const { onCommit } = setup({});combo("C");expect(readClipboard(null)?.span).toBe(2);diff --git a/packages/studio/src/hooks/useAutomationSelectionKeyboard.ts b/packages/studio/src/hooks/useAutomationSelectionKeyboard.tsindex 354fd7342b..8dfb9704ac 100644--- a/packages/studio/src/hooks/useAutomationSelectionKeyboard.ts+++ b/packages/studio/src/hooks/useAutomationSelectionKeyboard.ts@@ -246,8 +246,17 @@ 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.- const mark = { elementKey: paste.elementKey, target: paste.target, t0: atT, t1 };+ // 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.+ const mark = {+ elementKey: paste.elementKey,+ target: paste.target,+ t0: atT,+ t1,+ v0: paste.range.min,+ v1: paste.range.max,+ };state.setAutomationSelection(mark);markLastPaste(mark);return true;diff --git a/packages/studio/src/hooks/useDomEditAttributeCommits.ts b/packages/studio/src/hooks/useDomEditAttributeCommits.tsindex d4e76c2cb8..7b7a96de93 100644--- a/packages/studio/src/hooks/useDomEditAttributeCommits.ts+++ b/packages/studio/src/hooks/useDomEditAttributeCommits.ts@@ -8,6 +8,7 @@ import {import type { PersistDomEditOperations } from "./domEditCommitTypes";import { reportDomEditPersistFailure } from "./domEditPersistFailure";import { bumpDomEditCommitMapVersion, runDomEditCommit } from "./domEditCommitRunner";+import { syncStoredAutomationFromPreview } from "../player/lib/automationStoreSync";// ── Types ──@@ -26,6 +27,26 @@ interface DataAttributeCommitOptions {skipRefresh: boolean;refreshAfter?: boolean;onSettled?: (ok: boolean) => void;+ /**+ * Undo grouping for a gesture that spans several commits.+ *+ * Without it the key is derived from the prefix, attribute and element, and the+ * window is history's own 300ms — so a drag's moves and the release that ends it+ * landed in different entries, and a drag slower than the window split further.+ * A caller that knows a gesture is in progress passes one key for all of it.+ */+ coalesce?: { key: string; ms: number };+ /**+ * Apply to the preview and stop there — no file write, no history entry.+ *+ * What a gesture wants from every pointermove: the preview document and the+ * audio graph following the pointer, with the file written once on release.+ * Persisting each move put a fragment of one drag in the undo stack, and since+ * those writes race, a follow-up's "before" was often not the previous entry's+ * "after" — history refuses to coalesce across that gap, so undo took back a+ * few milliseconds of the gesture and looked like it had done nothing.+ */+ previewOnly?: boolean;}function resolveFullAttrName(attr: string, prefixData: boolean | undefined): string {@@ -108,7 +129,9 @@ export function useDomEditAttributeCommits({if (!domEditSelection) return;const iframe = previewIframeRef.current;const fullAttr = resolveFullAttrName(attr, true);- const commitKey = `${options.coalescePrefix}:${attr}:${getDomEditTargetKey(domEditSelection)}`;+ const commitKey =+ options.coalesce?.key ??+ `${options.coalescePrefix}:${attr}:${getDomEditTargetKey(domEditSelection)}`;const isLatestCommit = bumpDomEditCommitMapVersion(domAttributeCommitVersionRef.current,commitKey,@@ -134,12 +157,15 @@ export function useDomEditAttributeCommits({const nextValue = value === null || value === "" ? null : value;setOrRemovePreviewAttribute(editedElement, fullAttr, nextValue);},- persist: () =>- persistDomEditOperations(domEditSelection, [op], {- label: options.label,- coalesceKey: commitKey,- skipRefresh: options.skipRefresh,- }),+ persist: options.previewOnly+ ? async () => {}+ : () =>+ persistDomEditOperations(domEditSelection, [op], {+ label: options.label,+ coalesceKey: commitKey,+ ...(options.coalesce ? { coalesceMs: options.coalesce.ms } : {}),+ skipRefresh: options.skipRefresh,+ }),shouldRevert: () => isLatestCommit(),revert: () => {if (!editedElement) return;@@ -147,7 +173,19 @@ export function useDomEditAttributeCommits({},onError: (error) => reportDomEditPersistFailure(domEditSelection, [op], error, showToast),shouldResync: () => isLatestCommit() && !!options.refreshAfter,- 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);+ },onSettled: options.onSettled,});},@@ -273,12 +311,19 @@ export function useDomEditAttributeCommits({);const handleDomAttributeLiveCommit = useCallback(- async (attr: string, value: string | null, onSettled?: (ok: boolean) => void) => {+ async (+ attr: string,+ value: string | null,+ onSettled?: (ok: boolean) => void,+ live?: { coalesce?: { key: string; ms: number }; previewOnly?: boolean },+ ) => {await commitDataAttribute(attr, value, {label: `Edit ${attr.replace(/^(data-)?/, "").replace(/-/g, " ")}`,coalescePrefix: "attr-live",skipRefresh: true,onSettled,+ ...(live?.coalesce ? { coalesce: live.coalesce } : {}),+ ...(live?.previewOnly ? { previewOnly: true } : {}),});},[commitDataAttribute],@@ -294,12 +339,13 @@ export function useDomEditAttributeCommits({* edit computes from a pre-edit value and appears to do nothing.*/const handleDomAttributeQuietCommit = useCallback(- async (attr: string, value: string | null) => {+ async (attr: string, value: string | null, coalesce?: { key: string; ms: number }) => {await commitDataAttribute(attr, value, {label: `Edit ${attr.replace(/^(data-)?/, "").replace(/-/g, " ")}`,coalescePrefix: "attr-quiet",skipRefresh: true,refreshAfter: true,+ ...(coalesce ? { coalesce } : {}),});},[commitDataAttribute],diff --git a/packages/studio/src/player/components/TimelineAutomationLane.test.tsx b/packages/studio/src/player/components/TimelineAutomationLane.test.tsxindex 961c5f42b6..d162ca4b0a 100644--- a/packages/studio/src/player/components/TimelineAutomationLane.test.tsx+++ b/packages/studio/src/player/components/TimelineAutomationLane.test.tsx@@ -7,6 +7,7 @@ import { PAD_X } from "./automationLaneGeometry";import { AUTOMATION_LANE_H } from "./automationLaneHeight";import type { HfAudioFxChain } from "@hyperframes/core/audio-fx";import {+ normalizeAutomation,resolveAutomationRange,VOLUME_RANGE,type HfAutomation,@@ -89,6 +90,7 @@ function fire(buttons?: number;altKey?: boolean;shiftKey?: boolean;+ key?: string;} = {},): void {const event = new Event(type, { bubbles: true, cancelable: true });@@ -197,24 +199,65 @@ describe("TimelineAutomationLane", () => {expect(svgWidth).toBe(400 + PAD * 2);});- it("shows the parameter name in full, never clamped to a narrow gutter", () => {- // A clip starting at zero leaves no gutter; the label used to be clamped to- // 60px there and read "Low-pass ...".+ it("draws no plate behind the envelope", () => {+ // The lane used to darken its clip's width, which put a box inside the row and+ // made a stack of lanes read as tiles rather than rows of one timeline. Only the+ // selection rectangle may fill area now, and only while a range is selected.+ const { container } = render(<TimelineAutomationLane {...laneProps({ automation: ramp })} />);+ expect(container.querySelectorAll("rect")).toHaveLength(0);+ });++ it("still fills the selected range, which is the one rectangle it draws", () => {+ const { container } = render(+ <TimelineAutomationLane+ {...laneProps({ automation: ramp, rangeSelection: { t0: 1, t1: 3, v0: 0, v1: 1 } })}+ />,+ );+ const rects = container.querySelectorAll("rect");+ expect(rects).toHaveLength(1);+ expect(rects[0]?.getAttribute("data-automation-selection")).toBe("");+ });++ it("divides one lane from the next with a separator", () => {+ // A stack of envelopes with no rule between them reads as one tall field, and a+ // point near a boundary looks like it belongs to either lane.+ const { container } = render(<TimelineAutomationLane {...laneProps({ automation: ramp })} />);+ const border = container.querySelector<HTMLElement>("[data-automation-lane-border]");+ expect(border).not.toBeNull();+ expect(border?.style.height).toBe("1px");+ // Full row width, not just the clip's: it is a lane divider, not part of the clip.+ expect(border?.style.left).toBe("0px");+ expect(border?.style.right).toBe("0px");+ // Cannot eat a press aimed at the envelope underneath it.+ expect(border?.className).toContain("pointer-events-none");+ });++ it("keeps the lane's own height, so the separator cannot shift the geometry", () => {+ // Drawn as an overlay rather than a CSS border for this reason: hit testing maps+ // pointer positions through the svg's box, and a border would move it by a pixel.+ const { container } = render(<TimelineAutomationLane {...laneProps({ automation: ramp })} />);+ const lane = container.querySelector<HTMLElement>(".hf-automation-lane");+ const svg = container.querySelector("svg");+ expect(lane?.style.height).toBe(`${AUTOMATION_LANE_H}px`);+ expect(svg?.getAttribute("height")).toBe(String(AUTOMATION_LANE_H));+ });++ it("draws no name of its own — the label column owns it", () => {+ // Over the envelope the name obscured the curve it described, and it scrolled+ // with the canvas away from the row it belonged to. TimelineTrackHeader names+ // each lane in the sticky column instead, on the keyframe rows' own tree.const { container } = render(<TimelineAutomationLane {...laneProps({ target: "fx.n1.frequency", leftPx: 0 })} />,);- const name = container.querySelector<HTMLElement>(".hf-automation-name")!;- expect(name.textContent).toBe("Low-pass · Cutoff");- expect(name.className).not.toMatch(/truncate/);- expect(name.style.maxWidth).toBe("");+ expect(container.querySelector(".hf-automation-name")).toBeNull();+ expect(container.textContent).not.toMatch(/Cutoff/);});- it("names the parameter it draws, rather than offering a control to swap it", () => {+ it("offers no control to swap which parameter it draws", () => {const { container } = render(<TimelineAutomationLane {...laneProps({ target: "fx.n1.frequency" })} />,);expect(container.querySelector("select")).toBeNull();- expect(container.querySelector(".hf-automation-name")?.textContent).toMatch(/Cutoff/);});it("adds a point on double-click, at the value the pointer was at", () => {@@ -395,6 +438,75 @@ describe("TimelineAutomationLane", () => {expect(onPreview).not.toHaveBeenCalled();});+ it("marks the points a range has caught, by the same rule Delete uses", () => {+ // Feedback the tinted rectangle cannot give: which POINTS are in the range. The+ // rule has to match the delete path exactly, edges included, or the highlight+ // promises something different from what the key does.+ const dense: HfAutomation = {+ version: 1,+ lanes: [+ {+ target: "volume",+ points: [+ { t: 0, v: 1 },+ { t: 1, v: 0.8 },+ { t: 2, v: 0.5 },+ { t: 3, v: 0.2 },+ { t: 4, v: 0 },+ ],+ },+ ],+ };+ const { container } = render(+ <TimelineAutomationLane+ {...laneProps({ automation: dense, rangeSelection: { t0: 1, t1: 3, v0: 0, v1: 1 } })}+ />,+ );+ const marked = Array.from(container.querySelectorAll("[data-automation-point-in-range]"));+ expect(marked).toHaveLength(3); // t=1 and t=3 sit ON the edges and count+ const radii = marked.map((c) => Number(c.getAttribute("r")));+ const plain = Array.from(container.querySelectorAll("[data-automation-point]"))+ .filter((c) => !c.hasAttribute("data-automation-point-in-range"))+ .map((c) => Number(c.getAttribute("r")));+ // Bigger than the points around them, and ringed rather than recoloured — the+ // fill is the parameter's own colour and stays that way.+ expect(Math.min(...radii)).toBeGreaterThan(Math.max(...plain));+ expect(marked[0]?.getAttribute("stroke")).toBe("#fff");+ });++ it("marks nothing when there is no range", () => {+ const { container } = render(<TimelineAutomationLane {...laneProps({ automation: ramp })} />);+ expect(container.querySelectorAll("[data-automation-point-in-range]")).toHaveLength(0);+ });++ it("draws a range on the very first drag over a read-only lane", () => {+ // The papercut: the press that selects the clip used to be spent entirely on+ // selecting, so the first drag over a lane did nothing visible and a range took+ // two gestures. One gesture now selects AND draws the range — the selection is+ // ephemeral store state, and nothing can be written through it while the lane+ // is still read-only.+ const onSelect = vi.fn();+ const onRangeSelect = vi.fn();+ const { svg, props } = mount(ramp, { readOnly: true, onSelect, onRangeSelect });+ fire(svg, "pointerdown", at(1, 0.5));+ fire(svg, "pointermove", at(2, 0.5));+ fire(svg, "pointermove", at(3, 0.5));+ fire(svg, "pointerup", at(3, 0.5));++ expect(onSelect).toHaveBeenCalledTimes(1);+ // A flat drag draws a flat box: same value at both corners, since the pointer+ // never left that height.+ expect(onRangeSelect).toHaveBeenLastCalledWith(+ expect.closeTo(1, 1),+ expect.closeTo(3, 1),+ expect.closeTo(0.5, 1),+ expect.closeTo(0.5, 1),+ );+ // Still read-only: selecting is a separate thing from editing.+ expect(props.onCommit).not.toHaveBeenCalled();+ expect(props.onPreview).not.toHaveBeenCalled();+ });+it("selects the clip when pressed read-only, the only route to editing it", () => {// The lane sits below the clip bar, so the timeline's own selection handler// never sees this press. Without selecting here the lane could never be@@ -487,6 +599,64 @@ const mount = (automation: HfAutomation, over: Record<string, unknown> = {}) =>return { container, svg, props };};+describe("TimelineAutomationLane point visibility", () => {+ const opacityOf = (container: HTMLElement, i = 0): string => {+ const circle = container.querySelectorAll<SVGCircleElement>("[data-automation-point]")[i]!;+ return circle.style.opacity;+ };+ const svgOf = (container: HTMLElement): SVGSVGElement =>+ container.querySelector<SVGSVGElement>(".hf-automation-svg")!;+ // React synthesises onPointerEnter/Leave from pointerover/pointerout, so those+ // are the events a hover has to be driven with.+ const enter = (el: Element) => fire(el, "pointerover");+ const leave = (el: Element) => fire(el, "pointerout");++ it("keeps its breakpoints out of sight until the lane is pointed at", () => {+ // A stack of lanes across a long clip is hundreds of discs; at rest the shape+ // of each envelope is what matters, and the handles are only wanted by+ // someone about to grab one.+ const { container } = render(<TimelineAutomationLane {...laneProps({ automation: ramp })} />);+ expect(opacityOf(container)).toBe("0");+ // The line itself is not hidden — the envelope still reads at rest.+ expect(container.querySelector<SVGPathElement>("path")?.style.opacity).not.toBe("0");+ });++ it("shows them on hover and hides them again on leave", () => {+ const { container } = render(<TimelineAutomationLane {...laneProps({ automation: ramp })} />);+ enter(svgOf(container));+ expect(opacityOf(container)).toBe("1");+ leave(svgOf(container));+ expect(opacityOf(container)).toBe("0");+ });++ it("keeps a selected range's points visible with the pointer away", () => {+ // The range is the subject of a pending Delete, and which points it caught is+ // the thing the author is checking — it cannot depend on where the mouse is.+ const { container } = render(+ <TimelineAutomationLane+ {...laneProps({ automation: ramp, rangeSelection: { t0: 0, t1: 4, v0: 0, v1: 1 } })}+ />,+ );+ expect(opacityOf(container)).toBe("1");+ });++ it("keeps them visible through a drag that leaves the lane", () => {+ // Dragging a point past the lane's edge fires pointerleave; losing the handle+ // mid-gesture would be the worst moment for it to disappear.+ const { container } = render(<TimelineAutomationLane {...laneProps({ automation: ramp })} />);+ const svg = svgOf(container);+ // happy-dom boxes are zero-sized, and the lane maps a pointer through its own+ // box to find the point under it.+ stubBox(svg, { left: 0, top: 0, width: 400 + PAD * 2, height: AUTOMATION_LANE_H });+ enter(svg);+ // The first point of `ramp` is t=0 at full value: the lane's left edge, top.+ fire(svg, "pointerdown", { clientX: PAD, clientY: 6, buttons: 1 });+ fire(svg, "pointermove", { clientX: PAD + 40, clientY: 30, buttons: 1 });+ leave(svg);+ expect(opacityOf(container)).toBe("1");+ });+});+/** `mount`, plus the re-render a real store update causes — the persisted* automation and the new selection coming back down as props. */const mountRerenderable = (automation: HfAutomation, over: Record<string, unknown> = {}) => {@@ -510,15 +680,16 @@ const mountRerenderable = (automation: HfAutomation, over: Record<string, unknowdescribe("TimelineAutomationLane modifiers", () => {it("bends a segment when it is Alt-dragged, and leaves the points where they were", () => {- // `curve` was honoured everywhere it is read — drawn, sampled in preview,- // baked into the render — with no gesture that could set it.+ // The shape is honoured everywhere it is read — drawn, sampled in preview,+ // baked into the render — and this is the gesture that sets it. What it+ // writes is the via point: where the pointer took the line.const { svg, props } = mount(ramp);fire(svg, "pointerdown", { ...at(2, 0.5), altKey: true });fire(svg, "pointermove", { ...at(2, 0.85), altKey: true });const previewed = props.onPreview.mock.calls.at(-1)?.[0] as HfAutomation | undefined;const points = previewed?.lanes[0]?.points ?? [];- expect(points[0]?.curve).toBeDefined();- expect(points[0]?.curve).not.toBe(0);+ expect(points[0]?.viaX).toBeCloseTo(0.5, 2);+ expect(points[0]?.viaY).toBeCloseTo(0.15, 2); // dragged to 0.85 on a falling ramp// The breakpoints themselves are untouched: only the shape between them moved.expect(points.map((p) => [p.t, p.v])).toEqual([[0, 1],@@ -526,6 +697,82 @@ describe("TimelineAutomationLane modifiers", () => {]);});+ it("bends toward the pointer's own end of the segment", () => {+ // The complaint this model replaced: one exponent always bulged the line near+ // the left-hand breakpoint, wherever it was grabbed. Now grabbing near either+ // end puts the bend there, which is visible in the via point it writes.+ const nearB = mount(ramp);+ fire(nearB.svg, "pointerdown", { ...at(3.4, 0.5), altKey: true });+ fire(nearB.svg, "pointermove", { ...at(3.4, 0.4), altKey: true });+ const right = (nearB.props.onPreview.mock.calls.at(-1)?.[0] as HfAutomation | undefined)+ ?.lanes[0]?.points[0];+ expect(right?.viaX).toBeCloseTo(0.85, 2);++ const nearA = mount(ramp);+ fire(nearA.svg, "pointerdown", { ...at(0.6, 0.5), altKey: true });+ fire(nearA.svg, "pointermove", { ...at(0.6, 0.6), altKey: true });+ const left = (nearA.props.onPreview.mock.calls.at(-1)?.[0] as HfAutomation | undefined)+ ?.lanes[0]?.points[0];+ expect(left?.viaX).toBeCloseTo(0.15, 2);+ });++ it("deletes a point on Shift+click", () => {+ // Right-click already removes one, but it is not a gesture a trackpad reaches+ // for. Shift+click is the second route.+ const { svg, props } = mount(ramp);+ fire(svg, "pointerdown", { ...at(0, 1), shiftKey: true });+ fire(svg, "pointerup", { ...at(0, 1), shiftKey: true });+ const written = props.onCommit.mock.calls.at(-1)?.[0] as HfAutomation;+ expect(written.lanes[0]?.points.map((p) => p.t)).toEqual([4]);+ });++ it("still locks the axis when Shift is held through a drag", () => {+ // Decided on release, not on the press: acting on the press would take the+ // Shift axis-lock away, since both gestures start identically.+ const { svg, props } = mount(ramp);+ fire(svg, "pointerdown", { ...at(0, 1), shiftKey: true });+ fire(svg, "pointermove", { ...at(1.5, 0.4), shiftKey: true });+ fire(svg, "pointerup", { ...at(1.5, 0.4), shiftKey: true });+ const written = props.onCommit.mock.calls.at(-1)?.[0] as HfAutomation;+ // Both points still there — a drag is a drag, however it ends.+ expect(written.lanes[0]?.points).toHaveLength(2);+ });++ it("leaves a point alone on a plain click", () => {+ const { svg, props } = mount(ramp);+ fire(svg, "pointerdown", at(0, 1));+ fire(svg, "pointerup", at(0, 1));+ const written = props.onCommit.mock.calls.at(-1)?.[0] as HfAutomation;+ expect(written.lanes[0]?.points).toHaveLength(2);+ });++ it("closes the value field when the lane is pressed, applying what was typed", () => {+ // The field commits on blur, but the lane calls preventDefault on its own+ // pointerdown to keep the timeline from scrubbing — and that suppresses the focus+ // change the blur would have come from, so the field sat open until Enter however+ // far away the next click landed.+ const { svg, container, props } = mount(ramp);+ fire(svg, "dblclick", at(0, 1));+ const input = container.querySelector<HTMLInputElement>(".hf-automation-value");+ expect(input).not.toBeNull();+ act(() => {+ if (!input) return;+ // React tracks the value it set, so assigning `.value` directly is ignored;+ // going through the native setter is what makes onChange fire.+ const setter = Object.getOwnPropertyDescriptor(+ window.HTMLInputElement.prototype,+ "value",+ )?.set;+ setter?.call(input, "0.4");+ input.dispatchEvent(new Event("input", { bubbles: true }));+ });++ fire(svg, "pointerdown", at(2, 0.5));+ expect(container.querySelector(".hf-automation-value")).toBeNull();+ const written = props.onCommit.mock.calls.at(-1)?.[0] as HfAutomation;+ expect(written.lanes[0]?.points[0]?.v).toBeCloseTo(0.4, 5);+ });+it("straightens a segment on Alt-double-click", () => {const curved: HfAutomation = {version: 1,@@ -558,6 +805,65 @@ describe("TimelineAutomationLane modifiers", () => {expect(moved?.v).toBe(1);});+ /** Four points, so the middle two have a neighbour on either side. */+ const four: HfAutomation = {+ version: 1,+ lanes: [+ {+ target: "volume",+ points: [+ { t: 0, v: 1 },+ { t: 1, v: 0.8 },+ { t: 2, v: 0.6 },+ { t: 3.5, v: 0.2 },+ ],+ },+ ],+ };+ const draggedTimes = (props: { onPreview: ReturnType<typeof vi.fn> }) => {+ const points = props.onPreview.mock.calls.at(-1)?.[0].lanes[0].points as+ | { t: number }[]+ | undefined;+ return (points ?? []).map((p) => Number(p.t.toFixed(2)));+ };++ it("stops a dragged point at its neighbour rather than letting it cross", () => {+ // Order is the lane's contract: an envelope is a sequence, and a point that+ // swaps places with its neighbour mid-drag pulls the shape inside out under+ // the pointer. Reaching it is allowed — two points at one instant is a step.+ const { svg, props } = mount(four);+ fire(svg, "pointerdown", { ...at(1, 0.8), buttons: 1 });+ // Aimed a whole second past the point at t=2.+ fire(svg, "pointermove", { ...at(3, 0.8), buttons: 1, altKey: true });+ expect(draggedTimes(props)).toEqual([0, 2, 2, 3.5]);+ });++ it("keeps the neighbour it was dragged into, through a normalising round trip", () => {+ // The bug this pins: the lane collapses points that share a `t`, keeping the+ // later one — so a point dragged fully onto its neighbour deleted that+ // neighbour. Stopping a millisecond short is what keeps both, and the check has+ // to run through normalisation because that is where the loss happened, not in+ // the drag.+ const { svg, props } = mount(four);+ fire(svg, "pointerdown", { ...at(1, 0.8), buttons: 1 });+ fire(svg, "pointermove", { ...at(3, 0.8), buttons: 1, altKey: true });+ fire(svg, "pointerup", { ...at(3, 0.8), buttons: 0, altKey: true });+ const committed = props.onCommit.mock.calls.at(-1)?.[0] as HfAutomation | undefined;+ const normalized = normalizeAutomation(committed!);+ const times = normalized.lanes[0]!.points.map((p) => p.t);+ expect(times).toHaveLength(4);+ // It arrived just under its neighbour rather than on it.+ expect(times[1]).toBeLessThan(times[2]!);+ expect(times[2]! - times[1]!).toBeCloseTo(0.001, 4);+ });++ it("stops it at the neighbour on the way back too", () => {+ const { svg, props } = mount(four);+ fire(svg, "pointerdown", { ...at(2, 0.6), buttons: 1 });+ fire(svg, "pointermove", { ...at(-1, 0.6), buttons: 1, altKey: true });+ expect(draggedTimes(props)).toEqual([0, 1, 1, 3.5]);+ });+it("snaps a dragged point to the beat grid", () => {// By eye, "on the beat" and "20 ms off the beat" look identical.const { svg, props } = mount(ramp, { snapTimes: [2] });@@ -632,7 +938,22 @@ describe("TimelineAutomationLane modifiers", () => {});});-describe("TimelineAutomationLane range selection", () => {+/** Two peaks with a dip between them, so a box can take the peaks alone. */+const stacked: HfAutomation = {+ version: 1,+ lanes: [+ {+ target: "volume",+ points: [+ { t: 1, v: 0.9 },+ { t: 2, v: 0.1 },+ { t: 3, v: 0.85 },+ ],+ },+ ],+};++describe("TimelineAutomationLane selection box", () => {it("drag on the background selects a range, snapped to the grid", () => {const onRangeSelect = vi.fn();const { svg } = mount(ramp, { snapTimes: [1], onRangeSelect });@@ -654,8 +975,60 @@ describe("TimelineAutomationLane range selection", () => {expect(onRangeClear).toHaveBeenCalled();});+ it("reports both axes of the box a diagonal drag draws", () => {+ // The gesture the whole feature is: a box round some points, not a span of+ // time. Ordered on the way out, so dragging up-and-left is the same box as+ // dragging down-and-right.+ const onRangeSelect = vi.fn();+ const { svg } = mount(ramp, { onRangeSelect });+ fire(svg, "pointerdown", at(3, 0.8));+ fire(svg, "pointermove", at(1, 0.2));+ const last = onRangeSelect.mock.calls.at(-1);+ expect(last?.[0]).toBeCloseTo(1, 1);+ expect(last?.[1]).toBeCloseTo(3, 1);+ expect(last?.[2]).toBeCloseTo(0.2, 1);+ expect(last?.[3]).toBeCloseTo(0.8, 1);+ });++ it("a purely vertical drag still crosses the threshold", () => {+ // The threshold is what tells a box from a click that should clear one, and it+ // has to watch both axes: measured on time alone, a straight-down drag over a+ // dense passage read as a click and cleared the selection instead of drawing.+ const onRangeSelect = vi.fn();+ const onRangeClear = vi.fn();+ const { svg } = mount(ramp, { onRangeSelect, onRangeClear });+ fire(svg, "pointerdown", at(2, 0.9));+ fire(svg, "pointermove", at(2, 0.1));+ fire(svg, "pointerup", at(2, 0.1));+ expect(onRangeSelect).toHaveBeenCalled();+ expect(onRangeClear).not.toHaveBeenCalled();+ });++ it("catches the points inside the box and not one at the same time outside it", () => {+ // What a box is FOR, and the one thing a time range could never do: pick the+ // top of an envelope out of a passage without taking the bottom with it.+ const { container } = mount(stacked, {+ rangeSelection: { t0: 0.5, t1: 3.5, v0: 0.6, v1: 1 },+ });+ const caught = Array.from(container.querySelectorAll("[data-automation-point-in-range]")).map(+ (el) => el.getAttribute("data-automation-point"),+ );+ expect(caught).toEqual(["0", "2"]); // the dip at t=2, v=0.1 is below the box+ });++ it("draws the rect bounded on the value axis, not down the whole lane", () => {+ const { container } = mount(ramp, {+ rangeSelection: { t0: 1, t1: 3, v0: 0.25, v1: 0.75 },+ });+ const rect = container.querySelector("[data-automation-selection]");+ const inner = AUTOMATION_LANE_H - 12;+ // v1 is the upper bound, so it is the smaller y.+ expect(Number(rect?.getAttribute("y"))).toBeCloseTo(6 + 0.25 * inner, 0);+ expect(Number(rect?.getAttribute("height"))).toBeCloseTo(0.5 * inner, 0);+ });+it("draws the selection rect between its endpoints", () => {- const { container } = mount(ramp, { rangeSelection: { t0: 1, t1: 3 } });+ const { container } = mount(ramp, { rangeSelection: { t0: 1, t1: 3, v0: 0, v1: 1 } });const rect = container.querySelector("[data-automation-selection]");expect(rect).not.toBeNull();expect(Number(rect?.getAttribute("x"))).toBeCloseTo(PAD + 100, 0); // xOf(1) at 400px/4s@@ -673,9 +1046,292 @@ describe("TimelineAutomationLane range selection", () => {});});+describe("TimelineAutomationLane group drag", () => {+ /** Four points; the middle two sit inside the range the tests select. */+ const four: HfAutomation = {+ version: 1,+ lanes: [+ {+ target: "volume",+ points: [+ { t: 0, v: 1 },+ { t: 1, v: 0.8 },+ { t: 2, v: 0.6 },+ { t: 3.5, v: 0.2 },+ ],+ },+ ],+ };+ const pointsOf = (props: { onPreview: ReturnType<typeof vi.fn> }) =>+ props.onPreview.mock.calls.at(-1)?.[0].lanes[0].points as { t: number; v: number }[];++ it("moves every selected point by the same distance", () => {+ // Dragging one of a selected set has to move the set: nudging a carve's+ // envelope a beat later, or lifting a passage, is one gesture on a selection,+ // not one drag per point.+ const { svg, props } = mount(four, { rangeSelection: { t0: 0.9, t1: 2.1, v0: 0, v1: 1 } });+ fire(svg, "pointerdown", { ...at(1, 0.8), buttons: 1 });+ // A whole second later and a fifth of the lane's height lower, with Alt so the+ // grid does not round the deltas out from under the assertion.+ fire(svg, "pointermove", { ...at(2, 0.6), buttons: 1, altKey: true });+ const points = pointsOf(props);+ expect(points[1]!.t).toBeCloseTo(2, 2);+ expect(points[2]!.t).toBeCloseTo(3, 2);+ expect(points[1]!.v).toBeCloseTo(0.6, 2);+ expect(points[2]!.v).toBeCloseTo(0.4, 2);+ });++ it("leaves points outside the selection where they are", () => {+ const { svg, props } = mount(four, { rangeSelection: { t0: 0.9, t1: 2.1, v0: 0, v1: 1 } });+ fire(svg, "pointerdown", { ...at(1, 0.8), buttons: 1 });+ fire(svg, "pointermove", { ...at(1.5, 0.8), buttons: 1, altKey: true });+ const points = pointsOf(props);+ expect(points[0]).toEqual({ t: 0, v: 1 });+ expect(points.at(-1)).toEqual({ t: 3.5, v: 0.2 });+ });++ it("moves only the one under the pointer when it is not in the selection", () => {+ // The selection is elsewhere, so this is an ordinary single-point drag.+ const { svg, props } = mount(four, { rangeSelection: { t0: 3, t1: 3.6, v0: 0, v1: 1 } });+ fire(svg, "pointerdown", { ...at(1, 0.8), buttons: 1 });+ fire(svg, "pointermove", { ...at(1.5, 0.5), buttons: 1, altKey: true });+ const points = pointsOf(props);+ expect(points[1]!.t).toBeCloseTo(1.5, 2);+ expect(points[2]).toEqual({ t: 2, v: 0.6 });+ expect(points[3]).toEqual({ t: 3.5, v: 0.2 });+ });++ it("stops the whole group at the lane's edge rather than piling points up", () => {+ // Clamping each point on its own would squash the shape flat against the+ // boundary; the group has to stop when its first member reaches it.+ const { svg, props } = mount(four, { rangeSelection: { t0: 0.9, t1: 2.1, v0: 0, v1: 1 } });+ fire(svg, "pointerdown", { ...at(1, 0.8), buttons: 1 });+ fire(svg, "pointermove", { ...at(-4, 0.8), buttons: 1, altKey: true });+ const points = pointsOf(props);+ // The group stopped with its earliest member on zero, a second apart as it+ // began — and the unselected point that was already at zero is still there,+ // which is why the moved pair are the middle two after the sort.+ expect(points.map((p) => Number(p.t.toFixed(2)))).toEqual([0, 0, 1, 3.5]);+ });++ it("clamps the group's values to the lane's own floor and ceiling", () => {+ const { svg, props } = mount(four, { rangeSelection: { t0: 0.9, t1: 2.1, v0: 0, v1: 1 } });+ fire(svg, "pointerdown", { ...at(1, 0.8), buttons: 1 });+ fire(svg, "pointermove", { ...at(1, 4), buttons: 1, altKey: true });+ const points = pointsOf(props);+ expect(Math.max(...points.map((p) => p.v))).toBeLessThanOrEqual(1);+ // The gap between the two moved points survives the clamp.+ expect(points[1]!.v - points[2]!.v).toBeCloseTo(0.2, 2);+ });++ it("carries the selection along, so the same points stay selected", () => {+ // Otherwise a second nudge is no longer a group drag, and the highlight sits+ // where the points used to be.+ const onRangeSelect = vi.fn();+ const { svg } = mount(four, {+ rangeSelection: { t0: 0.9, t1: 2.1, v0: 0, v1: 1 },+ onRangeSelect,+ });+ fire(svg, "pointerdown", { ...at(1, 0.8), buttons: 1 });+ fire(svg, "pointermove", { ...at(2, 0.8), buttons: 1, altKey: true });+ const last = onRangeSelect.mock.calls.at(-1);+ expect(last?.[0]).toBeCloseTo(1.9, 1);+ expect(last?.[1]).toBeCloseTo(3.1, 1);+ });++ it("stops the group at a point it did not select", () => {+ // A box can catch a non-contiguous set — two peaks and not the dip between+ // them — so the constraint is per member, not just the ends of the group.+ // Here the two peaks each have an unselected neighbour a second ahead.+ const peaks: HfAutomation = {+ version: 1,+ lanes: [+ {+ target: "volume",+ points: [+ { t: 0, v: 1 },+ { t: 1, v: 0.2 },+ { t: 2, v: 0.9 },+ { t: 3, v: 0.5 },+ ],+ },+ ],+ };+ const { svg, props } = mount(peaks, {+ rangeSelection: { t0: 0, t1: 2, v0: 0.8, v1: 1 },+ });+ fire(svg, "pointerdown", { ...at(0, 1), buttons: 1 });+ // Aimed two seconds later; the dip at t=1 is a second away and stays put.+ fire(svg, "pointermove", { ...at(2, 1), buttons: 1, altKey: true });+ fire(svg, "pointerup", { ...at(2, 1), buttons: 0, altKey: true });+ const points = pointsOf(props);+ expect(points.map((p) => Number(p.t.toFixed(2)))).toEqual([1, 1, 3, 3]);+ // And short of them, not onto them: a group drag must not consume what it runs+ // into either, which normalisation is where it would have shown.+ const committed = props.onCommit.mock.calls.at(-1)?.[0] as HfAutomation | undefined;+ const times = normalizeAutomation(committed!).lanes[0]!.points.map((p) => p.t);+ expect(times).toHaveLength(4);+ expect(times[0]).toBeLessThan(times[1]!);+ expect(times[2]).toBeLessThan(times[3]!);+ });++ it("carries the box's value bounds along too", () => {+ // Both axes, or a vertical nudge slides its own points out of the box that+ // caught them and the second nudge moves fewer of them.+ const onRangeSelect = vi.fn();+ const { svg } = mount(four, {+ rangeSelection: { t0: 0.9, t1: 2.1, v0: 0.5, v1: 0.9 },+ onRangeSelect,+ });+ fire(svg, "pointerdown", { ...at(1, 0.8), buttons: 1 });+ fire(svg, "pointermove", { ...at(1, 0.6), buttons: 1, altKey: true });+ const last = onRangeSelect.mock.calls.at(-1);+ expect(last?.[2]).toBeCloseTo(0.3, 1);+ expect(last?.[3]).toBeCloseTo(0.7, 1);+ });+});++describe("TimelineAutomationLane shift axis lock", () => {+ const two: HfAutomation = {+ version: 1,+ lanes: [+ {+ target: "volume",+ points: [+ { t: 1, v: 0.5 },+ { t: 3, v: 0.5 },+ ],+ },+ ],+ };+ const lastPoints = (props: { onPreview: ReturnType<typeof vi.fn> }) =>+ props.onPreview.mock.calls.at(-1)?.[0].lanes[0].points as { t: number; v: number }[];++ it("holds the value when the pointer travels mostly sideways", () => {+ const { svg, props } = mount(two);+ fire(svg, "pointerdown", { ...at(1, 0.5), buttons: 1 });+ fire(svg, "pointermove", { ...at(2, 0.62), buttons: 1, shiftKey: true });+ const moved = lastPoints(props)[0]!;+ expect(moved.t).toBeCloseTo(2, 1);+ expect(moved.v).toBeCloseTo(0.5, 3);+ });++ it("holds the time when the pointer travels mostly up or down", () => {+ const { svg, props } = mount(two);+ fire(svg, "pointerdown", { ...at(1, 0.5), buttons: 1 });+ fire(svg, "pointermove", { ...at(1.05, 0.95), buttons: 1, shiftKey: true });+ const moved = lastPoints(props).find((p) => p.v !== 0.5)!;+ expect(moved.t).toBeCloseTo(1, 3);+ expect(moved.v).toBeGreaterThan(0.5);+ });++ it("keeps the axis it locked, rather than swapping as the pointer wobbles", () => {+ // The lock has to be decided once and held: recomputed per event, whichever+ // axis the last move happened to favour wins, so a hand that drifts up while+ // dragging sideways sees the point move in both — which is no lock at all.+ const { svg, props } = mount(two);+ fire(svg, "pointerdown", { ...at(1, 0.5), buttons: 1 });+ fire(svg, "pointermove", { ...at(1.6, 0.52), buttons: 1, shiftKey: true });+ // Now drift further vertically than the horizontal travel so far.+ fire(svg, "pointermove", { ...at(1.7, 0.95), buttons: 1, shiftKey: true });+ const moved = lastPoints(props)[0]!;+ expect(moved.v).toBeCloseTo(0.5, 3);+ expect(moved.t).toBeCloseTo(1.7, 1);+ });++ it("holds a value lock through sideways drift too", () => {+ const { svg, props } = mount(two);+ fire(svg, "pointerdown", { ...at(1, 0.5), buttons: 1 });+ fire(svg, "pointermove", { ...at(1.02, 0.8), buttons: 1, shiftKey: true });+ fire(svg, "pointermove", { ...at(2.5, 0.85), buttons: 1, shiftKey: true });+ const moved = lastPoints(props).find((p) => p.v !== 0.5)!;+ expect(moved.t).toBeCloseTo(1, 3);+ });++ it("locks an axis for a group drag too", () => {+ const four: HfAutomation = {+ version: 1,+ lanes: [+ {+ target: "volume",+ points: [+ { t: 0, v: 1 },+ { t: 1, v: 0.8 },+ { t: 2, v: 0.6 },+ { t: 3.5, v: 0.2 },+ ],+ },+ ],+ };+ const { svg, props } = mount(four, { rangeSelection: { t0: 0.9, t1: 2.1, v0: 0, v1: 1 } });+ fire(svg, "pointerdown", { ...at(1, 0.8), buttons: 1 });+ fire(svg, "pointermove", { ...at(2, 0.9), buttons: 1, shiftKey: true });+ const points = lastPoints(props);+ // Sideways wins, so both selected points keep the values they started with.+ expect(points[1]!.v).toBeCloseTo(0.8, 3);+ expect(points[2]!.v).toBeCloseTo(0.6, 3);+ expect(points[1]!.t).toBeCloseTo(2, 1);+ });+});++describe("TimelineAutomationLane gesture commits", () => {+ /**+ * One gesture, one persisting commit — which is one undo step.+ *+ * Every pointermove previews; only the release writes. Persisting each move put+ * fragments of one drag in the undo stack, and because those writes race, the+ * chain history needs to coalesce them was broken as often as not: undo took+ * back a few milliseconds of the gesture and read as doing nothing.+ */+ const four: HfAutomation = {+ version: 1,+ lanes: [+ {+ target: "volume",+ points: [+ { t: 0, v: 1 },+ { t: 1, v: 0.8 },+ { t: 2, v: 0.6 },+ { t: 3.5, v: 0.2 },+ ],+ },+ ],+ };++ it("commits once for a single-point drag, however many moves it took", () => {+ const { svg, props } = mount(four);+ fire(svg, "pointerdown", { ...at(1, 0.8), buttons: 1 });+ for (const t of [1.2, 1.4, 1.6, 1.8]) fire(svg, "pointermove", { ...at(t, 0.7), buttons: 1 });+ fire(svg, "pointerup", { ...at(1.8, 0.7), buttons: 0 });+ expect(props.onPreview.mock.calls.length).toBeGreaterThan(1);+ expect(props.onCommit).toHaveBeenCalledTimes(1);+ });++ it("commits once for a group drag", () => {+ const { svg, props } = mount(four, { rangeSelection: { t0: 0.9, t1: 2.1, v0: 0, v1: 1 } });+ fire(svg, "pointerdown", { ...at(1, 0.8), buttons: 1 });+ for (const t of [1.2, 1.5, 1.8]) fire(svg, "pointermove", { ...at(t, 0.8), buttons: 1 });+ fire(svg, "pointerup", { ...at(1.8, 0.8), buttons: 0 });+ expect(props.onCommit).toHaveBeenCalledTimes(1);+ // And what it commits is the moved set, not the shape it started from.+ const committed = props.onCommit.mock.calls[0]![0].lanes[0].points as { t: number }[];+ expect(committed[1]!.t).toBeGreaterThan(1);+ });++ it("commits once for a bend", () => {+ const { svg, props } = mount(four);+ // Alt-drag the line between two points curves that segment.+ fire(svg, "pointerdown", { ...at(1.5, 0.7), buttons: 1, altKey: true });+ for (const v of [0.6, 0.5, 0.4])+ fire(svg, "pointermove", { ...at(1.5, v), buttons: 1, altKey: true });+ fire(svg, "pointerup", { ...at(1.5, 0.4), buttons: 0, altKey: true });+ expect(props.onCommit).toHaveBeenCalledTimes(1);+ });+});+describe("TimelineAutomationLane selection menu", () => {it("right-click inside the selection opens the shape menu", () => {- const { container, svg } = mount(ramp, { rangeSelection: { t0: 1, t1: 3 } });+ const { container, svg } = mount(ramp, { rangeSelection: { t0: 1, t1: 3, v0: 0, v1: 1 } });fire(svg, "contextmenu", at(2, 0.5));expect(document.querySelector(".hf-automation-menu")).not.toBeNull();// The menu portals to document.body, outside `container` — dismiss it via@@ -690,7 +1346,7 @@ describe("TimelineAutomationLane selection menu", () => {});it("inserting a swell replaces the range and commits once", () => {- const { svg, props } = mount(ramp, { rangeSelection: { t0: 1, t1: 3 } });+ const { svg, props } = mount(ramp, { rangeSelection: { t0: 1, t1: 3, v0: 0, v1: 1 } });fire(svg, "contextmenu", at(2, 0.5));const swell = Array.from(document.querySelectorAll<HTMLButtonElement>(".hf-automation-menu button"),@@ -704,7 +1360,7 @@ describe("TimelineAutomationLane selection menu", () => {});it("right-click outside the selection does not open it", () => {- const { svg } = mount(ramp, { rangeSelection: { t0: 1, t1: 3 } });+ const { svg } = mount(ramp, { rangeSelection: { t0: 1, t1: 3, v0: 0, v1: 1 } });fire(svg, "contextmenu", at(3.8, 0.5));expect(document.querySelector(".hf-automation-menu")).toBeNull();});@@ -744,7 +1400,7 @@ describe("TimelineAutomationLane stretch", () => {it("dragging the right edge retimes the interior and persists on release", () => {const onRangeSelect = vi.fn();const { svg, props } = mount(stretchable, {- rangeSelection: { t0: 0.5, t1: 2.5 },+ rangeSelection: { t0: 0.5, t1: 2.5, v0: 0, v1: 1 },onRangeSelect,});dragRightEdge(svg, 2.5, 3.3); // off any point, dragged out to 3.3@@ -756,7 +1412,7 @@ describe("TimelineAutomationLane stretch", () => {expect(points.some((p) => Math.abs(p.t - 1.2) < 0.01 && p.v === 0.5)).toBe(true);expect(points.some((p) => Math.abs(p.t - 2.6) < 0.01 && p.v === 0.8)).toBe(true);- expect(onRangeSelect).toHaveBeenLastCalledWith(0.5, expect.closeTo(3.3, 1));+ expect(onRangeSelect).toHaveBeenLastCalledWith(0.5, expect.closeTo(3.3, 1), 0, 1);});it("moves the selection with the pointer instead of snapping it on release", () => {@@ -766,14 +1422,14 @@ describe("TimelineAutomationLane stretch", () => {// gesture. The marquee drag fires live for exactly this reason.const onRangeSelect = vi.fn();const { svg } = mount(stretchable, {- rangeSelection: { t0: 0.5, t1: 2.5 },+ rangeSelection: { t0: 0.5, t1: 2.5, v0: 0, v1: 1 },onRangeSelect,});fire(svg, "pointerdown", at(2.5, 0.5));fire(svg, "pointermove", at(3, 0.5));- expect(onRangeSelect).toHaveBeenLastCalledWith(0.5, expect.closeTo(3, 1));+ expect(onRangeSelect).toHaveBeenLastCalledWith(0.5, expect.closeTo(3, 1), 0, 1);fire(svg, "pointermove", at(3.3, 0.5));- expect(onRangeSelect).toHaveBeenLastCalledWith(0.5, expect.closeTo(3.3, 1));+ expect(onRangeSelect).toHaveBeenLastCalledWith(0.5, expect.closeTo(3.3, 1), 0, 1);});it("a bare click on an edge clears the selection instead of committing a no-op", () => {@@ -783,7 +1439,7 @@ describe("TimelineAutomationLane stretch", () => {const onRangeSelect = vi.fn();const onRangeClear = vi.fn();const { svg, props } = mount(stretchable, {- rangeSelection: { t0: 0.5, t1: 2.5 },+ rangeSelection: { t0: 0.5, t1: 2.5, v0: 0, v1: 1 },onRangeSelect,onRangeClear,});@@ -798,7 +1454,7 @@ describe("TimelineAutomationLane stretch", () => {it("a press that jitters under the threshold still clears rather than retiming", () => {const onRangeClear = vi.fn();const { svg, props } = mount(stretchable, {- rangeSelection: { t0: 0.5, t1: 2.5 },+ rangeSelection: { t0: 0.5, t1: 2.5, v0: 0, v1: 1 },onRangeClear,});fire(svg, "pointerdown", at(2.5, 0.5));@@ -816,7 +1472,7 @@ describe("TimelineAutomationLane stretch", () => {// with no way back other than undo.const onRangeSelect = vi.fn();const { svg, props } = mount(stretchable, {- rangeSelection: { t0: 0.5, t1: 2.5 },+ rangeSelection: { t0: 0.5, t1: 2.5, v0: 0, v1: 1 },onRangeSelect,});fire(svg, "pointerdown", at(2.5, 0.5));@@ -829,14 +1485,14 @@ describe("TimelineAutomationLane stretch", () => {const reverted = (props.onPreview.mock.calls.at(-1)?.[0] as HfAutomation | undefined)?.lanes[0]?.points;expect(reverted).toEqual(stretchable.lanes[0]?.points);- expect(onRangeSelect).toHaveBeenLastCalledWith(0.5, 2.5);+ expect(onRangeSelect).toHaveBeenLastCalledWith(0.5, 2.5, 0, 1);});it("gives up a stretch whose pointer capture vanished without a cancel", () => {// A capture taken on a child that unmounts mid-drag is lost silently: no// pointercancel, no pointerup. Every later hover kept retiming and writing.const { svg, props } = mount(stretchable, {- rangeSelection: { t0: 0.5, t1: 2.5 },+ rangeSelection: { t0: 0.5, t1: 2.5, v0: 0, v1: 1 },});fire(svg, "pointerdown", at(2.5, 0.5));fire(svg, "pointermove", { ...at(3.3, 0.5), buttons: 1 });@@ -853,7 +1509,7 @@ describe("TimelineAutomationLane stretch", () => {const onPreview = vi.fn();const onCommit = vi.fn();const { svg } = mount(stretchable, {- rangeSelection: { t0: 0.5, t1: 2.5 },+ rangeSelection: { t0: 0.5, t1: 2.5, v0: 0, v1: 1 },onPreview,onCommit,});@@ -884,20 +1540,28 @@ describe("TimelineAutomationLane stretch", () => {],};- it("the selection's edge wins over a point sitting exactly on it", () => {- // The regression this pins is the feature not being repeatable: stretching- // pins a breakpoint on the edge it just created, so a point-first rule made- // the SECOND stretch of that edge a point-drag every time — at the one- // height (on the envelope) where the user naturally grabs it.+ it("a point sitting exactly on the edge is selected content, not the edge", () => {+ // #3207's rule was the opposite — the edge won, so a repeated stretch of the+ // same edge (which pins a breakpoint there) always resolved to a point-drag.+ // A box selection changes the question: with value bounds as well as time,+ // a point on the edge is visibly INSIDE the box, and dragging selected+ // content has to move it or the box means nothing. So the press below drags+ // the group the box already caught — both points inside it — rather than+ // stretching the edge; the box travels with them.const onRangeSelect = vi.fn();- const { svg } = mount(pointOnEdge, {- rangeSelection: { t0: 1, t1: 2 },+ const { svg, props } = mount(pointOnEdge, {+ rangeSelection: { t0: 1, t1: 2, v0: 0, v1: 1 },onRangeSelect,});fire(svg, "pointerdown", at(2, 0.8)); // the point at t=2, which is also the right edgefire(svg, "pointermove", at(3, 0.8));fire(svg, "pointerup", at(3, 0.8));- expect(onRangeSelect).toHaveBeenLastCalledWith(1, expect.closeTo(3, 1));+ expect(onRangeSelect).toHaveBeenLastCalledWith(2, expect.closeTo(3, 1), 0, 1);+ const written = props.onCommit.mock.calls.at(-1)?.[0] as HfAutomation;+ const times = (written.lanes[0]?.points ?? []).map((p) => p.t);+ // Both points the box caught (t=1.5 and t=2) moved by the same +1 delta.+ expect(times.some((t) => Math.abs(t - 2.5) < 0.01)).toBe(true);+ expect(times.some((t) => Math.abs(t - 3) < 0.01)).toBe(true);});it("leaves that point reachable once the selection is gone", () => {@@ -918,19 +1582,19 @@ describe("TimelineAutomationLane stretch", () => {// right edge, the second grabbing the breakpoint the first one left there.const onRangeSelect = vi.fn();const { svg, props, rerender } = mountRerenderable(stretchable, {- rangeSelection: { t0: 0.5, t1: 2 },+ rangeSelection: { t0: 0.5, t1: 2, v0: 0, v1: 1 },onRangeSelect,});dragRightEdge(svg, 2, 2.6);- expect(onRangeSelect).toHaveBeenLastCalledWith(0.5, expect.closeTo(2.6, 1));+ expect(onRangeSelect).toHaveBeenLastCalledWith(0.5, expect.closeTo(2.6, 1), 0, 1);const afterFirst = props.onCommit.mock.calls.at(-1)?.[0] as HfAutomation;// A breakpoint landed on the new edge, which is what used to disarm it.expect((afterFirst.lanes[0]?.points ?? []).some((p) => Math.abs(p.t - 2.6) < 0.05)).toBe(true);// The store comes back with the persisted envelope and the new selection.- rerender({ automation: afterFirst, rangeSelection: { t0: 0.5, t1: 2.6 } });+ rerender({ automation: afterFirst, rangeSelection: { t0: 0.5, t1: 2.6, v0: 0, v1: 1 } });dragRightEdge(svg, 2.6, 3.4);- expect(onRangeSelect).toHaveBeenLastCalledWith(0.5, expect.closeTo(3.4, 1));+ expect(onRangeSelect).toHaveBeenLastCalledWith(0.5, expect.closeTo(3.4, 1), 0, 1);expect(props.onCommit).toHaveBeenCalledTimes(2);});@@ -942,20 +1606,20 @@ describe("TimelineAutomationLane stretch", () => {// the rule never comes up.const onRangeSelect = vi.fn();const { svg } = mount(stretchable, {- rangeSelection: { t0: 2, t1: 2.08 }, // 8px wide at 100 px/s: both halos overlap+ rangeSelection: { t0: 2, t1: 2.08, v0: 0, v1: 1 }, // 8px wide at 100 px/s: both halos overlaponRangeSelect,});fire(svg, "pointerdown", at(2.07, 0.5)); // nearer t1, inside t0's halo toofire(svg, "pointermove", at(3, 0.5));fire(svg, "pointerup", at(3, 0.5));// t0 stayed put and t1 moved out: the press resolved to the right edge.- expect(onRangeSelect).toHaveBeenLastCalledWith(2, expect.closeTo(3, 1));+ expect(onRangeSelect).toHaveBeenLastCalledWith(2, expect.closeTo(3, 1), 0, 1);});it("clamps the dragged edge so it cannot cross its partner", () => {const onRangeSelect = vi.fn();const { svg } = mount(stretchable, {- rangeSelection: { t0: 0.5, t1: 2.5 },+ rangeSelection: { t0: 0.5, t1: 2.5, v0: 0, v1: 1 },onRangeSelect,});dragRightEdge(svg, 2.5, 0.3); // dragged past the left edge (t0=0.5)@@ -966,7 +1630,7 @@ describe("TimelineAutomationLane stretch", () => {it("clamps the dragged edge to the lane's own duration", () => {const onRangeSelect = vi.fn();const { svg } = mount(stretchable, {- rangeSelection: { t0: 0.5, t1: 2.5 },+ rangeSelection: { t0: 0.5, t1: 2.5, v0: 0, v1: 1 },onRangeSelect,});dragRightEdge(svg, 2.5, 10); // far past the clip's own duration (4s)@@ -983,7 +1647,7 @@ describe("TimelineAutomationLane stretch", () => {// this asserts the FINAL preview is identical regardless of how many.const onPreviewSingle = vi.fn();const single = mount(stretchable, {- rangeSelection: { t0: 0.5, t1: 2.5 },+ rangeSelection: { t0: 0.5, t1: 2.5, v0: 0, v1: 1 },onPreview: onPreviewSingle,});fire(single.svg, "pointerdown", at(2.5, 0.5));@@ -994,7 +1658,7 @@ describe("TimelineAutomationLane stretch", () => {const onPreviewMulti = vi.fn();const multi = mount(stretchable, {- rangeSelection: { t0: 0.5, t1: 2.5 },+ rangeSelection: { t0: 0.5, t1: 2.5, v0: 0, v1: 1 },onPreview: onPreviewMulti,});fire(multi.svg, "pointerdown", at(2.5, 0.5));@@ -1018,7 +1682,7 @@ describe("TimelineAutomationLane stretch", () => {it("retimes identically whether the left edge arrives in one move or several", () => {const onPreviewSingle = vi.fn();const single = mount(stretchable, {- rangeSelection: { t0: 1, t1: 3 },+ rangeSelection: { t0: 1, t1: 3, v0: 0, v1: 1 },onPreview: onPreviewSingle,});fire(single.svg, "pointerdown", at(1, 0.5));@@ -1029,7 +1693,7 @@ describe("TimelineAutomationLane stretch", () => {const onPreviewMulti = vi.fn();const multi = mount(stretchable, {- rangeSelection: { t0: 1, t1: 3 },+ rangeSelection: { t0: 1, t1: 3, v0: 0, v1: 1 },onPreview: onPreviewMulti,});fire(multi.svg, "pointerdown", at(1, 0.5));@@ -1043,13 +1707,13 @@ describe("TimelineAutomationLane stretch", () => {});it("shows a resize cursor when hovering an edge with nothing else live", () => {- const { svg } = mount(ramp, { rangeSelection: { t0: 1, t1: 3 } });+ const { svg } = mount(ramp, { rangeSelection: { t0: 1, t1: 3, v0: 0, v1: 1 } });fire(svg, "pointermove", at(3, 0.5)); // near the right edge, nothing pressedexpect(svg.style.cursor).toBe("col-resize");});it("keeps the normal cursor away from the selection's edges", () => {- const { svg } = mount(ramp, { rangeSelection: { t0: 1, t1: 3 } });+ const { svg } = mount(ramp, { rangeSelection: { t0: 1, t1: 3, v0: 0, v1: 1 } });fire(svg, "pointermove", at(2, 0.5)); // middle of the selection, not an edgeexpect(svg.style.cursor).not.toBe("col-resize");});diff --git a/packages/studio/src/player/components/TimelineAutomationLane.tsx b/packages/studio/src/player/components/TimelineAutomationLane.tsxindex cdd702991c..8aa2de83ed 100644--- a/packages/studio/src/player/components/TimelineAutomationLane.tsx+++ b/packages/studio/src/player/components/TimelineAutomationLane.tsx@@ -1,13 +1,17 @@/*** Breakpoint automation over an audio clip, edited the way a DAW edits it:- * double-click the line to add a point, drag one to shape it, right-click a- * point to remove it, Alt-drag the line between two points to bend it, and- * double-click a point to type an exact value.+ * double-click the line to add a point, drag one to shape it, right-click or+ * Shift+click a point to remove it, Alt-drag the line between two points to bend+ * it, and double-click a point to type an exact value.** Modifiers follow Ableton's, because that is the muscle memory an automation* lane inherits: Shift locks a drag to one axis and fines the value down, Alt* over a segment curves it, and Alt during a point drag ignores the grid.*+ * Drag the background to draw a selection box around a set of breakpoints, then+ * Delete to remove them, drag any one of them to move the whole set, or+ * right-click inside the box for shapes over its span.+ ** The lane knows nothing about any particular effect. Which parameters it can* offer, their ranges, units and whether they read logarithmically all come* from the FX registry, so an effect gained upstream needs no change here — the@@ -30,29 +34,66 @@ import {type HfAutomationLane,type HfAutomationPoint,} from "@hyperframes/core/audio-automation";-import {- envelopePath,- fromUnit,- GRAB_PX,- laneFor,- PAD_X,- toUnit,- withLane,-} from "./automationLaneGeometry";+import { envelopePath, fromUnit, laneFor, PAD_X, toUnit, withLane } from "./automationLaneGeometry";import { useAutomationLaneGestures } from "./useAutomationLaneGestures";import { AutomationValueInput } from "./AutomationValueInput";import { AutomationSelectionMenu } from "./AutomationSelectionMenu";import { AUTOMATION_LANE_H } from "./automationLaneHeight";import { generateShape, type AutomationShapeId } from "./automationShapes";import { simplifyPoints } from "./automationSimplify";-import { pointsIn, replaceRange } from "./automationLaneSelection";+import { pointInSelection, pointsIn, replaceRange } from "./automationLaneSelection";import { getTimelineLaneTop } from "./timelineLayout";+import { defaultTimelineTheme } from "./timelineTheme";import type { TimelineElement } from "../store/playerStore";import type { UseAutomationLanesResult } from "./useAutomationLanes";-/** Pointer shape: a stretch handle wins over everything else it might also- * sit above, a read-only lane can only be selected, a live one edited. */+/**+ * Drawn radius of a breakpoint.+ *+ * Independent of the grab radius, which is how close a pointer has to be to catch+ * one: the two were the same number scaled, and tying them meant a dot could not be+ * made easier to see without also changing what it caught. A touch over half the+ * grab radius reads clearly at lane height without swallowing a dense run.+ */+const POINT_R = 4.9;++/** Separator between stacked lanes — the same token a track row divides with. Read+ * off the default theme rather than threaded as a prop: nothing overrides the+ * timeline theme for lanes today, and a prop for one colour is plumbing to nowhere. */+const LANE_BORDER = defaultTimelineTheme.rowBorder;++/** Selection box on one lane. Value bounds included: a point at the right time+ * but the wrong value is not in it. */+type SelectionBox = { t0: number; t1: number; v0: number; v1: number };++/** Is this breakpoint inside the selection box? The rule itself is shared with+ * Delete and with the group drag, so what is drawn as caught is exactly what+ * those act on; this only adds tolerance for there being no selection at all. */+function pointInBox(point: HfAutomationPoint, box: SelectionBox | null | undefined): boolean {+ return !!box && pointInSelection(point, box);+}++/** A breakpoint's drawn radius and stroke, pulled out of the render loop so the+ * map callback stays a single JSX return — the ternaries below are what pushed+ * it over the complexity budget when they lived inline. */+function pointCircleStyle(+ inRange: boolean,+ dragging: boolean,+): { radius: number; stroke: string; strokeWidth: number } {+ return {+ radius: POINT_R * (dragging ? 1.3 : inRange ? 1.15 : 1),+ // A white ring rather than a different fill: the fill is the parameter's+ // own colour, and a lane with two envelopes on it is read by colour first.+ stroke: inRange ? "#fff" : "rgba(0,0,0,0.5)",+ strokeWidth: inRange ? 1.5 : 1,+ };+}++/** Pointer shape: a read-only lane can only be selected, a live one edited. */function laneCursor(readOnly: boolean | undefined, dragging: boolean, stretching: boolean): string {+ // A stretch handle wins over everything it might also sit above: the handle is+ // a few px wide and always overlaps whatever is under the selection edge, so+ // any other cursor there would advertise a gesture the press will not start.if (stretching) return "col-resize";if (readOnly) return "pointer";return dragging ? "grabbing" : "crosshair";@@ -85,9 +126,9 @@ export interface TimelineAutomationLaneProps {readOnly?: boolean;/** Called when a read-only lane is pressed: selects the clip so it goes live. */onSelect?(): void;- /** Active selection on THIS lane, or null. */- rangeSelection?: { t0: number; t1: number } | null | undefined;- onRangeSelect?: ((t0: number, t1: number) => void) | undefined;+ /** Active selection box on THIS lane, or null. */+ rangeSelection?: SelectionBox | null | undefined;+ onRangeSelect?: ((t0: number, t1: number, v0: number, v1: number) => void) | undefined;onRangeClear?: (() => void) | undefined;}@@ -223,6 +264,16 @@ export function TimelineAutomationLane({/** Client-coordinate position of an open selection menu, or null when closed. */const [menuAt, setMenuAt] = useState<{ x: number; y: number } | null>(null);+ /**+ * Whether the pointer is over this lane, which is what decides if the+ * breakpoints are drawn.+ *+ * A stack of envelopes across a long clip is hundreds of discs, and at rest the+ * shape of each is the thing worth reading — the handles matter only to someone+ * about to grab one. The line stays visible either way; this hides just the+ * points.+ */+ const [hovered, setHovered] = useState(false);const insertShape = useCallback((shape: AutomationShapeId): void => {@@ -234,7 +285,10 @@ export function TimelineAutomationLane({t0: rangeSelection.t0,t1: rangeSelection.t1,});- commitPoints(replaceRange({ lane, range, ...rangeSelection, inner }), true);+ commitPoints(+ replaceRange({ lane, range, t0: rangeSelection.t0, t1: rangeSelection.t1, inner }),+ true,+ );},[rangeSelection, lane, range, commitPoints],);@@ -242,7 +296,10 @@ export function TimelineAutomationLane({const simplifySelection = useCallback((): void => {if (!rangeSelection) return;const inner = simplifyPoints(pointsIn(lane, rangeSelection.t0, rangeSelection.t1), range);- commitPoints(replaceRange({ lane, range, ...rangeSelection, inner }), true);+ commitPoints(+ replaceRange({ lane, range, t0: rangeSelection.t0, t1: rangeSelection.t1, inner }),+ true,+ );}, [rangeSelection, lane, range, commitPoints]);// A point's own right-click already stops propagation and still deletes;@@ -251,8 +308,10 @@ export function TimelineAutomationLane({const onSvgContextMenu = useCallback((e: ReactMouseEvent<SVGSVGElement>): void => {if (readOnly || !rangeSelection) return;- const { t } = pointAt(e.clientX, e.clientY);- if (t < rangeSelection.t0 || t > rangeSelection.t1) return;+ // Inside the drawn box, not merely inside its span: the menu's own actions+ // read the span, but a right-click well above or below the box is a press+ // on empty lane as far as the author can see.+ if (!pointInSelection(pointAt(e.clientX, e.clientY), rangeSelection)) return;e.preventDefault();setMenuAt({ x: e.clientX, y: e.clientY });},@@ -270,16 +329,19 @@ export function TimelineAutomationLane({style={{ top: topPx, left: 0, right: 0, height: h }}data-automation-lane={target}>- {/* Name at the lane's top-left, like a DAW's lane header. Shown in full —- a clip starting at zero leaves no gutter to clamp it into — and- click-through, so it can sit over the envelope without blocking it. */}+ {/* Separator above each lane, in the same colour a track row divides with, so+ a stack of envelopes reads as rows rather than as one tall field. Drawn as+ an overlay rather than a CSS border: the lane's height is fixed and its svg+ is positioned against the same box, so a border would shift the drawing a+ pixel off the geometry every hit test is computed from. */}<div- className="hf-automation-name pointer-events-none absolute whitespace-nowrap font-mono text-[9px] text-panel-text-4"- style={{ left: 4, top: 2, zIndex: 2 }}- >- {range.label}- </div>-+ data-automation-lane-border=""+ className="hf-automation-lane-border pointer-events-none absolute"+ style={{ top: 0, left: 0, right: 0, height: 1, background: LANE_BORDER, zIndex: 1 }}+ />+ {/* No name drawn here: the label column carries it, on the same tree+ connector as the keyframe rows. Painted in the lane it sat on top of the+ envelope it described and scrolled horizontally away from its own row. */}<svgref={svgRef}className="hf-automation-svg absolute"@@ -298,6 +360,8 @@ export function TimelineAutomationLane({}}width={widthPx + PAD_X * 2}height={h}+ onPointerEnter={() => setHovered(true)}+ onPointerLeave={() => setHovered(false)}onPointerDown={gestures.onPointerDown}onPointerMove={gestures.onPointerMove}onPointerUp={gestures.endDrag}@@ -309,10 +373,13 @@ export function TimelineAutomationLane({><title>{readOnly- ? "Click to select this clip, then double-click to add a point"- : "Double-click to add a point, drag to shape, double-click a point to type a value, right-click to remove. Alt-drag the line to curve it. Shift locks an axis; Alt ignores the grid."}+ ? "Drag a box to select points, which also selects this clip; then double-click to add a point"+ : "Double-click to add a point, drag to shape, double-click a point to type a value, right-click or Shift+click to remove it. Drag the background to draw a box around points, then Delete to remove them or drag one to move them all. Alt-drag the line to curve it. Shift locks an axis mid-drag; Alt ignores the grid."}</title>- <rect x={PAD_X} y={0} width={widthPx} height={h} fill="rgba(0,0,0,0.18)" rx={3} />+ {/* No plate behind the envelope: the lane used to darken its clip's width,+ which drew a box inside the row and made a stack of lanes read as tiles+ rather than as rows of one timeline. The row background shows through, and+ the separator above each lane is what divides them now. */}{/* Mid rail, so a value reads against something. */}<linex1={PAD_X}@@ -323,29 +390,23 @@ export function TimelineAutomationLane({strokeDasharray="3 4"/>{rangeSelection ? (- <>- <rect- data-automation-selection=""- x={xOf(rangeSelection.t0)}- y={0}- width={Math.max(0, xOf(rangeSelection.t1) - xOf(rangeSelection.t0))}- height={h}- fill={accentColor}- opacity={0.15}- pointerEvents="none"- />- {[rangeSelection.t0, rangeSelection.t1].map((t) => (- <line- key={t}- x1={xOf(t)}- x2={xOf(t)}- y1={0}- y2={h}- stroke={accentColor}- opacity={0.5}- />- ))}- </>+ <rect+ data-automation-selection=""+ x={xOf(rangeSelection.t0)}+ // v1 is the upper bound, which is the SMALLER y: the value axis runs+ // up the lane and the screen axis runs down it.+ y={yOf(rangeSelection.v1)}+ width={Math.max(0, xOf(rangeSelection.t1) - xOf(rangeSelection.t0))}+ height={Math.max(0, yOf(rangeSelection.v0) - yOf(rangeSelection.v1))}+ fill={accentColor}+ opacity={0.15}+ // Outlined as well as tinted. A box dragged thin along either axis is+ // nearly invisible as a fill, and the author still has to be able to+ // see what they drew before pressing Delete.+ stroke={accentColor}+ strokeOpacity={0.6}+ pointerEvents="none"+ />) : null}<pathd={path}@@ -354,24 +415,41 @@ export function TimelineAutomationLane({strokeWidth={1.5}opacity={lane.points.length === 0 ? 0.35 : 0.95}/>- {lane.points.map((p, i) => (- <circle- key={`${i}-${p.t}`}- data-automation-point={i}- cx={xOf(p.t)}- cy={yOf(p.v)}- r={i === dragIndex ? GRAB_PX * 0.8 : GRAB_PX * 0.55}- fill={accentColor}- stroke="rgba(0,0,0,0.5)"- strokeWidth={1}- style={{ cursor: readOnly ? "default" : "grab" }}- onContextMenu={(e) => {- e.preventDefault();- e.stopPropagation();- removeAt(i);- }}- />- ))}+ {lane.points.map((p, i) => {+ // Endpoint-inclusive, the same rule Delete uses, so what looks caught by+ // the range is exactly what the range will remove. The tinted rectangle+ // says where the selection is; this says which points it has.+ const inRange = pointInBox(p, rangeSelection);+ const { radius, stroke, strokeWidth } = pointCircleStyle(inRange, i === dragIndex);+ return (+ <circle+ key={`${i}-${p.t}`}+ data-automation-point={i}+ {...(inRange ? { "data-automation-point-in-range": "" } : {})}+ cx={xOf(p.t)}+ cy={yOf(p.v)}+ r={radius}+ fill={accentColor}+ stroke={stroke}+ strokeWidth={strokeWidth}+ // Hidden rather than unmounted, so the hit area survives: a point+ // dragged past the lane's edge fires pointerleave mid-gesture, and a+ // handle that vanishes then would drop the drag. A drag in progress+ // and a selected range both keep them up for the same reason — the+ // range is the subject of a pending Delete, and which points it+ // caught cannot depend on where the mouse is.+ style={{+ cursor: readOnly ? "default" : "grab",+ opacity: hovered || dragIndex !== null || rangeSelection ? 1 : 0,+ }}+ onContextMenu={(e) => {+ e.preventDefault();+ e.stopPropagation();+ removeAt(i);+ }}+ />+ );+ })}{playheadSec !== null && currentValue !== null ? (<circledata-automation-playhead=""@@ -497,10 +575,15 @@ export function TimelineAutomationLaneSlot({readOnly={bound.readOnly}rangeSelection={bound.selection?.target === lane.target- ? { t0: bound.selection.t0, t1: bound.selection.t1 }+ ? {+ t0: bound.selection.t0,+ t1: bound.selection.t1,+ v0: bound.selection.v0,+ v1: bound.selection.v1,+ }: null}- onRangeSelect={(t0, t1) => bound.onRangeSelect(lane.target, t0, t1)}+ onRangeSelect={(t0, t1, v0, v1) => bound.onRangeSelect(lane.target, t0, t1, v0, v1)}onRangeClear={bound.onRangeClear}/>);diff --git a/packages/studio/src/player/components/TimelineAutomationLaneSlot.test.tsx b/packages/studio/src/player/components/TimelineAutomationLaneSlot.test.tsxindex 3684a85524..d30c2390a6 100644--- a/packages/studio/src/player/components/TimelineAutomationLaneSlot.test.tsx+++ b/packages/studio/src/player/components/TimelineAutomationLaneSlot.test.tsx@@ -56,14 +56,14 @@ function mountSlot(binding: Partial<AutomationLaneBinding>) {describe("TimelineAutomationLaneSlot stale-selection guard", () => {it("clears the selection when its lane's target no longer exists", () => {const { onRangeClear } = mountSlot({- selection: { elementKey: "bgm", target: "fx.gone.wet", t0: 1, t1: 2 },+ selection: { elementKey: "bgm", target: "fx.gone.wet", t0: 1, t1: 2, v0: 0, v1: 1 },});expect(onRangeClear).toHaveBeenCalledTimes(1);});it("leaves an in-scope selection alone", () => {const { onRangeClear } = mountSlot({- selection: { elementKey: "bgm", target: "volume", t0: 1, t1: 2 },+ selection: { elementKey: "bgm", target: "volume", t0: 1, t1: 2, v0: 0, v1: 1 },});expect(onRangeClear).not.toHaveBeenCalled();});diff --git a/packages/studio/src/player/components/TimelineLanes.tsx b/packages/studio/src/player/components/TimelineLanes.tsxindex 6764b32c94..e7902160ce 100644--- a/packages/studio/src/player/components/TimelineLanes.tsx+++ b/packages/studio/src/player/components/TimelineLanes.tsx@@ -196,6 +196,26 @@ export function TimelineLanes({keyframeClipKey != null && expandedClipIds.has(keyframeClipKey);// Link the sticky caret to the canvas lanes with a stable display-row id.const lanesId = `${lanesIdPrefix}-track-${row}`;+ // The header's remove buttons write through the same binding the lanes+ // themselves edit through, so a deletion persists exactly like dragging+ // a point does — and the binding reports read-only for an unselected+ // clip, which is what leaves the buttons off rather than offering one+ // that cannot act.+ const headerLanes =+ keyframeClip && keyframeClipKey+ ? automationLanes.bind(+ keyframeClip,+ selectedElementId === keyframeClipKey || selectedElementIds.has(keyframeClipKey),+ )+ : null;+ const removeAutomationLane =+ headerLanes && !headerLanes.readOnly+ ? (target: string) =>+ headerLanes.onCommit({+ version: 1,+ lanes: headerLanes.lanes.filter((lane) => lane.target !== target),+ })+ : undefined;return (<TimelineTrackRowkey={rowKey}@@ -239,6 +259,7 @@ export function TimelineLanes({}}onToggleTrackHidden={onToggleTrackHidden}onTogglePropertyGroupKeyframe={onTogglePropertyGroupKeyframe}+ onRemoveAutomationLane={removeAutomationLane}onSeek={onSeek}rovingTargetId={keyboard.rovingTargetId}/>diff --git a/packages/studio/src/player/components/TimelineTrackHeader.test.tsx b/packages/studio/src/player/components/TimelineTrackHeader.test.tsxindex bd591054e6..af763b7258 100644--- a/packages/studio/src/player/components/TimelineTrackHeader.test.tsx+++ b/packages/studio/src/player/components/TimelineTrackHeader.test.tsx@@ -9,7 +9,8 @@ import { TimelineTrackHeader } from "./TimelineTrackHeader";import { defaultTimelineTheme } from "./timelineTheme";import type { TimelineElement } from "../store/playerStore";import type { TimelineEditCallbacks } from "./timelineCallbacks";-import { LABEL_COL_W } from "./timelineLayout";+import { getTimelineLaneTop, LABEL_COL_W } from "./timelineLayout";+import { AUTOMATION_LANE_H } from "./automationLaneHeight";(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -68,6 +69,7 @@ interface RenderHeaderOptions {onSeek?: (time: number) => void;onTogglePropertyGroupKeyframe?: TimelineEditCallbacks["onTogglePropertyGroupKeyframe"];onToggleTrackHidden?: TimelineEditCallbacks["onToggleTrackHidden"];+ onRemoveAutomationLane?: (target: string) => void;}function renderHeader(options: RenderHeaderOptions = {}): {@@ -100,6 +102,7 @@ function renderHeader(options: RenderHeaderOptions = {}): {onToggleClipExpanded={vi.fn()}onToggleTrackHidden={next.onToggleTrackHidden ?? vi.fn()}onTogglePropertyGroupKeyframe={next.onTogglePropertyGroupKeyframe}+ onRemoveAutomationLane={next.onRemoveAutomationLane}onSeek={next.onSeek}/>,);@@ -414,4 +417,115 @@ describe("TimelineTrackHeader", () => {assertAligned([POSITION, OPACITY]);act(() => view.root.unmount());});++ /**+ * Automation lanes are named in the label column, on the same tree as the+ * keyframe rows — not painted inside the lane, where the name sat on top of+ * the envelope it belonged to and scrolled away from its own row.+ */+ describe("audio automation rows", () => {+ const BED: TimelineElement = {+ id: "bed",+ label: "Music Bed",+ tag: "audio",+ start: 0,+ duration: 10,+ track: 0,+ fxChain: JSON.stringify({+ version: 1,+ nodes: [{ type: "peaking", id: "n1", params: { frequency: 1600, gain: -6, q: 1.4 } }],+ }),+ automation: JSON.stringify({+ version: 1,+ lanes: [+ {+ target: "volume",+ points: [+ { t: 0, v: 1 },+ { t: 5, v: 0.4 },+ ],+ },+ {+ target: "fx.n1.gain",+ points: [+ { t: 0, v: 0 },+ { t: 5, v: -6 },+ ],+ },+ ],+ }),+ } as TimelineElement;++ it("names every envelope in the label column", () => {+ const { host, root } = renderHeader({ keyframeClip: BED, animations: [] });+ const rows = Array.from(host.querySelectorAll<HTMLElement>("[data-automation-lane-label]"));+ expect(rows.map((r) => r.getAttribute("data-automation-lane-label"))).toEqual([+ "fx.n1.gain",+ "volume",+ ]);+ // A band is named by its frequency: with several of them, "Peaking EQ" says+ // nothing about which is which. Bands sit above the level lanes.+ // Two lines per row: what the effect is, then which knob the envelope+ // drives. One line truncated mid-word in a column this narrow.+ expect(rows.map((r) => r.querySelector("[data-automation-lane-name]")?.textContent)).toEqual([+ "Peaking EQ 1.6 kHz",+ "Volume",+ ]);+ expect(rows.map((r) => r.querySelector("[data-automation-lane-param]")?.textContent)).toEqual(+ [+ "Gain",+ // Volume has no effect behind it, so it has no second line at all.+ undefined,+ ],+ );+ act(() => root.unmount());+ });++ it("hides them when the track is collapsed", () => {+ const { host, root } = renderHeader({+ keyframeClip: BED,+ animations: [],+ expanded: false,+ });+ expect(host.querySelectorAll("[data-automation-lane-label]")).toHaveLength(0);+ act(() => root.unmount());+ });++ it("removes just that envelope from the label column", () => {+ // The panel's automate toggle can only reach a parameter it still shows; a+ // carve's own lanes are not in it at all, so without this an envelope could+ // be created and never deleted.+ const onRemoveAutomationLane = vi.fn();+ const { host, root } = renderHeader({+ keyframeClip: BED,+ animations: [],+ onRemoveAutomationLane,+ });+ const button = host.querySelector<HTMLButtonElement>(+ 'button[aria-label="Remove Peaking EQ 1.6 kHz · Gain automation"]',+ );+ expect(button).not.toBeNull();+ act(() => button?.click());+ expect(onRemoveAutomationLane).toHaveBeenCalledWith("fx.n1.gain");+ act(() => root.unmount());+ });++ it("offers no remove button when the lanes are read-only", () => {+ const { host, root } = renderHeader({ keyframeClip: BED, animations: [] });+ expect(host.querySelectorAll('button[aria-label$="automation"]')).toHaveLength(0);+ act(() => root.unmount());+ });++ it("stacks each envelope's row where its lane is drawn", () => {+ // Same rhythm the canvas uses: automation begins below the keyframe lanes+ // and steps by its own taller row height.+ const { host, root } = renderHeader({ keyframeClip: BED, animations: [OPACITY] });+ const tops = Array.from(+ host.querySelectorAll<HTMLElement>("[data-automation-lane-label]"),+ ).map((r) => r.style.top);+ const base = getTimelineLaneTop(1);+ expect(tops).toEqual([`${base}px`, `${base + AUTOMATION_LANE_H}px`]);+ act(() => root.unmount());+ });+ });});diff --git a/packages/studio/src/player/components/TimelineTrackHeader.tsx b/packages/studio/src/player/components/TimelineTrackHeader.tsxindex 707c809c77..8241e8e1fd 100644--- a/packages/studio/src/player/components/TimelineTrackHeader.tsx+++ b/packages/studio/src/player/components/TimelineTrackHeader.tsx@@ -5,6 +5,13 @@ import type { TimelineElement } from "../store/playerStore";import type { TimelineEditCallbacks } from "./timelineCallbacks";import { getTimelinePropertyLanes } from "./TimelinePropertyLanes";import { automationLaneCountOf } from "./useTimelineTrackLayout";+import {+ automationLaneLabel,+ automationLaneLabelParts,+ elementAutomationLanes,+ elementFxChain,+} from "./automationLaneData";+import { AUTOMATION_LANE_H } from "./automationLaneHeight";import { clipTimingStart } from "../../hooks/gsapShared";import { LayerDisclosureRow } from "./LayerDisclosureRow";import { TrackClipCount } from "./TrackClipCount";@@ -19,6 +26,32 @@ import { valueReadout } from "./trackHeaderLaneValues";import { trackDisplaySuffix } from "./timelineTrackDisplay";import { timelineLogicalRowCellId, timelinePropertyRowId } from "./timelineNavigationIdentity";+/** One envelope's label-column row content, resolved against the FX chain. */+interface AutomationRowInfo {+ target: string;+ label: string;+ name: string;+ param: string;+}++/**+ * Each envelope's name, resolved against the chain the same way the lane+ * resolves its axis — a band is named by its frequency, not by its effect. The+ * lane list is already in drawing order, which is the order these rows have to+ * follow: a name beside the wrong envelope is worse than an awkward order.+ */+function resolveAutomationRows(keyframeClip: TimelineElement | null): AutomationRowInfo[] {+ if (!keyframeClip) return [];+ const chain = elementFxChain(keyframeClip);+ return elementAutomationLanes(keyframeClip).flatMap((lane) => {+ const parts = automationLaneLabelParts(lane.target, chain);+ const label = automationLaneLabel(lane.target, chain);+ return parts && label+ ? [{ target: lane.target, label, name: parts.name, param: parts.param }]+ : [];+ });+}+interface TimelineTrackHeaderProps {/** The track's real key: a FRACTIONAL z-order sort value. Routes callbacks;* never shown or announced. */@@ -48,6 +81,9 @@ interface TimelineTrackHeaderProps {onToggleClipExpanded: () => void;onToggleTrackHidden: TimelineEditCallbacks["onToggleTrackHidden"];onTogglePropertyGroupKeyframe?: TimelineEditCallbacks["onTogglePropertyGroupKeyframe"];+ /** Drop one envelope. Absent while the lanes are read-only, which is what+ * hides the control rather than offering a button that cannot act. */+ onRemoveAutomationLane?: (target: string) => void;onSeek?: (time: number) => void;}@@ -292,6 +328,102 @@ function PropertyGroupHeaderRow({);}+/**+ * One envelope's row in the label column.+ *+ * Named here rather than inside the lane, on the same tree connector the+ * keyframe rows use: an automation lane is a child of its clip exactly as a+ * property group is, and drawing its name over the envelope put the label on top+ * of the curve it describes and scrolled it away from its own row.+ */+function AutomationLaneHeaderRow({+ target,+ label,+ name,+ param,+ top,+ isLastLane,+ gutterBackground,+ columnWidth,+ onRemove,+}: {+ target: string;+ /** The whole thing on one line, for the tooltip and the remove button's name. */+ label: string;+ /** What the effect is — "Peaking EQ 1.6 kHz". */+ name: string;+ /** Which knob the envelope drives. Empty when there is no second line to draw. */+ param: string;+ top: number;+ isLastLane: boolean;+ gutterBackground: string;+ columnWidth: number;+ onRemove?: (target: string) => void;+}) {+ return (+ <div+ data-automation-lane-label={target}+ data-timeline-lane-top={top}+ className="absolute left-0 flex items-center gap-1 overflow-hidden px-1.5 text-[10px] text-white/65"+ style={{+ top,+ width: columnWidth,+ height: AUTOMATION_LANE_H,+ background: gutterBackground,+ }}+ >+ {/* Tree connector, as the keyframe rows draw it: spine down the row, branch+ tick at the name's own height. */}+ <span className="relative h-full w-3 shrink-0" aria-hidden="true">+ <span+ className="absolute left-1.5 top-0 w-px bg-white/15"+ style={{ height: isLastLane ? "50%" : "100%" }}+ />+ <span className="absolute left-1.5 top-1/2 h-px w-1.5 bg-white/15" />+ </span>+ {/* Two lines: what the effect is, then which knob the envelope drives. On+ one line a band's own name was the first thing truncated in a column this+ narrow — "Peaking EQ 1.6 k…" — losing exactly the part that tells two+ bands apart. */}+ <span className="flex min-w-0 flex-1 flex-col justify-center leading-tight" title={label}>+ <span data-automation-lane-name="" className="truncate font-mono text-[9px] text-white/70">+ {name}+ </span>+ {param ? (+ <span+ data-automation-lane-param=""+ className="truncate font-mono text-[9px] text-white/40"+ >+ {param}+ </span>+ ) : null}+ </span>+ {/* Beside the name it labels, because that is the only place an envelope is+ named at all: a carve writes its own lanes, and the FX panel's automate+ toggle can only reach a parameter it still lists — so without this an+ envelope could be created and never removed. */}+ {onRemove && (+ <button+ type="button"+ aria-label={`Remove ${label} automation`}+ title={`Remove ${label} automation`}+ // h-6 w-6 is the 24x24 WCAG 2.2 target; the glyph stays small.+ className="flex h-6 w-6 shrink-0 items-center justify-center border-0 bg-transparent p-0 text-[11px] text-white/35 hover:text-white focus-visible:outline focus-visible:outline-1 focus-visible:outline-[#3CE6AC]"+ onPointerDown={(event) => event.stopPropagation()}+ onClick={(event) => {+ // A control in the label column owns its click; it does not also hit+ // the track row behind it and change the selection.+ event.stopPropagation();+ onRemove(target);+ }}+ >+ ×+ </button>+ )}+ </div>+ );+}+export function TimelineTrackHeader({trackNumber,trackDisplayNumber,@@ -309,6 +441,7 @@ export function TimelineTrackHeader({onToggleClipExpanded,onToggleTrackHidden,onTogglePropertyGroupKeyframe,+ onRemoveAutomationLane,onSeek,rovingTargetId = null,}: TimelineTrackHeaderProps) {@@ -327,6 +460,7 @@ export function TimelineTrackHeader({// left an audio clip's envelopes unreachable, since the track could not expand.const disclosable =lanes.length > 0 || (keyframeClip ? automationLaneCountOf(keyframeClip) : 0) > 0;+ const automationRows = resolveAutomationRows(keyframeClip);const isKeyframeLayer = !!keyframeClip && disclosable;return (@@ -396,7 +530,7 @@ export function TimelineTrackHeader({lanesId={lanesId}lane={lane}laneIndex={laneIndex}- isLastLane={laneIndex === lanes.length - 1}+ isLastLane={laneIndex === lanes.length - 1 && automationRows.length === 0}expandedElement={keyframeClip}currentTime={currentTime}clipPercentage={clipPercentage}@@ -407,6 +541,24 @@ export function TimelineTrackHeader({rovingTargetId={rovingTargetId}/>))}+ {/* Below the keyframe rows and stepping by its own height, which is how+ TimelineAutomationLaneSlot lays the envelopes out on the canvas. The+ two have to agree or a name labels the wrong curve. */}+ {isExpanded &&+ automationRows.map((row, index) => (+ <AutomationLaneHeaderRow+ key={row.target}+ target={row.target}+ label={row.label}+ name={row.name}+ param={row.param}+ top={getTimelineLaneTop(lanes.length) + index * AUTOMATION_LANE_H}+ isLastLane={index === automationRows.length - 1}+ gutterBackground={theme.gutterBackground}+ columnWidth={showTrackLabel ? LABEL_COL_W : contentOrigin}+ onRemove={onRemoveAutomationLane}+ />+ ))}</>)}</div>diff --git a/packages/studio/src/player/components/automationGestureKeys.test.ts b/packages/studio/src/player/components/automationGestureKeys.test.tsnew file mode 100644index 0000000000..c88cfd2bd3--- /dev/null+++ b/packages/studio/src/player/components/automationGestureKeys.test.ts@@ -0,0 +1,49 @@+import { describe, expect, it } from "vitest";+import { createAutomationGestureKeys } from "./automationGestureKeys";++const keys = () => {+ let n = 0;+ return createAutomationGestureKeys(() => `g${++n}`);+};++describe("createAutomationGestureKeys", () => {+ it("holds one key across every move of a drag", () => {+ // Each move persists; history merges same-key entries inside 300ms. Separate+ // keys, or a window that can expire mid-drag, is what made undo take back a+ // fragment of the move instead of the move.+ const g = keys();+ expect([g.live().key, g.live().key, g.live().key]).toEqual(["g1", "g1", "g1"]);+ });++ it("never lets the window expire", () => {+ expect(keys().live().ms).toBe(Number.POSITIVE_INFINITY);+ expect(keys().commit().ms).toBe(Number.POSITIVE_INFINITY);+ });++ it("ends the gesture on the release, under the same key", () => {+ const g = keys();+ g.live();+ expect(g.commit().key).toBe("g1");+ });++ it("starts a fresh key for the next drag", () => {+ const g = keys();+ g.live();+ g.commit();+ expect(g.live().key).toBe("g2");+ });++ it("gives a standalone commit its own key", () => {+ // Deleting a range, pasting one, typing a value: one write, one step each.+ const g = keys();+ expect(g.commit().key).toBe("g1");+ expect(g.commit().key).toBe("g2");+ });++ it("does not join a commit to a gesture that already ended", () => {+ const g = keys();+ g.live();+ g.commit();+ expect(g.commit().key).toBe("g2");+ });+});diff --git a/packages/studio/src/player/components/automationGestureKeys.ts b/packages/studio/src/player/components/automationGestureKeys.tsnew file mode 100644index 0000000000..387ff52096--- /dev/null+++ b/packages/studio/src/player/components/automationGestureKeys.ts@@ -0,0 +1,49 @@+/**+ * Undo grouping for a lane gesture.+ *+ * Dragging a point persists on every move and once more on release. History+ * coalesces entries that share a key and land within 300ms of each other, and+ * these writes did neither: the moves and the release used different keys, and a+ * drag slower than the window split into several entries. Undo then took back+ * whatever fragment happened to be last, leaving the point near where the drag+ * had dropped it — which reads as undo not working at all.+ *+ * So a gesture mints one key and holds it: every move and the release that ends+ * it record under that key with no window to expire, and the next gesture gets a+ * fresh one so two drags never collapse into a single step.+ */++export interface CoalesceHint {+ key: string;+ /** No expiry: a gesture is one step however long the pointer is held. */+ ms: number;+}++export interface AutomationGestureKeys {+ /** A continuous write. Opens a gesture if one is not already open. */+ live(): CoalesceHint;+ /** The persisting write that ends a gesture — or a standalone edit. */+ commit(): CoalesceHint;+}++export function createAutomationGestureKeys(+ mint: () => string = () => `automation-gesture:${++counter}`,+): AutomationGestureKeys {+ let open: string | null = null;+ const hint = (key: string): CoalesceHint => ({ key, ms: Number.POSITIVE_INFINITY });+ return {+ live: () => {+ open ??= mint();+ return hint(open);+ },+ commit: () => {+ // A commit with no drag before it — a Delete, a paste, a typed value — is+ // its own step, so it mints rather than joining anything.+ const key = open ?? mint();+ open = null;+ return hint(key);+ },+ };+}++let counter = 0;diff --git a/packages/studio/src/player/components/automationLaneData.test.ts b/packages/studio/src/player/components/automationLaneData.test.tsindex 948c926167..69b486b871 100644--- a/packages/studio/src/player/components/automationLaneData.test.ts+++ b/packages/studio/src/player/components/automationLaneData.test.ts@@ -1,6 +1,11 @@// @vitest-environment happy-domimport { describe, expect, it } from "vitest";-import { elementAutomation, elementFxChain } from "./automationLaneData";+import {+ automationLaneLabel,+ automationLaneLabelParts,+ elementAutomation,+ elementFxChain,+} from "./automationLaneData";import type { TimelineElement } from "../store/timelineElement";const el = (over: Partial<TimelineElement> = {}): TimelineElement => ({@@ -13,6 +18,9 @@ const el = (over: Partial<TimelineElement> = {}): TimelineElement => ({...over,});+/** The chain as the lane code sees it: parsed, not the attribute text. */+const parseChain = (chain: unknown) => elementFxChain(el({ fxChain: JSON.stringify(chain) }))!;+const CHAIN = JSON.stringify({version: 1,nodes: [{ type: "lowpass", id: "n1", params: { frequency: 400, q: 0.9, poles: "2" } }],@@ -63,4 +71,91 @@ describe("automationLaneData", () => {expect(elementAutomation(el({ automation: "{nope" })).lanes).toEqual([]);expect(elementFxChain(el({ fxChain: "{nope" }))).toBeNull();});++ describe("lane order", () => {+ // A stack of EQ bands reads as a spectrum, so it has to be laid out like one:+ // the top of the stack is the top of the audible range. Attribute order is+ // whatever the carve happened to mint, which is the opposite — bands come out+ // ascending.+ const bandChain = JSON.stringify({+ version: 1,+ nodes: [+ { type: "peaking", id: "n1", params: { frequency: 400, gain: -6, q: 1.4 } },+ { type: "peaking", id: "n2", params: { frequency: 1600, gain: -9, q: 1.4 } },+ { type: "peaking", id: "n3", params: { frequency: 1000, gain: -3, q: 1.4 } },+ { type: "gain", id: "n4", params: { gain: -6 } },+ ],+ });+ const bandLanes = JSON.stringify({+ version: 1,+ lanes: [+ { target: "volume", points: [{ t: 0, v: 1 }] },+ { target: "fx.n1.gain", points: [{ t: 0, v: -6 }] },+ { target: "fx.n2.gain", points: [{ t: 0, v: -9 }] },+ { target: "fx.n3.gain", points: [{ t: 0, v: -3 }] },+ { target: "fx.n4.gain", points: [{ t: 0, v: -6 }] },+ ],+ });++ it("puts the highest frequency at the top", () => {+ const lanes = elementAutomation(el({ automation: bandLanes, fxChain: bandChain })).lanes;+ expect(lanes.map((l) => l.target)).toEqual([+ "fx.n2.gain", // 1.6 kHz+ "fx.n3.gain", // 1 kHz+ "fx.n1.gain", // 400 Hz+ // Neither of these is a band, so they sit under the spectrum in the order+ // they were written.+ "volume",+ "fx.n4.gain",+ ]);+ });++ it("keeps the same object identity, so a drag survives the sort", () => {+ const a = elementAutomation(el({ automation: bandLanes, fxChain: bandChain }));+ const b = elementAutomation(el({ automation: bandLanes, fxChain: bandChain }));+ expect(a).toBe(b);+ });+ });++ describe("automationLaneLabel", () => {+ const chain = parseChain({+ version: 1,+ nodes: [+ { type: "peaking", id: "n1", params: { frequency: 1600, gain: -9, q: 1.4 } },+ { type: "peaking", id: "n2", params: { frequency: 400, gain: -6, q: 1.4 } },+ { type: "gain", id: "n3", params: { gain: -6 } },+ ],+ });++ it("names the effect and the band it sits at", () => {+ // Three lanes all reading "Peaking EQ · Gain" say nothing about which band+ // each one is; a bare frequency does not say whether it is a bell or a+ // shelf. Both, then the parameter.+ expect(automationLaneLabel("fx.n1.gain", chain)).toBe("Peaking EQ 1.6 kHz · Gain");+ expect(automationLaneLabel("fx.n2.gain", chain)).toBe("Peaking EQ 400 Hz · Gain");+ });++ it("falls back to the effect's name when it has no frequency", () => {+ expect(automationLaneLabel("fx.n3.gain", chain)).toBe("Gain · Gain");+ expect(automationLaneLabel("volume", chain)).toBe("Volume");+ });++ it("has nothing to say about a target that does not resolve", () => {+ expect(automationLaneLabel("fx.gone.gain", chain)).toBeNull();+ expect(automationLaneLabelParts("fx.gone.gain", chain)).toBeNull();+ });++ it("splits the name from the parameter, which the column stacks", () => {+ expect(automationLaneLabelParts("fx.n1.gain", chain)).toEqual({+ name: "Peaking EQ 1.6 kHz",+ param: "Gain",+ });+ expect(automationLaneLabelParts("fx.n3.gain", chain)).toEqual({+ name: "Gain",+ param: "Gain",+ });+ // Volume is one word with no effect behind it, so there is no second line.+ expect(automationLaneLabelParts("volume", chain)).toEqual({ name: "Volume", param: "" });+ });+ });});diff --git a/packages/studio/src/player/components/automationLaneData.ts b/packages/studio/src/player/components/automationLaneData.tsindex 375f891dcd..e62b8b7324 100644--- a/packages/studio/src/player/components/automationLaneData.ts+++ b/packages/studio/src/player/components/automationLaneData.ts@@ -15,7 +15,9 @@import {parseAutomation,+ parseAutomationTarget,resolveAutomation,+ resolveAutomationRange,type HfAutomation,type HfAutomationLane,} from "@hyperframes/core/audio-automation";@@ -79,7 +81,8 @@ export function elementAutomation(element: TimelineElement): HfAutomation {// through a separator no attribute can contain.return cached(automationCache, `${raw}\u0000${element.fxChain ?? ""}`, () => {try {- return resolveAutomation(parseAutomation(raw), chain ?? undefined);+ const resolved = resolveAutomation(parseAutomation(raw), chain ?? undefined);+ return { ...resolved, lanes: orderLanes(resolved.lanes, chain) };} catch {// Unreadable automation draws no lanes rather than breaking the row.return EMPTY;@@ -91,3 +94,83 @@ export function elementAutomation(element: TimelineElement): HfAutomation {export function elementAutomationLanes(element: TimelineElement): HfAutomationLane[] {return elementAutomation(element).lanes;}++/** The frequency the lane's effect sits at, when it has one. */+function laneFrequency(target: string, chain: HfAudioFxChain | null): number | null {+ const parsed = parseAutomationTarget(target);+ if (!parsed || parsed.kind !== "fx") return null;+ const node = chain?.nodes.find((n) => n.id === parsed.nodeId);+ const freq = node?.params?.["frequency"];+ return typeof freq === "number" ? freq : null;+}++/**+ * Lane order: the audible spectrum, top down, then everything else.+ *+ * A stack of EQ bands is read as a spectrum, so it has to be laid out like one —+ * high at the top, the way every analyser and every EQ curve is drawn. Attribute+ * order is whatever minted the nodes, which for a carve is ascending: exactly+ * upside down. Lanes with no frequency to place them — a level stage, the track's+ * own volume — keep their written order and sit under the bands, like a fader+ * below the EQ section of a channel strip.+ *+ * Sorted here, in the one function both the canvas lanes and the label column+ * read, because a label whose row disagrees with the envelope it names is worse+ * than either order.+ */+function orderLanes(lanes: HfAutomationLane[], chain: HfAudioFxChain | null): HfAutomationLane[] {+ const withFreq: { lane: HfAutomationLane; freq: number }[] = [];+ const rest: HfAutomationLane[] = [];+ for (const lane of lanes) {+ const freq = laneFrequency(lane.target, chain);+ if (freq === null) rest.push(lane);+ else withFreq.push({ lane, freq });+ }+ withFreq.sort((a, b) => b.freq - a.freq);+ return [...withFreq.map((e) => e.lane), ...rest];+}++/** A frequency as an author reads it: 400 Hz, 1.6 kHz, 10 kHz. */+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`;+}++/**+ * What a lane is called in the timeline, as its two lines.+ *+ * `name` is the effect and, when it has one, the frequency it sits at: "Peaking+ * EQ 1.6 kHz". The frequency is what tells two bands apart — three lanes all+ * reading "Peaking EQ" say nothing about which is which — and the effect still+ * has to be named, since a chain mixes filter types and a bare frequency does not+ * say whether it is a bell or a shelf.+ *+ * `param` is which knob the envelope drives, on its own line: a band can carry a+ * gain lane and a Q lane, and stacking the two lines is what keeps a name legible+ * in a column this narrow instead of truncating mid-word.+ *+ * Null when the target does not resolve against the chain — the same condition+ * that stops the lane being drawn at all.+ */+export function automationLaneLabelParts(+ target: string,+ chain: HfAudioFxChain | null,+): { name: string; param: string } | null {+ const range = resolveAutomationRange(target, chain ?? undefined);+ if (!range) return null;+ // The registry's label is "<effect> · <param>", or just "<param>" for volume.+ const parts = range.label.split(" · ");+ const param = parts.at(-1) ?? range.label;+ const effect = parts.length > 1 ? parts.slice(0, -1).join(" · ") : null;+ const freq = laneFrequency(target, chain);+ const name = [effect, freq === null ? null : formatHz(freq)].filter(Boolean).join(" ");+ return { name: name || param, param: name ? param : "" };+}++/** The whole label on one line, for a tooltip or an accessible name. */+export function automationLaneLabel(target: string, chain: HfAudioFxChain | null): string | null {+ const parts = automationLaneLabelParts(target, chain);+ if (!parts) return null;+ return parts.param ? `${parts.name} · ${parts.param}` : parts.name;+}diff --git a/packages/studio/src/player/components/automationLaneDragMath.ts b/packages/studio/src/player/components/automationLaneDragMath.tsnew file mode 100644index 0000000000..79b029a66d--- /dev/null+++ b/packages/studio/src/player/components/automationLaneDragMath.ts@@ -0,0 +1,194 @@+/**+ * Pure position math for the two multi-point drags on an automation lane: a+ * group move (dragging a whole box-selected set by one delta) and a single+ * point's move (the modifiers and neighbour clamp one breakpoint honours).+ *+ * Split out of useAutomationLaneGestures.ts so the hook's own onPointerDown+ * and movePoint stay orchestration — read the pointer, call one of these,+ * apply the result — rather than carrying this branching themselves.+ */++import type { AutomationRange, HfAutomationLane } from "@hyperframes/core/audio-automation";+import {+ applyShiftConstraint,+ dominantDragAxis,+ MIN_POINT_GAP_SEC,+ snapLaneTime,+} from "./automationLaneGeometry";+import { pointInSelection } from "./automationLaneSelection";++/** Snap radius in clip seconds, shared with the single-point and group drags. */+export const SNAP_SEC = 0.04;++export type AutomationSelectionBox = { t0: number; t1: number; v0: number; v1: number };++/** Which points a press on `pressed` should drag together: the whole box-selected+ * set if it contains more than one member, otherwise none (an ordinary+ * single-point drag, selection or no). */+function resolveGroupDragIndices(+ lane: HfAutomationLane,+ pressed: HfAutomationLane["points"][number] | undefined,+ rangeSelection: AutomationSelectionBox | null | undefined,+): number[] {+ if (!rangeSelection || !pressed || !pointInSelection(pressed, rangeSelection)) return [];+ return lane.points.flatMap((p, i) => (pointInSelection(p, rangeSelection) ? [i] : []));+}++export interface GroupDragSnapshot {+ points: HfAutomationLane["points"];+ indices: number[];+ anchor: { t: number; v: number };+ selection: AutomationSelectionBox;+}++/** Snapshot to arm a group drag from a press on `pressed`, or null when the+ * press does not land on a multi-point selection — an ordinary single-point+ * drag, selection or no. */+export function armGroupDrag(+ lane: HfAutomationLane,+ pressed: HfAutomationLane["points"][number] | undefined,+ rangeSelection: AutomationSelectionBox | null | undefined,+): GroupDragSnapshot | null {+ const indices = resolveGroupDragIndices(lane, pressed, rangeSelection);+ if (indices.length <= 1 || !pressed) return null;+ return {+ points: lane.points.map((p) => ({ ...p })),+ indices,+ anchor: { t: pressed.t, v: pressed.v },+ selection: rangeSelection ? { ...rangeSelection } : { t0: 0, t1: 0, v0: 0, v1: 0 },+ };+}++export interface GroupMoveResult {+ points: HfAutomationLane["points"];+ selection: AutomationSelectionBox;+ hint: string;+}++/**+ * Move a selected set by one delta, taken from the point under the pointer.+ *+ * The whole group has to stop when its first member reaches a boundary, not+ * each point on its own: clamping individually squashes the shape flat against+ * the edge, and the gesture is meant to preserve it. Deltas are in the+ * parameter's own units, so on a logarithmic axis a group moves by Hz rather+ * than by octaves — the same as dragging one point does.+ */+export function computeGroupMove(input: {+ group: GroupDragSnapshot;+ raw: { t: number; v: number };+ shiftKey: boolean;+ altKey: boolean;+ range: AutomationRange;+ duration: number;+ snapTimes: readonly number[] | undefined;+ xOf(t: number): number;+ yOf(v: number): number;+}): GroupMoveResult {+ const { group, raw, shiftKey, altKey, range, duration, snapTimes, xOf, yOf } = input;+ const moving = group.indices.map((i) => group.points[i]!);+ let dt = raw.t - group.anchor.t;+ let dv = raw.v - group.anchor.v;+ if (shiftKey) {+ // The axis lock, as a single-point drag has it: keep whichever the pointer+ // has travelled further along and drop the other.+ const alongTime = Math.abs(dt * (xOf(1) - xOf(0)));+ const alongValue = Math.abs((dv * (yOf(range.min) - yOf(range.max))) / (range.max - range.min));+ if (alongTime >= alongValue) dv = 0;+ else dt = 0;+ } else if (!altKey) {+ // Snap the point under the pointer, and move the set by that same amount.+ const others = group.points.filter((_, i) => !group.indices.includes(i)).map((p) => p.t);+ dt =+ snapLaneTime(group.anchor.t + dt, [...(snapTimes ?? []), ...others], SNAP_SEC) -+ group.anchor.t;+ }+ const times = moving.map((p) => p.t);+ const values = moving.map((p) => p.v);+ // No member may cross a point that is staying put. Only stationary+ // neighbours constrain: two selected points travel together, so the gap+ // between them never changes. Per member rather than per end of the group,+ // because a box can select a non-contiguous set — the peaks of an envelope+ // and not the dip between them.+ const gapTo = (step: 1 | -1): number[] =>+ group.indices.flatMap((i) => {+ const neighbour = group.points[i + step];+ if (!neighbour || group.indices.includes(i + step)) return [];+ // Short of the neighbour, not onto it — the lane collapses points that+ // share a time, and a group drag must not consume what it runs into.+ return [Math.max(0, Math.abs(neighbour.t - group.points[i]!.t) - MIN_POINT_GAP_SEC)];+ });+ dt = Math.min(+ Math.max(dt, -Math.min(Math.min(...times), ...gapTo(-1))),+ Math.min(duration - Math.max(...times), ...gapTo(1)),+ );+ dv = Math.min(Math.max(dv, range.min - Math.min(...values)), range.max - Math.max(...values));++ // No re-sort: clamped to the neighbours, the lane's order cannot change+ // under a drag, so the point under the pointer keeps its index.+ const points = group.points.map((p, i) =>+ group.indices.includes(i) ? { ...p, t: p.t + dt, v: p.v + dv } : p,+ );+ return {+ points,+ // The box travels with the points — both axes, or a vertical nudge would+ // slide its own points out of the box that caught them and a second nudge+ // would move fewer of them.+ selection: {+ t0: group.selection.t0 + dt,+ t1: group.selection.t1 + dt,+ v0: group.selection.v0 + dv,+ v1: group.selection.v1 + dv,+ },+ hint: `${group.indices.length} points ${dt >= 0 ? "+" : ""}${dt.toFixed(2)}s`,+ };+}++/** Where Shift last locked a single-point drag's axis. */+export type ShiftAxis = "time" | "value" | null;++/** The clip-local time and value a single dragged point should land on,+ * honouring the modifiers held with it and the neighbours it cannot cross. */+export function computeSinglePointMove(input: {+ raw: { t: number; v: number };+ origin: { t: number; v: number } | null;+ shiftKey: boolean;+ altKey: boolean;+ shiftAxis: ShiftAxis;+ range: AutomationRange;+ duration: number;+ snapTimes: readonly number[] | undefined;+ lane: HfAutomationLane;+ dragIndex: number;+ xOf(t: number): number;+ yOf(v: number): number;+}): { t: number; v: number; shiftAxis: ShiftAxis } {+ const { raw, origin, shiftKey, altKey, range, duration, snapTimes, lane, dragIndex, xOf, yOf } =+ input;+ let shiftAxis = shiftKey ? input.shiftAxis : null;+ let { t, v } = raw;+ if (shiftKey && origin) {+ shiftAxis ??= dominantDragAxis({ origin, raw, xOf, yOf });+ ({ t, v } = applyShiftConstraint({ range, origin, raw, xOf, yOf, axis: shiftAxis }));+ }+ // Shift is a deliberate free-hand move as much as Alt is, so neither snaps.+ if (!altKey && !shiftKey) {+ const neighbours = lane.points.filter((_, i) => i !== dragIndex).map((p) => p.t);+ t = snapLaneTime(t, [...(snapTimes ?? []), ...neighbours], SNAP_SEC);+ }+ // A breakpoint cannot cross another in time, and cannot land exactly on one+ // either: the lane collapses points that share a `t`, so arriving on top of a+ // neighbour deletes it. It stops a hair short instead, which reads as touching+ // and keeps both points. Applied after the snap, which can itself put the+ // point on a beat past a neighbour.+ const floor = (lane.points[dragIndex - 1]?.t ?? -Infinity) + MIN_POINT_GAP_SEC;+ const ceiling = (lane.points[dragIndex + 1]?.t ?? Infinity) - MIN_POINT_GAP_SEC;+ const held = lane.points[dragIndex]?.t ?? t;+ t =+ ceiling >= floor+ ? Math.min(ceiling, Math.max(floor, Math.min(duration, Math.max(0, t))))+ : // Neighbours closer together than the gap leave nowhere to go, so the+ // point stays where it is rather than being flung to one side.+ held;+ return { t, v, shiftAxis };+}diff --git a/packages/studio/src/player/components/automationLaneGeometry.test.ts b/packages/studio/src/player/components/automationLaneGeometry.test.tsindex 2b087bd9b0..105cb3b6f3 100644--- a/packages/studio/src/player/components/automationLaneGeometry.test.ts+++ b/packages/studio/src/player/components/automationLaneGeometry.test.ts@@ -79,29 +79,97 @@ describe("curveForDrag", () => {const a = { t: 0, v: 1 };const b = { t: 4, v: 0 };+ /** The segment the drag describes, as the model would store it. */+ const bentLane = (bend: { viaX: number; viaY: number } | null) => ({+ target: "volume",+ points: [{ ...a, ...(bend ?? {}) }, b],+ });+it("puts the curved segment through the point that was dragged", () => {- // The whole contract: whatever curve comes back, sampling the segment at the- // dragged time has to give the dragged value back — otherwise the line runs- // away from the pointer.+ // The whole contract: sampling the segment at the dragged time gives the dragged+ // value back, so the line never runs away from the pointer. Anywhere in the+ // segment, at any depth.for (const [t, v] of [- [1, 0.9],- [2, 0.8],- [3, 0.15],+ [0.4, 0.75],+ [1.6, 0.65],+ [2, 0.6],+ [2, 0.1],+ [2.8, 0.4],+ [3.6, 0.5],] as const) {- const curve = curveForDrag({ range: VOLUME_RANGE, a, b, t, v });- expect(curve).not.toBeNull();- const lane = { target: "volume", points: [{ ...a, curve: curve ?? 0 }, b] };- expect(sampleAutomationLane(lane, t, "linear")).toBeCloseTo(v, 2);+ const bend = curveForDrag({ range: VOLUME_RANGE, a, b, t, v });+ expect(bend).not.toBeNull();+ expect(sampleAutomationLane(bentLane(bend), t, "linear")).toBeCloseTo(v, 2);}});- it("stays inside the range the model will accept", () => {- // Anything outside ±1 is clamped on parse, so a drag past the limit has to- // saturate rather than round-trip to something else.- const curve = curveForDrag({ range: VOLUME_RANGE, a, b, t: 0.05, v: 0.02 });- expect(curve).not.toBeNull();- expect(Math.abs(curve ?? 0)).toBeLessThanOrEqual(1);- expect(applyCurve(0.5, curve ?? 0)).toBeGreaterThan(0);+ it("follows the pointer into the corner of a segment, as deep as it is dragged", () => {+ // The extreme: 10% along, pulled almost to the floor of a falling ramp. The old+ // exponent saturated a third of the segment away from the pointer, and a later+ // slope cap stopped following it too. Reached exactly now, and the shape it draws+ // stays one smooth arc — checked by sampling it, not by trusting it.+ const bend = curveForDrag({ range: VOLUME_RANGE, a, b, t: 0.4, v: 0.05 });+ expect(bend).not.toBeNull();+ const drawn = bentLane(bend);+ expect(sampleAutomationLane(drawn, 0.4, "linear")).toBeCloseTo(0.05, 2);++ let previous: number | null = null;+ let worst = 1;+ for (let i = 1; i < 60; i += 1) {+ const t = (4 * i) / 60;+ const h = 0.01;+ const slope =+ (sampleAutomationLane(drawn, t + h, "linear") -+ sampleAutomationLane(drawn, t - h, "linear")) /+ (2 * h);+ if (previous !== null && Math.abs(previous) > 1e-6) {+ const ratio = Math.abs(slope) > Math.abs(previous) ? slope / previous : previous / slope;+ worst = Math.max(worst, Math.abs(ratio));+ }+ previous = slope;+ }+ // Gradual: a crease would show up here as a step change in slope.+ expect(worst).toBeLessThan(3);+ });++ it("biases the bend toward whichever point the pointer is nearer", () => {+ // The behaviour a single exponent could not give: grabbing the line near the+ // right-hand point has to bulge it on the RIGHT. Measured as where the curve+ // deviates furthest from the straight line it replaced.+ const apexOf = (bend: { viaX: number; viaY: number } | null): number => {+ const lane = bentLane(bend);+ let best = 0;+ let at = 0;+ for (let i = 1; i < 40; i++) {+ const t = (4 * i) / 40;+ const straight = 1 - t / 4;+ const gap = Math.abs(sampleAutomationLane(lane, t, "linear") - straight);+ if (gap > best) {+ best = gap;+ at = t;+ }+ }+ return at;+ };+ const nearA = curveForDrag({ range: VOLUME_RANGE, a, b, t: 0.6, v: 0.55 });+ const nearB = curveForDrag({ range: VOLUME_RANGE, a, b, t: 3.4, v: 0.45 });+ expect(apexOf(nearA)).toBeLessThan(1.6);+ expect(apexOf(nearB)).toBeGreaterThan(2.4);+ // And the two sit on opposite sides of centre, which is the whole complaint:+ // every bend used to land on the same side whatever the pointer did.+ expect(apexOf(nearA)).toBeLessThan(apexOf(nearB));+ });++ it("stays inside the normalised segment the model will accept", () => {+ // Both coordinates are clamped clear of the ends on parse, so a drag right up+ // against a breakpoint has to describe an interior point, not the breakpoint.+ const bend = curveForDrag({ range: VOLUME_RANGE, a, b, t: 0.05, v: 0.02 });+ expect(bend).not.toBeNull();+ expect(bend?.viaX).toBeGreaterThan(0);+ expect(bend?.viaX).toBeLessThan(1);+ expect(bend?.viaY).toBeGreaterThan(0);+ expect(bend?.viaY).toBeLessThan(1);+ expect(applyCurve(0.5, 0)).toBe(0.5);});it("declines a segment with no room to bend", () => {diff --git a/packages/studio/src/player/components/automationLaneGeometry.ts b/packages/studio/src/player/components/automationLaneGeometry.tsindex a0da602c82..ef9966f2b9 100644--- a/packages/studio/src/player/components/automationLaneGeometry.ts+++ b/packages/studio/src/player/components/automationLaneGeometry.ts@@ -11,6 +11,7 @@ import {fxAutomationTarget,resolveAutomationRange,sampleAutomationLane,+ steadyViaPoint,VOLUME_RANGE,VOLUME_TARGET,type AutomationRange,@@ -21,6 +22,17 @@ import { getAudioFxDef, type HfAudioFxChain } from "@hyperframes/core/audio-fx";/** Points nearer than this in clip seconds are the same point, not two. */export const POINT_MERGE_SEC = 0.02;++/**+ * Closest two breakpoints may sit in clip seconds while still being two points.+ *+ * A drag clamps to this short of its neighbour rather than onto it. Landing on the+ * exact same time is not a step, it is a deletion: the lane's own normalisation+ * collapses points that share a `t`, keeping the later one — so dragging a point+ * fully into its neighbour used to consume that neighbour. A millisecond is under a+ * pixel at any zoom the lane offers, so the two still read as touching.+ */+export const MIN_POINT_GAP_SEC = 0.001;/** Hit radius for grabbing a point, in px. */export const GRAB_PX = 7;/** Samples used to draw a segment the eye should see as curved. */@@ -98,16 +110,21 @@ export function formatValue(range: AutomationRange, value: number): string {}/**- * The `curve` that bends a segment through a dragged point.+ * The via point that bends a segment through a dragged pointer: the pointer's own+ * position in the segment's normalised space, which is all the model needs.*- * `applyCurve` raises normalised progress to `2^(2*curve)`, so a point the- * pointer holds at progress `x` and unit height `f` fixes the exponent:- * `x^e = f`, hence `e = ln f / ln x` and `curve = log2(e) / 2`. Solving rather- * than accumulating a delta means the segment passes through the pointer- * instead of drifting away from it over a long drag.+ * There is nothing to solve any more, and that is the point. This used to fit an+ * exponent — `x^e = f`, so `curve = log2(ln f / ln x) / 2` — and an exponent is+ * one knob for two questions. It spent it on the wrong one: every upward bend it+ * could draw deviated most inside the first fifth of the segment, so grabbing the+ * line near its right-hand breakpoint still bulged it on the left. And reaching a+ * pointer near either end needed an exponent the model refuses — `e` runs past 15+ * at `x = 0.9`, clamped to 4 — so the line stopped following the pointer+ * altogether, missing it by up to a third of the segment's height. Naming the+ * point the curve passes through says both things at once, exactly, anywhere.*- * Null when the segment cannot express the shape: a flat segment has no room to- * bend, and progress or height at the very ends divides by zero.+ * Null when the segment cannot take a bend: a flat segment draws the same line+ * whatever the shape, and a pointer at the very ends is the ends.*/export function curveForDrag(input: {range: AutomationRange;@@ -115,7 +132,7 @@ export function curveForDrag(input: {b: { t: number; v: number };t: number;v: number;-}): number | null {+}): { viaX: number; viaY: number } | null {const { range, a, b, t, v } = input;const span = b.t - a.t;if (span <= 0) return null;@@ -126,7 +143,11 @@ export function curveForDrag(input: {if (Math.abs(ub - ua) < 0.001) return null;const f = (toUnit(range, v) - ua) / (ub - ua);if (f <= 0.001 || f >= 0.999) return null;- return Math.max(-1, Math.min(1, Math.log2(Math.log(f) / Math.log(x)) / 2));+ // Reported as the model will honour it, not as the pointer asked. A bend is held+ // to a steady curve, so a pointer dragged past that stops being followed — and+ // the write, the preview and the readout all have to say the same thing about+ // where the line actually went.+ return steadyViaPoint(x, f);}/**@@ -137,6 +158,32 @@ export function curveForDrag(input: {* Which axis "won" is decided in pixels, not in seconds and dB — those are* different units and comparing them would make the lock depend on the zoom.*/+/** Which way a gesture is going, in pixels — the only comparable unit. */+export function dominantDragAxis(input: {+ origin: { t: number; v: number };+ raw: { t: number; v: number };+ xOf(t: number): number;+ yOf(v: number): number;+}): "time" | "value" {+ const { origin, raw, xOf, yOf } = input;+ return Math.abs(xOf(raw.t) - xOf(origin.t)) > Math.abs(yOf(raw.v) - yOf(origin.v))+ ? "time"+ : "value";+}++/**+ * The pointer, constrained to one axis.+ *+ * The axis is handed in rather than worked out here, because it has to be decided+ * once for the gesture and held. Recomputed per event it followed whichever way+ * the last move happened to lean, so a hand drifting sideways during a vertical+ * drag flipped the lock and the point moved in both — which is indistinguishable+ * from no lock at all.+ *+ * Locking to time holds the value exactly. Locking to value holds the time and+ * moves the value at a quarter speed: the same gesture is the fine adjustment,+ * because a fader spanning 60px of lane has no other way to be set precisely.+ */export function applyShiftConstraint(input: {range: AutomationRange;origin: { t: number; v: number };@@ -144,11 +191,12 @@ export function applyShiftConstraint(input: {/** Same projections the lane draws with, so the comparison is on screen. */xOf(t: number): number;yOf(v: number): number;+ /** Decided on the gesture's first travel; worked out here when absent. */+ axis?: "time" | "value";}): { t: number; v: number } {- const { range, origin, raw, xOf, yOf } = input;- if (Math.abs(xOf(raw.t) - xOf(origin.t)) > Math.abs(yOf(raw.v) - yOf(origin.v))) {- return { t: raw.t, v: origin.v };- }+ const { range, origin, raw } = input;+ const axis = input.axis ?? dominantDragAxis(input);+ if (axis === "time") return { t: raw.t, v: origin.v };const from = toUnit(range, origin.v);return { t: origin.t, v: fromUnit(range, from + (toUnit(range, raw.v) - from) * 0.25) };}@@ -202,7 +250,9 @@ export function envelopePath(input: {const a = lane.points[i];const b = lane.points[i + 1];if (!a || !b) continue;- if (!a.curve && range.scale === "linear") {+ // A via point bends the segment with no `curve` of its own, so the+ // straight-line shortcut has to rule out both.+ if (!a.curve && a.viaX === undefined && range.scale === "linear") {pts.push(`L ${xOf(b.t)} ${yOf(b.v)}`);continue;}diff --git a/packages/studio/src/player/components/automationLaneHeight.ts b/packages/studio/src/player/components/automationLaneHeight.tsindex 3ad43c4282..b657ee5f76 100644--- a/packages/studio/src/player/components/automationLaneHeight.ts+++ b/packages/studio/src/player/components/automationLaneHeight.ts@@ -6,6 +6,10 @@* component's constant living somewhere it is not used.** Taller than a keyframe lane because it carries a value axis rather than a row- * of diamonds: a fader envelope drawn 28px high cannot be aimed.+ * of diamonds: a fader envelope drawn 28px high cannot be aimed. 48 was still+ * too tight in use — the drawing area is the height minus 6px of padding either+ * side, so 48 left 36px for the whole 0..1 fader and a breakpoint's 11px grab+ * disc covered a third of the axis. 72 leaves 60px, which is what makes a value+ * aimable and two points at similar values separately grabbable.*/-export const AUTOMATION_LANE_H = 48;+export const AUTOMATION_LANE_H = 72;diff --git a/packages/studio/src/player/components/automationLaneSelection.ts b/packages/studio/src/player/components/automationLaneSelection.tsindex 66e384e6f1..f5939dd7d8 100644--- a/packages/studio/src/player/components/automationLaneSelection.ts+++ b/packages/studio/src/player/components/automationLaneSelection.ts@@ -2,7 +2,7 @@* Range operations over one automation lane.** `replaceRange` is the only mutator every range feature (delete, shapes,- * paste, stretch) composes, and it carries the invariant that makes them safe:+ * paste) composes, and it carries the invariant that makes them safe:* the envelope OUTSIDE the selection never moves. It samples the lane at both* edges first and pins anchor points there, so cutting the middle out of a* ramp cannot reshape the rest of the clip.@@ -76,6 +76,24 @@ export function replaceRange(input: {return [...outside, ...edges, ...cappedInner].sort((a, b) => a.t - b.t);}+/**+ * Whether a breakpoint falls inside the selection box, edges included.+ *+ * The one rule three places need: what Delete removes, what the lane rings, and+ * what a group drag moves. They have to agree — a point drawn as caught but left+ * behind by the drag is worse than either answer.+ *+ * Both axes, which is what makes a selection a box: a point at the right time but+ * the wrong value is not in it. Values compare in the parameter's own units, and+ * that is correct on a logarithmic axis too — the mapping to screen is monotonic,+ * so a box drawn around some pixels holds exactly the values it looks like it does.+ */+export function pointInSelection(+ point: { t: number; v: number },+ box: { t0: number; t1: number; v0: number; v1: number },+): boolean {+ return point.t >= box.t0 && point.t <= box.t1 && point.v >= box.v0 && point.v <= box.v1;+}/*** Retime a selection: interior points scale proportionally into the new span,* then replaceRange runs over the UNION of old and new spans — growing eatsdiff --git a/packages/studio/src/player/components/useAutomationEdgeStretch.ts b/packages/studio/src/player/components/useAutomationEdgeStretch.tsindex faae242e46..ed7b2fd49f 100644--- a/packages/studio/src/player/components/useAutomationEdgeStretch.ts+++ b/packages/studio/src/player/components/useAutomationEdgeStretch.ts@@ -56,8 +56,11 @@ export interface UseAutomationEdgeStretchInput {duration: number;readOnly?: boolean | undefined;/** Active selection on this lane, so its edges have something to grab. */- rangeSelection?: { t0: number; t1: number } | null | undefined;- onRangeSelect?: ((t0: number, t1: number) => void) | undefined;+ rangeSelection?: { t0: number; t1: number; v0: number; v1: number } | null | undefined;+ /** Whether the pointer is over a point the current selection contains. Such a+ * press is a group drag, not a stretch — see `arm`. */+ pointInSelectionAt?: ((clientX: number, clientY: number) => boolean) | undefined;+ onRangeSelect?: ((t0: number, t1: number, v0: number, v1: number) => void) | undefined;onRangeClear?: (() => void) | undefined;/** Value readout owned by the lane's gesture hook. */onHint(text: string | null): void;@@ -89,7 +92,7 @@ export interface UseAutomationEdgeStretchResult {export function clampEdge(edge: "t0" | "t1",raw: number,- origin: { t0: number; t1: number },+ origin: { t0: number; t1: number; v0: number; v1: number },duration: number,): number {if (edge === "t0") {@@ -108,6 +111,7 @@ export function useAutomationEdgeStretch({duration,readOnly,rangeSelection,+ pointInSelectionAt,onRangeSelect,onRangeClear,onHint,@@ -117,7 +121,7 @@ export function useAutomationEdgeStretch({* points as they stood at arm time. */const [drag, setDrag] = useState<{edge: "t0" | "t1";- origin: { t0: number; t1: number };+ origin: { t0: number; t1: number; v0: number; v1: number };current: number;points: HfAutomationPoint[];} | null>(null);@@ -158,6 +162,18 @@ export function useAutomationEdgeStretch({if (readOnly || !rangeSelection) return false;const edge = edgeAt(e.clientX);if (!edge) return false;+ // Selected CONTENT outranks the edge it sits on.+ //+ // #3207 had the opposite rule, and it was right for a time-only selection:+ // every range operation leaves a breakpoint exactly on the edge it created,+ // so a point-first rule made the second stretch of an edge resolve to a+ // point-drag. A box selection changes the question — a point on the edge is+ // now visibly INSIDE the selection, with the value axis saying so, and+ // dragging selected content has to move it or the box means nothing.+ //+ // So the edge still stretches everywhere it is not also selected content,+ // which is most of its length.+ if (pointInSelectionAt?.(e.clientX, e.clientY)) return false;e.preventDefault();capturePointer(e);setHover(false);@@ -170,7 +186,7 @@ export function useAutomationEdgeStretch({});return true;},- [readOnly, rangeSelection, edgeAt, lane],+ [readOnly, rangeSelection, edgeAt, lane, pointInSelectionAt],);/** Preview the stretch: the partner edge stays put as the retime's anchor, and@@ -190,7 +206,7 @@ export function useAutomationEdgeStretch({const newT0 = edge === "t0" ? current : origin.t0;const newT1 = edge === "t1" ? current : origin.t1;onHint(`${newT0.toFixed(2)}s → ${newT1.toFixed(2)}s`);- onRangeSelect?.(newT0, newT1);+ onRangeSelect?.(newT0, newT1, origin.v0, origin.v1);commitPoints(retimeRange({lane: { target: lane.target, points },@@ -221,7 +237,12 @@ export function useAutomationEdgeStretch({}crossed.current = false;commitPoints(lane.points, true);- onRangeSelect?.(edge === "t0" ? current : origin.t0, edge === "t1" ? current : origin.t1);+ onRangeSelect?.(+ edge === "t0" ? current : origin.t0,+ edge === "t1" ? current : origin.t1,+ origin.v0,+ origin.v1,+ );}, [drag, onHint, onRangeClear, commitPoints, lane, onRangeSelect]);const cancel = useCallback((): void => {@@ -234,7 +255,7 @@ export function useAutomationEdgeStretch({// A live write is a preview, so putting the snapshot back through the same// channel is the whole revert — there is nothing persisted to undo.commitPoints(points, false);- onRangeSelect?.(origin.t0, origin.t1);+ onRangeSelect?.(origin.t0, origin.t1, origin.v0, origin.v1);}, [drag, onHint, commitPoints, onRangeSelect]);const updateHover = useCallback(diff --git a/packages/studio/src/player/components/useAutomationLaneGestures.ts b/packages/studio/src/player/components/useAutomationLaneGestures.tsindex 73f1a23553..de166cf5e9 100644--- a/packages/studio/src/player/components/useAutomationLaneGestures.ts+++ b/packages/studio/src/player/components/useAutomationLaneGestures.ts@@ -4,7 +4,7 @@* Its own hook because the lane component sits at the studio's file ceiling and* because these are the parts worth testing on their own: which of a press,* a drag and a modifier resolves to moving a point, bending a segment,- * stretching a selection's edge, or nothing at all.+ * drawing a selection box, or nothing at all.** Modifiers follow Ableton's, since that is the muscle memory an automation lane* inherits: Shift locks a drag to one axis and fines the value down, Alt over a@@ -13,20 +13,21 @@import { useCallback, useRef, useState, type PointerEvent as ReactPointerEvent } from "react";import type { AutomationRange, HfAutomationLane } from "@hyperframes/core/audio-automation";-import {- applyShiftConstraint,- curveForDrag,- formatValue,- GRAB_PX,- POINT_MERGE_SEC,- snapLaneTime,-} from "./automationLaneGeometry";+import { curveForDrag, formatValue, GRAB_PX, POINT_MERGE_SEC } from "./automationLaneGeometry";+import { pointInSelection } from "./automationLaneSelection";import { capturePointer } from "./automationLanePointer";import { useAutomationEdgeStretch } from "./useAutomationEdgeStretch";+import { useAutomationRangeDrag } from "./useAutomationRangeDrag";+import {+ armGroupDrag,+ computeGroupMove,+ computeSinglePointMove,+ type GroupDragSnapshot,+ type ShiftAxis,+} from "./automationLaneDragMath";-/** Snap radius in clip seconds. Tight on purpose: a lane is often a few seconds- * wide, where a generous radius makes a point unplaceable between two beats. */-const SNAP_SEC = 0.04;+/** How far a press may travel and still count as a click rather than a drag. */+const CLICK_SLOP_PX = 3;/** A point's position, or the origin when the index no longer resolves. */function originOf(point: HfAutomationLane["points"][number] | undefined): { t: number; v: number } {@@ -49,12 +50,12 @@ export interface UseAutomationLaneGesturesInput {snapTimes?: readonly number[] | undefined;readOnly?: boolean | undefined;onSelect?: (() => void) | undefined;- /** Live range-select callbacks; absent = background drags do nothing (read-only lanes). */- onRangeSelect?: ((t0: number, t1: number) => void) | undefined;+ /** Live box-select callbacks; absent = background drags do nothing (read-only lanes). */+ onRangeSelect?: ((t0: number, t1: number, v0: number, v1: number) => void) | undefined;onRangeClear?: (() => void) | undefined;- duration: number; // clamp bound for range endpoints- /** Active selection on this lane, so its edges have something to grab. */- rangeSelection?: { t0: number; t1: number } | null | undefined;+ duration: number; // clamp bound for box endpoints+ /** Active selection box on this lane, so a press inside it can drag its points. */+ rangeSelection?: { t0: number; t1: number; v0: number; v1: number } | null | undefined;}export interface UseAutomationLaneGesturesResult {@@ -62,21 +63,20 @@ export interface UseAutomationLaneGesturesResult {dragIndex: number | null;/** Segment being bent, identified by the point that owns its curve. */curveIndex: number | null;- /** Edge being stretched, for the cursor. */- edgeDrag: "t0" | "t1" | null;- /** Whether the pointer sits over a stretch handle with no gesture live —- * the col-resize cursor hint before a press commits to the drag. */- edgeHover: boolean;/** Value readout to show while a gesture is live. */hint: string | null;hitIndex(clientX: number, clientY: number): number | null;segmentIndex(clientX: number, clientY: number): number | null;onPointerDown(e: ReactPointerEvent<SVGSVGElement>): void;onPointerMove(e: ReactPointerEvent<SVGSVGElement>): void;- endDrag(e: ReactPointerEvent<SVGSVGElement>): void;- /** The browser took the gesture away (`pointercancel`): a stretch reverts- * rather than persisting whatever partial retime it had reached. */+ /** Edge being stretched, for the cursor. Null when no stretch is live. */+ edgeDrag: "t0" | "t1" | null;+ /** Pointer resting over a stretch handle with nothing armed, so the cursor+ * can advertise the gesture before it starts. */+ edgeHover: boolean;+ /** `pointercancel`: a live stretch reverts; anything else ends normally. */cancelDrag(e: ReactPointerEvent<SVGSVGElement>): void;+ endDrag(e: ReactPointerEvent<SVGSVGElement>): void;/** Adds a point, opens the value field on one, or straightens a segment. */onDoubleClick(e: ReactPointerEvent<SVGSVGElement>): void;/** The point whose value is being typed, and the text so far. */@@ -105,16 +105,19 @@ export function useAutomationLaneGestures({const [dragIndex, setDragIndex] = useState<number | null>(null);const [curveIndex, setCurveIndex] = useState<number | null>(null);const [hint, setHint] = useState<string | null>(null);- /** Where a point drag began, so Shift can lock an axis and fine the value. */- const dragOrigin = useRef<{ t: number; v: number } | null>(null);- /** Point whose value is being typed, and the text so far. */- const [editing, setEditing] = useState<{ index: number; text: string } | null>(null);- /** A background drag in progress: its start and live end, in clip seconds. */- const [rangeDrag, setRangeDrag] = useState<{ from: number; to: number } | null>(null);- /** Whether the live drag has crossed the pixel threshold that turns a press- * into an actual range, rather than a click that should just clear one. */- const rangeCrossed = useRef(false);+ /**+ * Stretching a selection by one of its time edges (#3207).+ *+ * Kept as its own module rather than inlined: it is a fifth mutually-exclusive+ * gesture on a hook already at the file's complexity budget, and it owns a+ * snapshot the other gestures have no use for — `retimeRange` scales against+ * the bounds captured when the drag armed, so running it against the live+ * draft would compound the scale factor on every pointermove.+ *+ * Only the time edges stretch. The value extent rides through untouched, which+ * is what keeps this the same gesture it was before the selection became a box.+ */const stretch = useAutomationEdgeStretch({getBox,lane,@@ -125,10 +128,74 @@ export function useAutomationLaneGestures({duration,readOnly,rangeSelection,+ // The stretch stands down on a press that lands on selected content — that+ // gesture belongs to the group drag below.+ pointInSelectionAt: (clientX, clientY) => {+ if (!rangeSelection) return false;+ const i = hitIndex(clientX, clientY);+ const p = i === null ? null : lane.points[i];+ return p ? pointInSelection(p, rangeSelection) : false;+ },onRangeSelect,onRangeClear,onHint: setHint,});+ /** Where a point drag began, so Shift can lock an axis and fine the value. */+ const dragOrigin = useRef<{ t: number; v: number } | null>(null);+ /**+ * The set a group drag moves, snapshotted on the press.+ *+ * Snapshotted rather than recomputed per move for two reasons: every point is+ * moving, so "which ones are selected" has to mean what it meant when the+ * gesture started, and the deltas have to accumulate from the original+ * positions or a rounded move would drift on every pointermove.+ */+ const groupDrag = useRef<GroupDragSnapshot | null>(null);+ /** Point whose value is being typed, and the text so far. */+ const [editing, setEditing] = useState<{ index: number; text: string } | null>(null);+ const rangeDrag = useAutomationRangeDrag({+ pointAt,+ xOf,+ yOf,+ duration,+ snapTimes,+ onRangeSelect,+ onRangeClear,+ });+ /** Where a press on a point landed, and whether it has travelled since. A press+ * that goes nowhere is a click, which is a different gesture from a drag even+ * though both start the same way — see the Shift branch in `endDrag`. */+ const pressAt = useRef<{ x: number; y: number } | null>(null);+ const pressTravelled = useRef(false);+ /**+ * The axis Shift locked, decided on the gesture's first travel and held until+ * the drag ends or Shift is let go. Deciding per event followed whichever way+ * the last move leaned, so a drifting hand unlocked the axis mid-drag.+ */+ const shiftAxis = useRef<ShiftAxis>(null);++ // The value field's own handlers, above the gestures that close it: a press on the+ // lane applies whatever was typed, so onPointerDown lists commitEdit as a+ // dependency and cannot be declared before it.+ const setEditingText = useCallback((text: string): void => {+ setEditing((current) => (current ? { index: current.index, text } : null));+ }, []);++ const cancelEdit = useCallback((): void => setEditing(null), []);++ /** Apply a typed value, or drop the edit when it is not a number. */+ const commitEdit = useCallback((): void => {+ const active = editing;+ setEditing(null);+ if (!active) return;+ const typed = Number(active.text);+ if (!Number.isFinite(typed)) return;+ const clamped = Math.min(range.max, Math.max(range.min, typed));+ commitPoints(+ lane.points.map((p, i) => (i === active.index ? { ...p, v: clamped } : p)),+ true,+ );+ }, [editing, lane, range, commitPoints]);/** Index of a point under the pointer, or null. */const hitIndex = useCallback(@@ -172,25 +239,6 @@ export function useAutomationLaneGestures({[hitIndex, segmentIndex],);- /**- * What a press on the lane's empty background arms: a new range selection,- * and only when a caller wants to hear about one — a read-only lane never- * reaches here at all.- */- const armRangeDrag = useCallback(- (e: ReactPointerEvent<SVGSVGElement>): void => {- if (!onRangeSelect) return;- e.preventDefault();- capturePointer(e);- const raw = pointAt(e.clientX, e.clientY).t;- const clamped = Math.min(duration, Math.max(0, raw));- const t = e.altKey ? clamped : snapLaneTime(clamped, snapTimes ?? [], SNAP_SEC);- rangeCrossed.current = false;- setRangeDrag({ from: t, to: t });- },- [onRangeSelect, pointAt, duration, snapTimes],- );-const onPointerDown = useCallback((e: ReactPointerEvent<SVGSVGElement>): void => {if (e.button !== 0) return;@@ -198,21 +246,30 @@ export function useAutomationLaneGestures({// timeline's own gesture (scrub / marquee / clip drag), which then eats the// rest of the sequence — including the second half of a double-click.e.stopPropagation();+ // A press anywhere on the lane closes the value field, applying what was+ // typed — the same thing Enter and a blur do. It cannot rely on the blur: the+ // gesture branches below call preventDefault to keep the timeline from+ // scrubbing, and that suppresses the focus change the blur would come from,+ // so the field sat open until Enter however far away the next click landed.+ if (editing) commitEdit();if (readOnly) {// The lane sits below the clip bar, so the timeline's selection handler- // never sees this press; selecting here is the only way in.+ // never sees this press; selecting here is the only way in. The press then+ // goes on to arm a range drag rather than being spent on the selection: a+ // press that only selected made the first drag over any lane do nothing+ // visible, so a range took two gestures and looked broken on the first.onSelect?.();+ rangeDrag.arm(e);return;}// An active selection's edge outranks a point sitting on it. Every range- // operation — stretch, delete, shape insert — leaves a breakpoint exactly- // on the edge it just created, so a point-first rule meant the second- // stretch of the same edge resolved to a point-drag and the feature was- // not repeatable. Clear the selection to reach that point again.+ // operation leaves a breakpoint exactly on the edge it just created, so a+ // point-first rule made the second stretch of the same edge resolve to a+ // point-drag — which is how the feature silently stopped working.if (stretch.arm(e)) return;const gesture = gestureAt(e);if (!gesture) {- armRangeDrag(e);+ rangeDrag.arm(e);return;}e.preventDefault();@@ -222,9 +279,27 @@ export function useAutomationLaneGestures({return;}dragOrigin.current = originOf(lane.points[gesture.index]);+ // Pressing one of a selected set drags the whole set. Pressing a point+ // outside the selection is an ordinary single-point drag, selection or no.+ groupDrag.current = armGroupDrag(lane, lane.points[gesture.index], rangeSelection);+ pressAt.current = { x: e.clientX, y: e.clientY };+ pressTravelled.current = false;setDragIndex(gesture.index);},- [gestureAt, lane, readOnly, onSelect, armRangeDrag, stretch],+ [+ gestureAt,+ lane,+ readOnly,+ onSelect,+ rangeDrag,+ editing,+ commitEdit,+ // The press decides whether it starts a group drag, so it has to see the+ // selection as it is now — captured stale, a point pressed straight after+ // selecting a range read the previous selection, or none.+ rangeSelection,+ stretch,+ ],);/** Bend the segment under the pointer, which is what Alt-dragging the line does. */@@ -235,74 +310,103 @@ export function useAutomationLaneGestures({const b = lane.points[curveIndex + 1];if (!a || !b) return;const { t, v } = pointAt(clientX, clientY);- const curve = curveForDrag({ range, a, b, t, v });- if (curve === null) return;- setHint(`curve ${curve.toFixed(2)}`);+ const bend = curveForDrag({ range, a, b, t, v });+ if (bend === null) return;+ // Read out where the bend now sits along the segment, which is what the+ // pointer is choosing: a percentage means more here than a curve exponent+ // the author never types.+ setHint(`bend ${Math.round(bend.viaX * 100)}%`);commitPoints(- lane.points.map((p, i) => (i === curveIndex ? { ...p, curve } : p)),+ // `curve` is dropped rather than carried: the via point supersedes it, and+ // leaving a stale exponent behind would make the segment's shape depend on+ // which of the two the reader happened to honour.+ lane.points.map((p, i) =>+ i === curveIndex ? { ...p, curve: undefined, viaX: bend.viaX, viaY: bend.viaY } : p,+ ),false,);},[curveIndex, lane, pointAt, range, commitPoints],);+ /**+ * Move a selected set by one delta, taken from the point under the pointer.+ *+ * The whole group has to stop when its first member reaches a boundary, not+ * each point on its own: clamping individually squashes the shape flat against+ * the edge, and the gesture is meant to preserve it. Deltas are in the+ * parameter's own units, so on a logarithmic axis a group moves by Hz rather+ * than by octaves — the same as dragging one point does.+ */+ const moveGroup = useCallback(+ (e: ReactPointerEvent<SVGSVGElement>, group: GroupDragSnapshot): void => {+ const { points, selection, hint } = computeGroupMove({+ group,+ raw: pointAt(e.clientX, e.clientY),+ shiftKey: e.shiftKey,+ altKey: e.altKey,+ range,+ duration,+ snapTimes,+ xOf,+ yOf,+ });+ onRangeSelect?.(selection.t0, selection.t1, selection.v0, selection.v1);+ setHint(hint);+ commitPoints(points, false);+ },+ [commitPoints, duration, onRangeSelect, pointAt, range, snapTimes, xOf, yOf],+ );+/** Move the point being dragged, honouring the modifiers held with it. */const movePoint = useCallback((e: ReactPointerEvent<SVGSVGElement>): void => {if (dragIndex === null) return;- const raw = pointAt(e.clientX, e.clientY);- const origin = dragOrigin.current;- let { t, v } =- e.shiftKey && origin ? applyShiftConstraint({ range, origin, raw, xOf, yOf }) : raw;- // Shift is a deliberate free-hand move as much as Alt is, so neither snaps.- if (!e.altKey && !e.shiftKey) {- const neighbours = lane.points.filter((_, i) => i !== dragIndex).map((p) => p.t);- t = snapLaneTime(t, [...(snapTimes ?? []), ...neighbours], SNAP_SEC);+ const group = groupDrag.current;+ if (group) {+ moveGroup(e, group);+ return;}+ if (!e.shiftKey) shiftAxis.current = null;+ const {+ t,+ v,+ shiftAxis: nextAxis,+ } = computeSinglePointMove({+ raw: pointAt(e.clientX, e.clientY),+ origin: dragOrigin.current,+ shiftKey: e.shiftKey,+ altKey: e.altKey,+ shiftAxis: shiftAxis.current,+ range,+ duration,+ snapTimes,+ lane,+ dragIndex,+ xOf,+ yOf,+ });+ shiftAxis.current = nextAxis;const next = lane.points.map((p, i) => (i === dragIndex ? { ...p, t, v } : p));- // Re-sort so dragging a point past a neighbour behaves, and keep the- // dragged one addressable by following where it landed.- const moved = next[dragIndex];- next.sort((a, b) => a.t - b.t);- if (moved) setDragIndex(next.indexOf(moved));setHint(`${formatValue(range, v)} @ ${t.toFixed(2)}s`);commitPoints(next, false);},- [dragIndex, lane, pointAt, range, commitPoints, snapTimes, xOf, yOf],- );-- /** Update the live range-drag as the pointer moves, firing `onRangeSelect`- * once it has covered enough pixels to count as an actual range rather- * than a click that should just clear one. */- const moveRangeDrag = useCallback(- (e: ReactPointerEvent<SVGSVGElement>): void => {- if (rangeDrag === null) return;- const raw = pointAt(e.clientX, e.clientY).t;- const clamped = Math.min(duration, Math.max(0, raw));- const t = e.altKey ? clamped : snapLaneTime(clamped, snapTimes ?? [], SNAP_SEC);- setRangeDrag({ from: rangeDrag.from, to: t });- if (Math.abs(xOf(t) - xOf(rangeDrag.from)) <= 3) return;- rangeCrossed.current = true;- onRangeSelect?.(Math.min(rangeDrag.from, t), Math.max(rangeDrag.from, t));- },- [rangeDrag, pointAt, duration, snapTimes, xOf, onRangeSelect],+ [dragIndex, duration, lane, pointAt, range, commitPoints, snapTimes, xOf, yOf, moveGroup],);const onPointerMove = useCallback((e: ReactPointerEvent<SVGSVGElement>): void => {if (stretch.edge !== null) {e.stopPropagation();- // A capture lost without a `pointercancel` — the child it was taken on- // unmounted, or the browser handed the gesture elsewhere — leaves no- // gesture-end event at all, and every later hover would keep retiming.- // A move with no button held is the only signal left that it is over.+ // A button-less move means the browser handed the gesture back without a+ // pointerup — revert rather than leaving a half-applied retime.if (e.buttons === 0) stretch.cancel();else stretch.move(e);return;}- if (rangeDrag !== null) {+ if (rangeDrag.dragging) {e.stopPropagation();- moveRangeDrag(e);+ rangeDrag.move(e);return;}if (curveIndex === null && dragIndex === null) {@@ -310,20 +414,16 @@ export function useAutomationLaneGestures({return;}e.stopPropagation();+ const from = pressAt.current;+ if (from && Math.hypot(e.clientX - from.x, e.clientY - from.y) > CLICK_SLOP_PX) {+ pressTravelled.current = true;+ }if (curveIndex !== null) bendSegment(e.clientX, e.clientY);else movePoint(e);},- [stretch, rangeDrag, moveRangeDrag, curveIndex, dragIndex, bendSegment, movePoint],+ [rangeDrag, curveIndex, dragIndex, bendSegment, movePoint, stretch],);- /** A sub-threshold press clears the selection rather than leaving a- * zero-width one behind. */- const finishRangeDrag = useCallback((): void => {- if (!rangeCrossed.current) onRangeClear?.();- rangeCrossed.current = false;- setRangeDrag(null);- }, [onRangeClear]);-const endDrag = useCallback((e: ReactPointerEvent<SVGSVGElement>): void => {if (stretch.edge !== null) {@@ -331,25 +431,42 @@ export function useAutomationLaneGestures({stretch.finish();return;}- if (rangeDrag !== null) {+ if (rangeDrag.dragging) {e.stopPropagation();- finishRangeDrag();+ rangeDrag.finish();return;}if (dragIndex === null && curveIndex === null) return;e.stopPropagation();+ const index = dragIndex;+ const shiftClicked = index !== null && e.shiftKey && !pressTravelled.current;setDragIndex(null);setCurveIndex(null);dragOrigin.current = null;+ groupDrag.current = null;+ shiftAxis.current = null;+ pressAt.current = null;setHint(null);+ // Shift+click removes the point. Decided on RELEASE, not on the press: Shift+ // held through a drag is the axis lock, and acting on the press would take+ // that gesture away. A press that never travelled was a click.+ if (shiftClicked) {+ commitPoints(+ lane.points.filter((_, i) => i !== index),+ true,+ );+ return;+ }commitPoints(lane.points, true);},- [stretch, rangeDrag, finishRangeDrag, curveIndex, dragIndex, lane, commitPoints],+ [rangeDrag, curveIndex, dragIndex, lane, commitPoints, stretch],);- /** `pointercancel`: the browser abandoned the gesture, so a stretch reverts- * instead of persisting the partial retime `endDrag` would have committed.- * Anything else ends the way a release ends it. */+ /**+ * `pointercancel`: the browser abandoned the gesture, so a stretch reverts+ * rather than persisting the partial retime `endDrag` would have committed.+ * Anything else ends the way a release ends it.+ */const cancelDrag = useCallback((e: ReactPointerEvent<SVGSVGElement>): void => {if (stretch.edge !== null) {@@ -399,38 +516,18 @@ export function useAutomationLaneGestures({[lane, pointAt, commitPoints, readOnly, hitIndex, segmentIndex],);- const setEditingText = useCallback((text: string): void => {- setEditing((current) => (current ? { index: current.index, text } : null));- }, []);-- const cancelEdit = useCallback((): void => setEditing(null), []);-- /** Apply a typed value, or drop the edit when it is not a number. */- const commitEdit = useCallback((): void => {- const active = editing;- setEditing(null);- if (!active) return;- const typed = Number(active.text);- if (!Number.isFinite(typed)) return;- const clamped = Math.min(range.max, Math.max(range.min, typed));- commitPoints(- lane.points.map((p, i) => (i === active.index ? { ...p, v: clamped } : p)),- true,- );- }, [editing, lane, range, commitPoints]);-return {dragIndex,curveIndex,edgeDrag: stretch.edge,edgeHover: stretch.hover,+ cancelDrag,hint,hitIndex,segmentIndex,onPointerDown,onPointerMove,endDrag,- cancelDrag,onDoubleClick,editing,setEditingText,diff --git a/packages/studio/src/player/components/useAutomationLanes.test.tsx b/packages/studio/src/player/components/useAutomationLanes.test.tsxindex 2003035ea2..17e5cd1322 100644--- a/packages/studio/src/player/components/useAutomationLanes.test.tsx+++ b/packages/studio/src/player/components/useAutomationLanes.test.tsx@@ -78,6 +78,9 @@ describe("useAutomationLanes", () => {});it("gives one lane per automated parameter, in draw order", () => {+ // Draw order is the spectrum: a lane belonging to an effect that sits at a+ // frequency is placed by that frequency, high first, and lanes with none —+ // the track's own volume — follow in written order.const automation = JSON.stringify({version: 1,lanes: [@@ -87,7 +90,7 @@ describe("useAutomationLanes", () => {],});const bound = bindOnce(el({ automation, fxChain: CHAIN }));- expect(bound.lanes.map((l) => l.target)).toEqual(["volume", "fx.n2.frequency", "fx.n2.q"]);+ expect(bound.lanes.map((l) => l.target)).toEqual(["fx.n2.frequency", "fx.n2.q", "volume"]);});it("reads an element with neither attribute as an empty volume lane", () => {diff --git a/packages/studio/src/player/components/useAutomationLanes.ts b/packages/studio/src/player/components/useAutomationLanes.tsindex 1862d4d33c..66242dd747 100644--- a/packages/studio/src/player/components/useAutomationLanes.ts+++ b/packages/studio/src/player/components/useAutomationLanes.ts@@ -10,7 +10,7 @@* read only, which is also what stops a stray drag from editing the wrong track.*/-import { useCallback, useMemo } from "react";+import { useCallback, useMemo, useRef } from "react";import {HF_AUDIO_AUTOMATION_ATTR,serializeAutomation,@@ -27,6 +27,7 @@ import { getTimelineElementIdentity } from "../lib/timelineElementHelpers";import { usePlayerStore, type TimelineElement } from "../store/playerStore";import type { AutomationSelection } from "../store/automationSelectionSlice";import { elementAutomation, elementFxChain } from "./automationLaneData";+import { createAutomationGestureKeys } from "./automationGestureKeys";export interface AutomationLaneBinding {automation: HfAutomation;@@ -54,12 +55,13 @@ export interface AutomationLaneBinding {* element's key; it lags only in the window a non-gesture caller can hit.*/commitTargetKey: string | null;- /** This element's active time selection, or null if none / it belongs to a+ /** This element's active selection box, or null if none / it belongs to a* different element. */selection: AutomationSelection | null;- /** Live write while dragging a range on the given lane; does not persist —- * the selection is ephemeral store state, not part of the composition. */- onRangeSelect(target: string, t0: number, t1: number): void;+ /** Live write while dragging a selection box on the given lane; does not+ * persist — the selection is ephemeral store state, not part of the+ * composition. */+ onRangeSelect(target: string, t0: number, t1: number, v0: number, v1: number): void;onRangeClear(): void;}@@ -68,6 +70,9 @@ export interface UseAutomationLanesResult {}export function useAutomationLanes(): UseAutomationLanesResult {+ // One per hook instance, held across renders: a gesture spans many commits and+ // they all have to record under the same key for undo to take the whole drag.+ const gestureKeys = useRef(createAutomationGestureKeys());// Optional: the player also runs outside Studio, where there is no edit// session. There the lanes render read-only, which is the right fallback.const domEdit = useDomEditActionsContextOptional();@@ -97,14 +102,32 @@ export function useAutomationLanes(): UseAutomationLanesResult {const write = (next: HfAutomation, persist: boolean): void => {if (!domEdit || !isSelected) return;const value = next.lanes.length > 0 ? serializeAutomation(next) : "";+ // Every write of one gesture under one key, so undo takes back the whole+ // drag rather than the last fragment history happened to keep.+ const coalesce = persist ? gestureKeys.current.commit() : gestureKeys.current.live();// Quiet, not the refreshing commit: releasing a dragged point used to// reload the preview, which restarts every playing track — the same chop// the live write during the drag exists to avoid. Quiet still persists// and still resyncs the selection, so the next edit sees this one.- if (persist) void domEdit.handleDomAttributeQuietCommit(HF_AUDIO_AUTOMATION_ATTR, value);+ if (persist) {+ void domEdit.handleDomAttributeQuietCommit(HF_AUDIO_AUTOMATION_ATTR, value, coalesce);+ }// Dragging a point writes live: no preview refresh, so the composition// does not reload and restart playback on every pixel.- else void domEdit.handleDomAttributeLiveCommit(HF_AUDIO_AUTOMATION_ATTR, value || null);+ else {+ // Preview only, because a gesture writes on every pointermove: the+ // preview and the running audio follow the pointer, and the release+ // below is the one write that reaches the file and the undo stack.+ void domEdit.handleDomAttributeLiveCommit(+ HF_AUDIO_AUTOMATION_ATTR,+ value || null,+ undefined,+ {+ coalesce,+ previewOnly: true,+ },+ );+ }};return {@@ -121,9 +144,15 @@ export function useAutomationLanes(): UseAutomationLanesResult {readOnly: !domEdit || !isSelected,commitTargetKey: domEdit ? commitTargetKey : null,selection: automationSelection?.elementKey === elementKey ? automationSelection : null,- onRangeSelect: (target, t0, t1) => {- if (!domEdit || !isSelected) return;- setAutomationSelection({ elementKey, target, t0, t1 });+ // Not gated on `isSelected`, unlike the writes above. A selection is+ // ephemeral store state, and the drag that draws one on a read-only lane is+ // the same press that selects the clip — refusing it here meant the first+ // drag on a lane silently did nothing and the author had to drag again.+ // Nothing can be written through it while the lane is read-only: every+ // consumer resolves the binding again and finds `readOnly`.+ onRangeSelect: (target, t0, t1, v0, v1) => {+ if (!domEdit) return;+ setAutomationSelection({ elementKey, target, t0, t1, v0, v1 });},onRangeClear: () => clearAutomationSelection(),};diff --git a/packages/studio/src/player/components/useAutomationRangeDrag.ts b/packages/studio/src/player/components/useAutomationRangeDrag.tsnew file mode 100644index 0000000000..4429bc32bd--- /dev/null+++ b/packages/studio/src/player/components/useAutomationRangeDrag.ts@@ -0,0 +1,114 @@+/**+ * Drawing a new selection box over an automation lane's empty background.+ *+ * Its own module for the same reason useAutomationEdgeStretch is: a sixth+ * mutually-exclusive gesture on a hook already at the file's complexity+ * budget, and one with no use for anything the others snapshot.+ */++import { useCallback, useRef, useState, type PointerEvent as ReactPointerEvent } from "react";+import { snapLaneTime } from "./automationLaneGeometry";+import { capturePointer } from "./automationLanePointer";+import { SNAP_SEC } from "./automationLaneDragMath";++export interface UseAutomationRangeDragInput {+ pointAt(clientX: number, clientY: number): { t: number; v: number };+ xOf(t: number): number;+ yOf(v: number): number;+ duration: number;+ snapTimes?: readonly number[] | undefined;+ onRangeSelect?: ((t0: number, t1: number, v0: number, v1: number) => void) | undefined;+ onRangeClear?: (() => void) | undefined;+}++export interface UseAutomationRangeDragResult {+ /** Whether a box is being drawn right now. */+ dragging: boolean;+ /** Arms a new box at the press, or declines when no caller wants to hear+ * about one (a read-only lane). */+ arm(e: ReactPointerEvent<SVGSVGElement>): void;+ move(e: ReactPointerEvent<SVGSVGElement>): void;+ /** A sub-threshold press clears the selection rather than leaving a+ * zero-width one behind. */+ finish(): void;+}++/**+ * A corner of the selection box under the pointer.+ *+ * Time is clamped to the clip and snaps to the grid, because the box's span is+ * also what a shape insert or a paste acts over and those want beat-aligned+ * edges. The value is taken as it lies: there is no grid on a parameter axis,+ * and rounding a dB bound would move which points the box catches.+ */+function boxCornerAt(+ e: ReactPointerEvent<SVGSVGElement>,+ input: Pick<UseAutomationRangeDragInput, "pointAt" | "duration" | "snapTimes">,+): { t: number; v: number } {+ const raw = input.pointAt(e.clientX, e.clientY);+ const clamped = Math.min(input.duration, Math.max(0, raw.t));+ return {+ t: e.altKey ? clamped : snapLaneTime(clamped, input.snapTimes ?? [], SNAP_SEC),+ v: raw.v,+ };+}++export function useAutomationRangeDrag({+ pointAt,+ xOf,+ yOf,+ duration,+ snapTimes,+ onRangeSelect,+ onRangeClear,+}: UseAutomationRangeDragInput): UseAutomationRangeDragResult {+ const [box, setBox] = useState<{+ from: { t: number; v: number };+ to: { t: number; v: number };+ } | null>(null);+ /** Whether the live drag has crossed the pixel threshold that turns a press+ * into an actual box, rather than a click that should just clear one. */+ const crossed = useRef(false);++ const arm = useCallback(+ (e: ReactPointerEvent<SVGSVGElement>): void => {+ if (!onRangeSelect) return;+ e.preventDefault();+ capturePointer(e);+ const corner = boxCornerAt(e, { pointAt, duration, snapTimes });+ crossed.current = false;+ setBox({ from: corner, to: corner });+ },+ [onRangeSelect, pointAt, duration, snapTimes],+ );++ const move = useCallback(+ (e: ReactPointerEvent<SVGSVGElement>): void => {+ if (box === null) return;+ const to = boxCornerAt(e, { pointAt, duration, snapTimes });+ const { from } = box;+ setBox({ from, to });+ const travelled = Math.max(+ Math.abs(xOf(to.t) - xOf(from.t)),+ Math.abs(yOf(to.v) - yOf(from.v)),+ );+ if (travelled <= 3) return;+ crossed.current = true;+ onRangeSelect?.(+ Math.min(from.t, to.t),+ Math.max(from.t, to.t),+ Math.min(from.v, to.v),+ Math.max(from.v, to.v),+ );+ },+ [box, pointAt, duration, snapTimes, xOf, yOf, onRangeSelect],+ );++ const finish = useCallback((): void => {+ if (!crossed.current) onRangeClear?.();+ crossed.current = false;+ setBox(null);+ }, [onRangeClear]);++ return { dragging: box !== null, arm, move, finish };+}diff --git a/packages/studio/src/player/lib/automationStoreSync.test.ts b/packages/studio/src/player/lib/automationStoreSync.test.tsnew file mode 100644index 0000000000..78148dbb35--- /dev/null+++ b/packages/studio/src/player/lib/automationStoreSync.test.ts@@ -0,0 +1,83 @@+// @vitest-environment happy-dom+import { beforeEach, describe, expect, it } from "vitest";+import { syncStoredAutomationFromPreview } from "./automationStoreSync";+import { usePlayerStore, type TimelineElement } from "../store/playerStore";++const TWO_POINTS = '{"version":1,"lanes":[{"target":"volume","points":[{"t":0,"v":1}]}]}';+const RESTORED =+ '{"version":1,"lanes":[{"target":"volume","points":[{"t":0,"v":1},{"t":4,"v":0}]}]}';++const el = (over: Partial<TimelineElement> = {}): TimelineElement => ({+ id: "bgm",+ key: "bgm",+ tag: "audio",+ start: 0,+ duration: 10,+ track: 1,+ domId: "bgm",+ ...over,+});++/** A stand-in preview document carrying the attributes an undo would have written. */+function previewWith(attrs: Record<string, string>): Document {+ const doc = document.implementation.createHTMLDocument("preview");+ const audio = doc.createElement("audio");+ audio.id = "bgm";+ for (const [name, value] of Object.entries(attrs)) audio.setAttribute(name, value);+ doc.body.append(audio);+ return doc;+}++beforeEach(() => {+ usePlayerStore.getState().reset();+});++describe("syncStoredAutomationFromPreview", () => {+ it("reads back an envelope an undo restored on the preview", () => {+ // The bug: a soft undo patches the preview document and re-runs the timeline, but+ // the store keeps its own copy of the attributes and that copy is what a lane+ // draws — so an undone delete stayed invisible until the page was reloaded.+ usePlayerStore.setState({ elements: [el({ automation: TWO_POINTS })] });+ syncStoredAutomationFromPreview(previewWith({ "data-automation": RESTORED }));+ expect(usePlayerStore.getState().elements[0]?.automation).toBe(RESTORED);+ });++ it("reads back an undone FX chain too, since a lane's targets come from it", () => {+ const chain = '{"version":1,"nodes":[{"type":"lowpass","id":"n1","params":{}}]}';+ usePlayerStore.setState({ elements: [el()] });+ syncStoredAutomationFromPreview(previewWith({ "data-fx-chain": chain }));+ expect(usePlayerStore.getState().elements[0]?.fxChain).toBe(chain);+ });++ it("clears an attribute the undo removed", () => {+ usePlayerStore.setState({ elements: [el({ automation: TWO_POINTS })] });+ syncStoredAutomationFromPreview(previewWith({}));+ expect(usePlayerStore.getState().elements[0]?.automation).toBeUndefined();+ });++ it("finds the node by data-hf-id when the dom id does not match", () => {+ // Studio stamps hf-ids; an element discovered under a suffixed dom id still has+ // to resolve, or the sync silently skips it.+ const doc = document.implementation.createHTMLDocument("preview");+ const audio = doc.createElement("audio");+ audio.setAttribute("data-hf-id", "hf-snao");+ audio.setAttribute("data-automation", RESTORED);+ doc.body.append(audio);+ usePlayerStore.setState({ elements: [el({ domId: "bgm-2", hfId: "hf-snao" })] });+ syncStoredAutomationFromPreview(doc);+ expect(usePlayerStore.getState().elements[0]?.automation).toBe(RESTORED);+ });++ it("keeps the same array when nothing changed, so nothing re-renders", () => {+ usePlayerStore.setState({ elements: [el({ automation: RESTORED })] });+ const before = usePlayerStore.getState().elements;+ syncStoredAutomationFromPreview(previewWith({ "data-automation": RESTORED }));+ expect(usePlayerStore.getState().elements).toBe(before);+ });++ it("does nothing without a preview document", () => {+ usePlayerStore.setState({ elements: [el({ automation: TWO_POINTS })] });+ syncStoredAutomationFromPreview(null);+ expect(usePlayerStore.getState().elements[0]?.automation).toBe(TWO_POINTS);+ });+});diff --git a/packages/studio/src/player/lib/automationStoreSync.ts b/packages/studio/src/player/lib/automationStoreSync.tsnew file mode 100644index 0000000000..02894699df--- /dev/null+++ b/packages/studio/src/player/lib/automationStoreSync.ts@@ -0,0 +1,56 @@+/**+ * Keeping the player store's automation attributes true.+ *+ * The store is what a lane draws from, and it is populated by element discovery — a+ * message from the preview runtime, which only arrives on load. Anything that edits+ * an envelope afterwards writes to the preview document and the source file, and the+ * store would go on holding the value it was born with until a reload.+ *+ * One reader, called from the two places a change lands: the resync every dom-edit+ * attribute commit already runs, and the soft restore an undo or redo applies. It+ * reads the preview rather than being told, because those callers know a file+ * changed, not which attribute — and because three separate writers shipped without+ * remembering to sync, which is what a single sink prevents.+ */++import { HF_AUDIO_AUTOMATION_ATTR } from "@hyperframes/core/audio-automation";+import { HF_AUDIO_FX_ATTR } from "@hyperframes/core/audio-fx";+import { usePlayerStore, type TimelineElement } from "../store/playerStore";++/** The preview node an element stands for, by dom id and then by `data-hf-id`. */+function previewNodeFor(doc: Document, element: TimelineElement): Element | null {+ const domId = element.domId ?? element.id;+ const byId = domId ? doc.getElementById(domId) : null;+ if (byId) return byId;+ return element.hfId ? doc.querySelector(`[data-hf-id="${element.hfId}"]`) : null;+}++/**+ * Re-read every element's automation and FX-chain attributes from the preview+ * document, for a change that reached the DOM without going through this store.+ *+ * That is undo and redo. A soft restore patches the reverted attributes onto the+ * live preview and re-runs the timeline — deliberately, so the frame does not blank+ * — but the store it does not touch is the one the lanes read, so an undone delete+ * stayed invisible until a reload. A full restore already clears the store and waits+ * for discovery, so it needs nothing from here.+ *+ * Reads rather than being told: an undo restores whole files, so the attribute it+ * reverted is only known by looking.+ */+export function syncStoredAutomationFromPreview(doc: Document | null | undefined): void {+ if (!doc) return;+ usePlayerStore.setState((state) => {+ let changed = false;+ const elements = state.elements.map((element) => {+ const node = previewNodeFor(doc, element);+ if (!node) return element;+ const automation = node.getAttribute(HF_AUDIO_AUTOMATION_ATTR) ?? undefined;+ const fxChain = node.getAttribute(HF_AUDIO_FX_ATTR) ?? undefined;+ if (automation === element.automation && fxChain === element.fxChain) return element;+ changed = true;+ return { ...element, automation, fxChain };+ });+ return changed ? { elements } : {};+ });+}diff --git a/packages/studio/src/player/store/automationSelectionSlice.test.ts b/packages/studio/src/player/store/automationSelectionSlice.test.tsindex cb1af6c155..7229fcf3a9 100644--- a/packages/studio/src/player/store/automationSelectionSlice.test.ts+++ b/packages/studio/src/player/store/automationSelectionSlice.test.ts@@ -2,12 +2,28 @@ import { describe, expect, it } from "vitest";import { usePlayerStore } from "./playerStore";describe("automationSelectionSlice", () => {- it("stores one ordered selection and clears it", () => {+ it("stores one ordered selection box and clears it", () => {const store = usePlayerStore.getState();- store.setAutomationSelection({ elementKey: "bgm", target: "volume", t0: 2, t1: 1 });+ // Dragged up and to the left: both axes arrive backwards.+ store.setAutomationSelection({+ elementKey: "bgm",+ target: "volume",+ t0: 2,+ t1: 1,+ v0: 0.8,+ v1: 0.3,+ });const sel = usePlayerStore.getState().automationSelection;- // Ordered on write, so every consumer can assume t0 < t1.- expect(sel).toEqual({ elementKey: "bgm", target: "volume", t0: 1, t1: 2 });+ // Ordered on write, so every consumer can assume t0 <= t1 and v0 <= v1 —+ // which is what lets a point test be two range checks rather than four.+ expect(sel).toEqual({+ elementKey: "bgm",+ target: "volume",+ t0: 1,+ t1: 2,+ v0: 0.3,+ v1: 0.8,+ });usePlayerStore.getState().clearAutomationSelection();expect(usePlayerStore.getState().automationSelection).toBeNull();});diff --git a/packages/studio/src/player/store/automationSelectionSlice.ts b/packages/studio/src/player/store/automationSelectionSlice.tsindex 8af1440237..d59ca83d20 100644--- a/packages/studio/src/player/store/automationSelectionSlice.ts+++ b/packages/studio/src/player/store/automationSelectionSlice.ts@@ -1,5 +1,5 @@/**- * The active time selection on one automation lane.+ * The active selection box on one automation lane.** A store slice, not lane-local state, for the same reason keyframe selection* is one: Delete/copy/paste handlers and the shape menu live outside the lane@@ -13,9 +13,19 @@ export interface AutomationSelection {elementKey: string;/** Lane target: "volume" or "fx.<nodeId>.<param>". */target: string;- /** Clip-local seconds; always t0 < t1 (ordered on write). */+ /** Clip-local seconds; always t0 <= t1 (ordered on write). */t0: number;t1: number;+ /**+ * The box's value bounds, in the parameter's own units; always v0 <= v1.+ *+ * What makes the selection a box rather than a time span: a point is caught+ * only if it falls inside both axes. Span operations — copy, paste, shape+ * insert, simplify — still read t0/t1 alone, because they act on the envelope+ * over a stretch of time rather than on a set of breakpoints.+ */+ v0: number;+ v1: number;}export interface AutomationSelectionSlice {@@ -31,7 +41,13 @@ export function createAutomationSelectionSlice(automationSelection: null,setAutomationSelection: (sel) =>set({- automationSelection: sel.t0 <= sel.t1 ? sel : { ...sel, t0: sel.t1, t1: sel.t0 },+ automationSelection: {+ ...sel,+ t0: Math.min(sel.t0, sel.t1),+ t1: Math.max(sel.t0, sel.t1),+ v0: Math.min(sel.v0, sel.v1),+ v1: Math.max(sel.v0, sel.v1),+ },}),clearAutomationSelection: () => set({ automationSelection: null }),};