Skip to content

Open source CapCut alternative.

TypeScript

fix(site): harden the cut editor from ultra review findings

David Le5f6a9960c218
diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsx
index 0dec4446..5ff6b018 100644
--- a/site/src/cut/components/AiPanel.tsx
+++ b/site/src/cut/components/AiPanel.tsx
@@ -38,7 +38,7 @@ import { apiFetch, engineReady } from "@/cut/lib/api";
import { buildAiContext } from "@/cut/lib/aiContext";
import { runAiTool } from "@/cut/lib/aiTools";
import { setAssetDragData } from "@/cut/lib/assetDrag";
-import { deleteChatAssets, setActiveChatThread, threadOwnsAssets } from "@/cut/lib/chatAssets";
+import { beginChatTurn, deleteChatAssets, endChatTurn, setActiveChatThread, threadOwnsAssets } from "@/cut/lib/chatAssets";
import {
addRefOnce,
collectRefs,
@@ -446,6 +446,15 @@ function ChatSession({
return () => setActiveChatThread(null);
}, [threadId]);
+ // Pin this thread as the owner while its turn streams. Deliberately no
+ // unmount cleanup: a thread switch mid-turn unmounts this session while the
+ // stream (and its tool calls) keeps running — the pin must outlive the
+ // panel so that work still files under the thread that asked.
+ useEffect(() => {
+ if (busy) beginChatTurn(threadId);
+ else endChatTurn(threadId);
+ }, [busy, threadId]);
+
// Coalesce every edit the assistant makes in one turn into a single undo
// step, so ⌘Z reverts the whole turn rather than one tool call at a time.
useEffect(() => {
diff --git a/site/src/cut/components/AudioPanel.tsx b/site/src/cut/components/AudioPanel.tsx
index 261fede5..c3e6a79b 100644
--- a/site/src/cut/components/AudioPanel.tsx
+++ b/site/src/cut/components/AudioPanel.tsx
@@ -69,12 +69,18 @@ export function AudioPanel({
importing: boolean;
}) {
// The app-wide preview player: starting a clip stops the last one, here or
- // on a chat audio card. Leaving the tab stops whatever is playing.
+ // on a chat audio card. Leaving the tab silences only this panel's own
+ // preview — a chat card's playback belongs to the chat, which is still on
+ // screen.
const playingUrl = usePreviewAudio((s) => s.url);
- const togglePlay = usePreviewAudio((s) => s.toggle);
+ const ownedUrl = useRef<string | null>(null);
+ const togglePlay = (url: string) => {
+ ownedUrl.current = url;
+ usePreviewAudio.getState().toggle(url);
+ };
useEffect(
() => () => {
- usePreviewAudio.getState().stop();
+ if (ownedUrl.current) usePreviewAudio.getState().stop(ownedUrl.current);
},
[]
);
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index 4d011a85..d94e3f1b 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -378,7 +378,9 @@ export async function runAiTool(
const nextIn = isNum(input.in) ? clamp(input.in, 0, dur - 0.1) : clip.in;
const nextOut = isNum(input.out) ? clamp(input.out, 0.1, dur) : clip.out;
if (nextOut - nextIn < 0.1) throw new ToolError("Clip must stay at least 0.1s long.");
- s.updateClip(clip.id, { in: nextIn, out: nextOut });
+ // Trim through the store's resize path so track 0 keeps its no-overlap
+ // invariant: extending a clip pushes the following run right.
+ s.setClipTrim(clip.id, nextIn, nextOut);
return { in: nextIn, out: nextOut, len: Math.round((nextOut - nextIn) * 100) / 100 };
}
diff --git a/site/src/cut/lib/assetRef.ts b/site/src/cut/lib/assetRef.ts
index 343c6312..4fa46297 100644
--- a/site/src/cut/lib/assetRef.ts
+++ b/site/src/cut/lib/assetRef.ts
@@ -80,15 +80,25 @@ export const refFromStockVideo = (v: StockVideo): AssetRef => ({
duration: v.duration,
});
-/** A transient ref for a text file dropped from the desktop: the contents stay
- * behind an object URL and are read at send time. */
-export const refFromTextFile = (file: File): AssetRef => ({
- scope: "file",
- id: crypto.randomUUID().slice(0, 8),
- name: file.name,
- kind: "text",
- url: URL.createObjectURL(file),
-});
+/** A ref for a text file dropped from the desktop: the contents ride inline
+ * as a data: URL. The ref persists into the thread's saved messages, and a
+ * data: URL still reads after a reload — an object URL would die with the
+ * page and leave the attachment permanently unreadable. */
+export async function refFromTextFile(file: File): Promise<AssetRef> {
+ const url = await new Promise<string>((resolve, reject) => {
+ const r = new FileReader();
+ r.onload = () => resolve(String(r.result));
+ r.onerror = () => reject(r.error ?? new Error(`Could not read ${file.name}.`));
+ r.readAsDataURL(file);
+ });
+ return {
+ scope: "file",
+ id: crypto.randomUUID().slice(0, 8),
+ name: file.name,
+ kind: "text",
+ url,
+ };
+}
export const sameRef = (a: AssetRef, b: AssetRef) => a.scope === b.scope && a.id === b.id;
diff --git a/site/src/cut/lib/chatAssets.ts b/site/src/cut/lib/chatAssets.ts
index 732c2868..4db6a386 100644
--- a/site/src/cut/lib/chatAssets.ts
+++ b/site/src/cut/lib/chatAssets.ts
@@ -13,22 +13,37 @@ import { useEditor } from "./store";
// the Library (its own file).
let activeChatId: string | null = null;
+/** The thread whose turn is streaming right now. Pinned for the whole turn,
+ * so a tool that runs after the user clicks over to another thread still
+ * tags its media with the thread that asked. */
+let turnChatId: string | null = null;
-/** The chat thread whose tools are currently running. The chat session sets
- * this while mounted so tool-created assets can be tagged with their owner. */
+/** The chat thread whose panel is on screen. The chat session sets this while
+ * mounted so tool-created assets can be tagged with their owner. */
export function setActiveChatThread(id: string | null) {
activeChatId = id;
}
-/** The owning thread to stamp on an asset created right now. Capture it
- * before a background render so the clip files under the chat that asked,
- * even if the user has switched threads by the time it lands. */
+/** Pin `id` as the owner for a streaming turn's tool work. */
+export function beginChatTurn(id: string) {
+ turnChatId = id;
+}
+
+/** Release the turn pin — only if `id` still holds it (a newer turn wins). */
+export function endChatTurn(id: string) {
+ if (turnChatId === id) turnChatId = null;
+}
+
+/** The owning thread to stamp on an asset created right now: the streaming
+ * turn's thread when one is live, else the open panel's. Capture it before a
+ * background render so the clip files under the chat that asked, even if the
+ * user has switched threads by the time it lands. */
export function chatOwner(): string | null {
- return activeChatId;
+ return turnChatId ?? activeChatId;
}
/** Tag a landed project asset as owned by a chat thread. */
-export function tagChatAsset(assetId: string, chatId: string | null = activeChatId) {
+export function tagChatAsset(assetId: string, chatId: string | null = chatOwner()) {
if (!chatId) return;
useEditor.getState().updateAsset(assetId, { origin: "chat", chatId });
}
diff --git a/site/src/cut/lib/laneTracks.ts b/site/src/cut/lib/laneTracks.ts
index e6771456..f6b9111d 100644
--- a/site/src/cut/lib/laneTracks.ts
+++ b/site/src/cut/lib/laneTracks.ts
@@ -274,8 +274,18 @@ function rubberBand(overPx: number, max: number): number {
const leftGuide = (t: number, pps: number) => t * pps;
const rightGuide = (t: number, pps: number) => t * pps - CLIP_GAP;
-// The in-flight elastic snap-back; any new gesture cancels it.
-let snapBackRaf = 0;
+// The in-flight elastic snap-back. A new gesture settles it instantly rather
+// than abandoning it: the floor is a correctness bound (a media item's first
+// sample, or the leader run), and an abandoned snap would persist a
+// below-floor trim into the doc.
+let snapBack: { raf: number; finish: () => void } | null = null;
+function settleSnapBack() {
+ if (!snapBack) return;
+ cancelAnimationFrame(snapBack.raf);
+ const { finish } = snapBack;
+ snapBack = null;
+ finish();
+}
/** The live move drag, published so the Timeline can render the ghost, the
* landing slot, and grow the lane stack while a new row is hovered. */
@@ -326,7 +336,7 @@ export function startLaneMove<V = unknown>(
id: string,
ui: LaneMoveUI<V>
) {
- cancelAnimationFrame(snapBackRaf);
+ settleSnapBack();
const s = useEditor.getState();
if (e.metaKey || e.shiftKey) {
s.toggleSelect({ kind, id } as NonNullable<Selection>);
@@ -551,7 +561,7 @@ export function startLaneTrim(
side: "l" | "r",
ui: LaneTrimUI
) {
- cancelAnimationFrame(snapBackRaf);
+ settleSnapBack();
const s = useEditor.getState();
const ad = ADAPTERS[kind];
const raw0 = ad.raws(s).find((r) => ad.view(r).id === id);
@@ -582,15 +592,21 @@ export function startLaneTrim(
.sort((a, b) => a.view.start - b.view.start);
const last = leaders[leaders.length - 1];
const lastAllow = last ? allow(last.raw, raw0) : 0;
+ // Each leader's declared dissolve into the item after it (the last one's
+ // into the trimmed item itself): packing the run keeps those overlaps, so
+ // they come off the floor and stay in the re-lay.
+ const pairAllow = leaders.map((l, i) =>
+ i + 1 < leaders.length ? allow(l.raw, leaders[i + 1].raw) : lastAllow
+ );
const prevEnd =
leaders.reduce((m, l) => Math.max(m, l.view.start + l.view.len), 0) - lastAllow;
- const runFloor = leaders.reduce((sum, l) => sum + l.view.len, 0) - lastAllow;
+ const runFloor = leaders.reduce((sum, l, i) => sum + l.view.len - pairAllow[i], 0);
const floor = Math.max(runFloor, ad.leftFloor(raw0));
const free = Math.max(prevEnd, ad.leftFloor(raw0));
const moved = new Map<string, number>();
startDrag(e, {
onMove: (dx, _dy, ev) => {
- cancelAnimationFrame(snapBackRaf);
+ settleSnapBack();
const desired = Math.min(maxStart, start0 + dx / ui.pps);
let start: number;
if (desired >= free) {
@@ -614,7 +630,8 @@ export function startLaneTrim(
}
// Re-lay the leaders right-to-left from their resting spots: each one
// slides only as far as the pushed edge (or the item it now abuts)
- // forces it, so a retreating drag lets the run flow back. Unmoved
+ // forces it, so a retreating drag lets the run flow back — and a
+ // cross-dissolved pair keeps its overlap while it slides. Unmoved
// leaders get no patch (they'd re-render for nothing).
const patches = [ad.trimLeftPatch(raw0, start)];
let limit = Math.max(start, runFloor) + lastAllow;
@@ -628,7 +645,8 @@ export function startLaneTrim(
if (Math.abs(ns - l.view.start) > 1e-9) moved.set(l.view.id, ns);
else moved.delete(l.view.id);
}
- limit = ns;
+ // The leader before this one may keep its dissolve overlap into it.
+ limit = ns + (i > 0 ? pairAllow[i - 1] : 0);
}
ad.apply(patches);
},
@@ -637,15 +655,17 @@ export function startLaneTrim(
const cur = ad.raws(useEditor.getState()).find((r) => ad.view(r).id === id);
const from = cur ? ad.view(cur).start : floor;
if (from >= floor - 1e-4) return; // settled within the room
- // Elastic spring back to the floor.
+ // Elastic spring back to the floor. `finish` lands the floor exactly,
+ // so an interrupting gesture settles rather than strands the trim.
const t0 = performance.now();
+ const finish = () => ad.apply([ad.trimLeftPatch(raw0, floor)]);
const step = (now: number) => {
const p = Math.min(1, (now - t0) / 240);
const v = Math.max(0, from + (floor - from) * easeOutBack(p));
ad.apply([ad.trimLeftPatch(raw0, p < 1 ? v : floor)]);
- if (p < 1) snapBackRaf = requestAnimationFrame(step);
+ snapBack = p < 1 ? { raf: requestAnimationFrame(step), finish } : null;
};
- snapBackRaf = requestAnimationFrame(step);
+ snapBack = { raf: requestAnimationFrame(step), finish };
},
});
return;
diff --git a/site/src/cut/lib/previewAudio.ts b/site/src/cut/lib/previewAudio.ts
index 56b4310f..89da65aa 100644
--- a/site/src/cut/lib/previewAudio.ts
+++ b/site/src/cut/lib/previewAudio.ts
@@ -32,7 +32,12 @@ export const usePreviewAudio = create<PreviewAudioState>((set, get) => ({
audio.onended = () => set({ url: null });
audio.onerror = () => set({ url: null });
set({ url });
- void audio.play().catch(() => set({ url: null }));
+ void audio.play().catch(() => {
+ // A superseded play() rejects late ("interrupted by a new load
+ // request") — only the call still owning the state may clear it, or a
+ // stale rejection would knock out the preview playing now.
+ if (get().url === url) set({ url: null });
+ });
},
stop: (url) => {
if (url !== undefined && get().url !== url) return;
diff --git a/site/src/cut/lib/refMedia.ts b/site/src/cut/lib/refMedia.ts
index e8e1b72d..f5f7a57a 100644
--- a/site/src/cut/lib/refMedia.ts
+++ b/site/src/cut/lib/refMedia.ts
@@ -147,7 +147,7 @@ export async function refsFromDroppedFiles(projectId: string, files: File[]): Pr
for (const file of files) {
try {
if (isTextFile(file) && !isMediaFile(file)) {
- refs.push(refFromTextFile(file));
+ refs.push(await refFromTextFile(file));
continue;
}
const asset = await importFileToProject(projectId, file);
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index 9ea19503..42df93c8 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -144,6 +144,10 @@ export interface EditorState {
/** Set a clip's playback rate (0.25–4). A longer footprint pushes the
* following clips right by the overflow; a shorter one opens a gap. */
setClipSpeed: (id: string, speed: number) => void;
+ /** Set a clip's source trim points with the same run rules as a speed
+ * resize: a longer footprint pushes the following clips right, a shorter
+ * one opens a gap, and a live dissolve keeps its overlap. */
+ setClipTrim: (id: string, nextIn: number, nextOut: number) => void;
/** Set the transition into the next clip (seconds; 0 clears it), optionally
* changing its style; omitting the style keeps the clip's current one. */
setClipTransition: (id: string, seconds: number, style?: TransitionStyle) => void;
@@ -287,6 +291,52 @@ type ClipboardItem =
| { kind: "text"; item: TextOverlay };
let clipboard: ClipboardItem[] = [];
+/** Bumped whenever subtitle lanes renumber (a track removal). Async work that
+ * captured a lane index checks it before landing, so a result can't write to
+ * what is now a different language's track. */
+let laneEpoch = 0;
+
+/** Resize a track-0 clip's footprint to `newLen` (a trim or speed change),
+ * keeping the track sound: a live dissolve into the next clip stays a
+ * dissolve (the run follows the resize so the pair keeps its overlap);
+ * otherwise a longer footprint pushes the run right by the overflow and a
+ * shorter one just opens a gap. One undo step. */
+function resizeClipFootprint(clip: VideoClip, patch: Partial<VideoClip>, newLen: number) {
+ useEditor.getState().pushHistory();
+ useEditor.getState().updateClipTransient(clip.id, patch);
+ const next = useEditor
+ .getState()
+ .clips.filter((c) => c.id !== clip.id && c.start >= clip.start)
+ .reduce<VideoClip | null>((m, c) => (!m || c.start < m.start ? c : m), null);
+ const nextStart = next?.start ?? Infinity;
+ const keep = next
+ ? Math.min(
+ transitionOverlap(clip, next),
+ Math.max(0, clip.start + clipLen(clip) - nextStart),
+ newLen * 0.9
+ )
+ : 0;
+ const delta =
+ keep > 1e-6
+ ? clip.start + newLen - keep - nextStart
+ : Math.max(0, clip.start + newLen - nextStart);
+ if (Math.abs(delta) > 1e-6) {
+ useEditor.setState((st) => ({
+ clips: st.clips
+ .map((c) =>
+ c.id !== clip.id && c.start >= clip.start
+ ? { ...c, start: Math.max(0, c.start + delta) }
+ : c
+ )
+ .sort((a, b) => a.start - b.start),
+ }));
+ }
+}
+const staleLaneError = {
+ subtitleStatus: "error" as const,
+ subtitleError: "Subtitle tracks changed while working — run it again.",
+};
+
/** Earliest start at/after `t` where a `len`-long item fits between the
* occupied `spans` of one lane: each blocker slides the candidate right to its
* end until a big-enough gap opens. The one placement-collision primitive for
@@ -525,7 +575,11 @@ export const useEditor = create<EditorState>((set, get) => {
// the asset list, so removing one must not open a checkpoint or churn
// the clip arrays (a fresh clips reference would count as a doc change
// and wipe the redo branch).
- if (!st.clips.some((c) => c.assetId === id) && !st.audioClips.some((c) => c.assetId === id)) {
+ if (
+ !st.clips.some((c) => c.assetId === id) &&
+ !st.overlayClips.some((c) => c.assetId === id) &&
+ !st.audioClips.some((c) => c.assetId === id)
+ ) {
set((s) => ({ assets: s.assets.filter((a) => a.id !== id) }));
return;
}
@@ -534,15 +588,18 @@ export const useEditor = create<EditorState>((set, get) => {
// the rest of the timeline (and its annotations) stays where it is.
set((s) => {
const goneClips = new Set(s.clips.filter((c) => c.assetId === id).map((c) => c.id));
+ const goneOverlay = new Set(s.overlayClips.filter((c) => c.assetId === id).map((c) => c.id));
const goneAudio = new Set(s.audioClips.filter((c) => c.assetId === id).map((c) => c.id));
const keep = (sel: Selection) =>
!!sel &&
!((sel.kind === "clip" && goneClips.has(sel.id)) ||
+ (sel.kind === "overlayClip" && goneOverlay.has(sel.id)) ||
(sel.kind === "audio" && goneAudio.has(sel.id)));
const multiSelection = s.multiSelection.filter(keep);
return {
assets: s.assets.filter((a) => a.id !== id),
clips: s.clips.filter((c) => c.assetId !== id),
+ overlayClips: s.overlayClips.filter((c) => c.assetId !== id),
audioClips: s.audioClips.filter((c) => c.assetId !== id),
multiSelection,
selection: keep(s.selection) ? s.selection : multiSelection[multiSelection.length - 1] ?? null,
@@ -648,46 +705,18 @@ export const useEditor = create<EditorState>((set, get) => {
},
setClipSpeed: (id, speed) => {
- const s = get();
- const clip = s.clips.find((c) => c.id === id);
+ const clip = get().clips.find((c) => c.id === id);
if (!clip) return;
const clamped = Math.max(SPEED_MIN, Math.min(SPEED_MAX, speed));
if (Math.abs(clamped - clipSpeed(clip)) < 1e-4) return;
- const newLen = Math.max(MIN_LEN, (clip.out - clip.in) / clamped);
- push();
- get().updateClipTransient(id, { speed: clamped });
- const followers = s.clips.filter((c) => c.id !== id && c.start >= clip.start);
- const next = followers.reduce<VideoClip | null>(
- (m, c) => (!m || c.start < m.start ? c : m),
- null
- );
- const nextStart = next?.start ?? Infinity;
- // A live dissolve into the next clip stays a dissolve: the run follows
- // the resize (both directions) so the pair keeps its overlap. Otherwise
- // free-track rules — a longer footprint pushes the run right by the
- // overflow (like a resize); a shorter one just opens a gap.
- const keep = next
- ? Math.min(
- transitionOverlap(clip, next),
- Math.max(0, clip.start + clipLen(clip) - nextStart),
- newLen * 0.9
- )
- : 0;
- const delta =
- keep > 1e-6
- ? clip.start + newLen - keep - nextStart
- : Math.max(0, clip.start + newLen - nextStart);
- if (Math.abs(delta) > 1e-6) {
- set((st) => ({
- clips: st.clips
- .map((c) =>
- c.id !== id && c.start >= clip.start
- ? { ...c, start: Math.max(0, c.start + delta) }
- : c
- )
- .sort((a, b) => a.start - b.start),
- }));
- }
+ resizeClipFootprint(clip, { speed: clamped }, Math.max(MIN_LEN, (clip.out - clip.in) / clamped));
+ },
+
+ setClipTrim: (id, nextIn, nextOut) => {
+ const clip = get().clips.find((c) => c.id === id);
+ if (!clip) return;
+ if (Math.abs(nextIn - clip.in) < 1e-6 && Math.abs(nextOut - clip.out) < 1e-6) return;
+ resizeClipFootprint(clip, { in: nextIn, out: nextOut }, (nextOut - nextIn) / clipSpeed(clip));
},
setClipTransition: (id, seconds, style) => {
@@ -1234,8 +1263,12 @@ export const useEditor = create<EditorState>((set, get) => {
insertTemplate: (template, assetIds, offset) => {
push();
const usable = template.layers.filter((l) => assetIds[l.media]);
- const clipLayers = usable.filter((l) => l.asClip);
- const overlayLayers = usable.filter((l) => !l.asClip);
+ // Templates saved before the base-track removal persisted `onBase`;
+ // read it as asClip so their footage still lands on track 0.
+ const isClip = (l: (typeof usable)[number]) =>
+ l.asClip ?? (l as { onBase?: boolean }).onBase;
+ const clipLayers = usable.filter((l) => isClip(l));
+ const overlayLayers = usable.filter((l) => !isClip(l));
// Clip layers append at the end of the current track 0; the
// free-positioned parts (overlays, audio, captions) shift to line up with
// that segment. A template with no clip layers drops in at the playhead.
@@ -1343,6 +1376,7 @@ export const useEditor = create<EditorState>((set, get) => {
const assetById = new Map(s.assets.map((a) => [a.id, a]));
// Generation targets the active subtitle track, with its own language.
const lane = s.subtitleLane;
+ const epoch = laneEpoch;
const spec = {
duration,
locale: trackLocale(s.subtitles, lane),
@@ -1378,6 +1412,7 @@ export const useEditor = create<EditorState>((set, get) => {
try {
const cues = await runTranscription(projectId, spec);
if (cues === null) return; // switched projects mid-run
+ if (laneEpoch !== epoch) return set(staleLaneError);
// Only the active track's cues are replaced; other languages stay.
const tagged = cues.map((c) => ({ ...c, ...(lane > 0 ? { lane } : {}) }));
if (cues.length === 0) {
@@ -1426,6 +1461,7 @@ export const useEditor = create<EditorState>((set, get) => {
const sp = getClipSpans(s.clips, s.assets).find((x) => x.clip.id === clipId);
if (!sp) throw new Error("The clip is no longer on the timeline.");
const lane = s.subtitleLane;
+ const epoch = laneEpoch;
// The clip's own sound, deliberately unmuted: this transcribes what the
// clip says even when its timeline audio is muted.
const spec = {
@@ -1447,6 +1483,10 @@ export const useEditor = create<EditorState>((set, get) => {
try {
const cues = await runTranscription(projectId, spec);
if (cues === null) return; // switched projects mid-run
+ if (laneEpoch !== epoch) {
+ set(staleLaneError);
+ throw new Error(staleLaneError.subtitleError);
+ }
// The job timed cues against the lone clip, so shift them (and their
// word timings) onto the clip's timeline span. New cues replace any
// on the active track that overlapped the clip; the rest of the
@@ -1490,6 +1530,7 @@ export const useEditor = create<EditorState>((set, get) => {
}
const duration = totalDuration(s.clips);
const lane = s.subtitleLane;
+ const epoch = laneEpoch;
set({ subtitleStatus: "running", subtitleError: null });
try {
const frames = await captureTimelineFrames(spans);
@@ -1510,6 +1551,7 @@ export const useEditor = create<EditorState>((set, get) => {
throw new Error(body.error ?? "Captioning failed.");
}
if (get().projectId !== projectId) return; // switched projects mid-run
+ if (laneEpoch !== epoch) return set(staleLaneError);
const cues: SubtitleCue[] = body.cues.map((c) => ({
id: uid(),
start: c.start,
@@ -1609,6 +1651,7 @@ export const useEditor = create<EditorState>((set, get) => {
if (source.length === 0) return;
const locale = trackLocale(s.subtitles, lane);
const projectId = s.projectId;
+ const epoch = laneEpoch;
set({ subtitleStatus: "running", subtitleError: null });
try {
const res = await apiFetch("/api/cut/ai/captions", {
@@ -1624,6 +1667,7 @@ export const useEditor = create<EditorState>((set, get) => {
if (!res.ok || !Array.isArray(body.texts) || body.texts.length !== source.length) {
throw new Error(body.error || "Could not translate the captions.");
}
+ if (laneEpoch !== epoch) return set(staleLaneError);
push();
const texts = body.texts;
set((cur) => ({
@@ -1694,6 +1738,7 @@ export const useEditor = create<EditorState>((set, get) => {
);
if (count <= 1) return;
push();
+ laneEpoch++; // lanes renumber: invalidate in-flight lane-targeted work
const gone = new Set(
s.subtitles.cues.filter((c) => (c.lane ?? 0) === lane).map((c) => c.id)
);
@@ -1720,7 +1765,12 @@ export const useEditor = create<EditorState>((set, get) => {
return l > lane ? { ...c, lane: l - 1 > 0 ? l - 1 : undefined } : c;
}),
},
- subtitleLane: Math.max(0, Math.min(count - 2, cur.subtitleLane)),
+ // The active lane follows its track: lanes above the removed one
+ // shift down; removing the active one clamps into range.
+ subtitleLane: Math.max(
+ 0,
+ Math.min(count - 2, cur.subtitleLane > lane ? cur.subtitleLane - 1 : cur.subtitleLane)
+ ),
multiSelection,
selection: keep(cur.selection)
? cur.selection