Skip to content

The open source AI video agent: turns any coding agent into a video agent, with an editor to change anything it makes.

Studio: pressing Undo again and again no longer takes the editor away (#135)

riverisbuilding8209ca45a5a1
diff --git a/.changeset/undo-refused-step.md b/.changeset/undo-refused-step.md
new file mode 100644
index 0000000..8279604
--- /dev/null
+++ b/.changeset/undo-refused-step.md
@@ -0,0 +1,5 @@
+---
+"openfilm": patch
+---
+
+Pressing Undo again and again no longer makes the editor disappear. An edit that cannot be undone, because the agent changed or removed what it was about since, says why once and leaves the history, so the next Undo goes on to the edit before it and Undo stops at the oldest one.
diff --git a/packages/openfilm/studio/ui/src/components/ProjectView.tsx b/packages/openfilm/studio/ui/src/components/ProjectView.tsx
index f2adf9a..7475f10 100644
--- a/packages/openfilm/studio/ui/src/components/ProjectView.tsx
+++ b/packages/openfilm/studio/ui/src/components/ProjectView.tsx
@@ -271,7 +271,10 @@ export function ProjectView({ projectId, onProject, onLeave }: {
personSteps.current = film.steps.done;
const filmRef = React.useRef(film.film);
filmRef.current = film.film;
- React.useEffect(() => { if (film.error) toast.showError(film.error); }, [film.error, toast]);
+ /* on `showError`, which stays the same: `toast` is new with every message, so showing it would run this again, and
+ again (the editor gone) */
+ const { showError } = toast;
+ React.useEffect(() => { if (film.error) showError(film.error); }, [film.error, showError]);
/* media facts (length, size, sound) of the project's videos, stills and sounds and its web pages, probed once each: a
page without a duration has no end, and is dropped on the timeline with a length of its own; a picture's size
diff --git a/packages/openfilm/studio/ui/src/editor/steps.test.ts b/packages/openfilm/studio/ui/src/editor/steps.test.ts
new file mode 100644
index 0000000..4075e9f
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/editor/steps.test.ts
@@ -0,0 +1,97 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { applyOps, EditError } from '../../../server/ops.mjs';
+import type { Film, Op } from '../api';
+import { dropStep, moveStep, nextStep, pushStep, type Steps } from './steps.ts';
+import { inverse } from './undo.ts';
+
+/* The edit history as the editor keeps it (use-film): ⌘Z pressed again and again goes back step by step and stops at
+ the oldest, even when the agent removed what a step was about meanwhile. */
+
+type Step = { undo: Op[]; redo: Op[]; label: string };
+const empty = (): Steps<Step> => ({ done: [], undone: [] });
+const film = (...tracks: object[][]): Film => ({ stage: { w: 1920, h: 1080 }, tracks: tracks.map((clips) => ({ clips })) as Film['tracks'] });
+const ids = (f: Film) => f.tracks.map((t) => t.clips.map((c) => c.id));
+
+/** An editor in short: edits and undos applied as use-film applies them, a refused one leaving the history. */
+function editor(start: Film) {
+ let value = start;
+ let steps = empty();
+ return {
+ get film() { return value; },
+ get steps() { return steps; },
+ edit(ops: Op[], label: string) {
+ const after = applyOps(structuredClone(value), ops) as Film;
+ steps = pushStep(steps, { undo: inverse(value, after, ops), redo: ops, label });
+ value = after;
+ },
+ /** what the agent wrote: the film is the folder's, the history stays */
+ outside(next: Film) { value = next; },
+ /** ⌘Z: null when it did something, else why not (nothing left, or the step could not be undone) */
+ undo(): string | null {
+ const one = nextStep(steps, 'undo');
+ if (!one) return 'nothing to undo';
+ try {
+ value = applyOps(structuredClone(value), one.undo) as Film;
+ steps = moveStep(steps, one, 'undo');
+ return null;
+ } catch (e) {
+ assert.ok(e instanceof EditError, String(e));
+ steps = dropStep(steps, one);
+ return e.message;
+ }
+ },
+ };
+}
+
+test('undo pressed past the start of the history stops at the oldest film and stays there', () => {
+ const start = film([{ src: 'a.html', id: 'a' }, { src: 'b.html', id: 'b', at: 3 }], [{ src: 'c.html', id: 'c' }]);
+ const ed = editor(start);
+ ed.edit([{ op: 'remove', clip: 'a' }], 'remove a');
+ ed.edit([{ op: 'props', edits: [{ clip: 'c', prop: 'at', value: 2 }] }], 'move c');
+ for (let i = 0; i < 2; i++) assert.equal(ed.undo(), null);
+ assert.deepEqual(ed.film, start);
+ for (let i = 0; i < 6; i++) assert.equal(ed.undo(), 'nothing to undo');
+ assert.deepEqual(ed.film, start);
+ assert.deepEqual(ed.steps.done, []);
+ assert.deepEqual(ed.steps.undone.map((s) => s.label), ['move c', 'remove a']);
+});
+
+test('a step whose clip the agent removed leaves the history, and the next undo takes the one before it', () => {
+ const ed = editor(film([{ src: 'a.html', id: 'a' }], [{ src: 'b.html', id: 'b' }]));
+ ed.edit([{ op: 'props', edits: [{ clip: 'a', prop: 'at', value: 1 }] }], 'move a');
+ ed.edit([{ op: 'props', edits: [{ clip: 'b', prop: 'at', value: 2 }] }], 'move b');
+ /* the agent writes the film again without b */
+ ed.outside(film([{ src: 'a.html', id: 'a', at: 1 }]));
+ const why = ed.undo();
+ assert.match(why ?? '', /b/, 'says why it could not be undone');
+ assert.deepEqual(ed.steps.done.map((s) => s.label), ['move a'], 'the refused step is gone, not tried again');
+ assert.deepEqual(ed.steps.undone, []);
+ assert.equal(ed.undo(), null);
+ assert.deepEqual(ids(ed.film), [['a']]);
+ assert.equal(ed.film.tracks[0].clips[0].at ?? 0, 0);
+ /* and then it stops */
+ for (let i = 0; i < 4; i++) assert.equal(ed.undo(), 'nothing to undo');
+});
+
+test('moving or dropping a step touches that step only', () => {
+ const [a, b, c] = ['a', 'b', 'c'].map((label) => ({ undo: [], redo: [], label }));
+ const s = pushStep(pushStep(pushStep(empty(), a), b), c);
+ assert.equal(nextStep(s, 'undo'), c);
+ assert.equal(nextStep(empty(), 'undo'), null);
+ assert.equal(nextStep(empty(), 'redo'), null);
+ /* one not on the list it would leave (dropped meanwhile) is not moved, and nothing else is in its place */
+ const gone = dropStep(s, c);
+ assert.equal(moveStep(gone, c, 'undo'), gone);
+ assert.equal(moveStep(s, a, 'redo'), s);
+ const undone = moveStep(s, c, 'undo');
+ assert.deepEqual(undone, { done: [a, b], undone: [c] });
+ assert.deepEqual(moveStep(undone, c, 'redo'), s);
+ assert.deepEqual(dropStep(undone, c), { done: [a, b], undone: [] });
+ /* a new edit ends what could be made again; the history keeps the last hundred */
+ assert.deepEqual(pushStep(undone, a).undone, []);
+ let long = empty();
+ for (let i = 0; i < 120; i++) long = pushStep(long, { undo: [], redo: [], label: String(i) });
+ assert.equal(long.done.length, 100);
+ assert.equal(long.done[0].label, '20');
+});
diff --git a/packages/openfilm/studio/ui/src/editor/steps.ts b/packages/openfilm/studio/ui/src/editor/steps.ts
new file mode 100644
index 0000000..e33956b
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/editor/steps.ts
@@ -0,0 +1,36 @@
+/**
+ * The edit history's two lists: the steps done (oldest first) and the steps undone (the last one undone last). Plain
+ * functions, so the editor (use-film) and its tests move steps the same way.
+ */
+export type Steps<S> = { done: S[]; undone: S[] };
+
+/** How many steps are kept: the oldest go first. */
+const KEPT = 100;
+
+/** A new step: it goes on the done list, and what was undone cannot be made again. */
+export function pushStep<S>(s: Steps<S>, one: S): Steps<S> {
+ return { done: [...s.done.slice(-(KEPT - 1)), one], undone: [] };
+}
+
+/**
+ * `one` undone or made again: it moves to the other list. Only that step moves, so a list changed meanwhile (a step
+ * left out) never moves another one, and never one that is not there.
+ */
+export function moveStep<S>(s: Steps<S>, one: S, kind: 'undo' | 'redo'): Steps<S> {
+ const [from, to] = kind === 'undo' ? [s.done, s.undone] : [s.undone, s.done];
+ if (!from.includes(one)) return s;
+ const left = from.filter((x) => x !== one);
+ const moved = [...to, one];
+ return kind === 'undo' ? { done: left, undone: moved } : { done: moved, undone: left };
+}
+
+/** `one` cannot be undone or made again (what it was about changed since, elsewhere): it leaves both lists. */
+export function dropStep<S>(s: Steps<S>, one: S): Steps<S> {
+ return { done: s.done.filter((x) => x !== one), undone: s.undone.filter((x) => x !== one) };
+}
+
+/** The step the next undo or redo takes, or null at the end of the history (nothing is done then). */
+export function nextStep<S>(s: Steps<S>, kind: 'undo' | 'redo'): S | null {
+ const list = kind === 'undo' ? s.done : s.undone;
+ return list.length ? list[list.length - 1] : null;
+}
diff --git a/packages/openfilm/studio/ui/src/editor/use-film.ts b/packages/openfilm/studio/ui/src/editor/use-film.ts
index fdf139f..b089221 100644
--- a/packages/openfilm/studio/ui/src/editor/use-film.ts
+++ b/packages/openfilm/studio/ui/src/editor/use-film.ts
@@ -16,6 +16,7 @@ import { applyOps, EditError } from '../../../server/ops.mjs';
import { filmHead } from '../../../../src/film-doc.mjs';
import { api, ApiError, projectEvents, type Film, type Op } from '../api';
import { inverse } from './undo';
+import { dropStep, moveStep, nextStep, pushStep, type Steps } from './steps';
export type FilmState = { value: Film; rev: string };
@@ -40,11 +41,11 @@ export function useFilm(projectId: string, initial: FilmState | null, onChange:
const brokenRev = useRef<string | null>(null);
/** edits applied here and not yet written */
const pending = useRef(0);
- const [steps, setStepsState] = useState<{ done: Step[]; undone: Step[] }>({ done: [], undone: [] });
+ const [steps, setStepsState] = useState<Steps<Step>>({ done: [], undone: [] });
/* the steps as they are now, ahead of the render: an undo pressed right after an edit (a nudge written the moment
before it) undoes that edit, not the one before */
const stepsRef = useRef(steps);
- const setSteps = useCallback((next: (s: { done: Step[]; undone: Step[] }) => { done: Step[]; undone: Step[] }) => {
+ const setSteps = useCallback((next: (s: Steps<Step>) => Steps<Step>) => {
stepsRef.current = next(stepsRef.current);
setStepsState(stepsRef.current);
}, []);
@@ -96,8 +97,9 @@ export function useFilm(projectId: string, initial: FilmState | null, onChange:
* Apply `ops` here at once, then write them. Resolves once written: null, or why it was not (the film here is then
* the folder's again). Resolves at once with the reason when the film here refuses them.
*/
- /* `quiet`: the caller says why it was refused itself (the inspector, beside its field), so `error` is not set */
- const run = useCallback((ops: Op[], record: 'do' | 'undo' | 'redo' = 'do', label = 'history.stepEdit', quiet = false): Promise<string | null> => {
+ /* `quiet`: the caller says why it was refused itself (the inspector, beside its field), so `error` is not set.
+ `one`: the step an undo or redo takes, moved to the other list once applied here */
+ const run = useCallback((ops: Op[], record: 'do' | 'undo' | 'redo' = 'do', label = 'history.stepEdit', quiet = false, one?: Step): Promise<string | null> => {
const current = ref.current;
if (!current || !ops.length) return Promise.resolve(null);
/* film.html cannot be read: the edit could not be written, and shown it would draw the picture again from the
@@ -118,9 +120,7 @@ export function useFilm(projectId: string, initial: FilmState | null, onChange:
changed.current(after, 'edit');
pending.current += 1;
const step: Step = { undo: inverse(before, after, ops), redo: ops, label, at: Date.now() };
- setSteps((s) => (record === 'do' ? { done: [...s.done.slice(-99), step], undone: [] }
- : record === 'undo' ? { done: s.done.slice(0, -1), undone: [...s.undone, s.done[s.done.length - 1]] }
- : { done: [...s.done, s.undone[s.undone.length - 1]], undone: s.undone.slice(0, -1) }));
+ setSteps((s) => (record === 'do' ? pushStep(s, step) : one ? moveStep(s, one, record) : s));
const written = queue.current.then(async (): Promise<string | null> => {
try {
const done = await api.edit(projectId, ref.current?.rev ?? null, ops);
@@ -164,26 +164,31 @@ export function useFilm(projectId: string, initial: FilmState | null, onChange:
/* a step of another file: moved between the lists at once, its call made in turn with the film's writes; one that
cannot be undone (the file changed since, elsewhere) leaves both lists, and says why */
const runOutside = useCallback((step: Step, kind: 'undo' | 'redo') => {
- setSteps((s) => (kind === 'undo' ? { done: s.done.slice(0, -1), undone: [...s.undone, step] } : { done: [...s.done, step], undone: s.undone.slice(0, -1) }));
+ setSteps((s) => moveStep(s, step, kind));
const written = queue.current.then(async () => {
const why = await step.outside![kind]().catch((e: unknown) => String(e instanceof Error ? e.message : e));
if (why) {
setError(why);
- setSteps((s) => ({ done: s.done.filter((x) => x !== step), undone: s.undone.filter((x) => x !== step) }));
+ setSteps((s) => dropStep(s, step));
}
});
queue.current = written;
}, [setSteps]);
+ /* a step of the film: one whose ops cannot be applied or written now (the agent removed its clip since) leaves both
+ lists, as one of another file does, so the next undo takes the step before it and the history ends at the oldest */
const step = useCallback((one: Step, kind: 'undo' | 'redo') => {
- if (one.outside) runOutside(one, kind);
- else void run(kind === 'undo' ? one.undo : one.redo, kind);
- }, [run, runOutside]);
+ if (one.outside) { runOutside(one, kind); return; }
+ const ops = kind === 'undo' ? one.undo : one.redo;
+ /* nothing to apply (an edit that changed nothing): it only moves */
+ if (!ops.length) { setSteps((s) => moveStep(s, one, kind)); return; }
+ void run(ops, kind, undefined, false, one).then((why) => { if (why) setSteps((s) => dropStep(s, one)); });
+ }, [run, runOutside, setSteps]);
const undo = useCallback(() => {
- const one = stepsRef.current.done[stepsRef.current.done.length - 1];
+ const one = nextStep(stepsRef.current, 'undo');
if (one) step(one, 'undo');
}, [step]);
const redo = useCallback(() => {
- const one = stepsRef.current.undone[stepsRef.current.undone.length - 1];
+ const one = nextStep(stepsRef.current, 'redo');
if (one) step(one, 'redo');
}, [step]);
/** Undo or redo until `done` steps are done (the edit history's rows: click one to go back or forward to it). */
@@ -195,7 +200,7 @@ export function useFilm(projectId: string, initial: FilmState | null, onChange:
const edit = useCallback((ops: Op[], label?: string, quiet?: boolean) => run(ops, 'do', label, quiet), [run]);
/** An edit of another file, made already: kept as a step, so ⌘Z undoes it in turn with the film's. */
const record = useCallback((label: string, outside: OutsideStep) => {
- setSteps((s) => ({ done: [...s.done.slice(-99), { undo: [], redo: [], label, at: Date.now(), outside }], undone: [] }));
+ setSteps((s) => pushStep(s, { undo: [], redo: [], label, at: Date.now(), outside }));
}, [setSteps]);
/** The film was replaced as a whole (an earlier version put back): the edits made before are not undone into it. */
const forget = useCallback(() => setSteps(() => ({ done: [], undone: [] })), [setSteps]);