Skip to content

The open-source full-stack studio for Opus 5.5 motion video. Reverse engineering for any video. Code video with HTML: recreate, edit and render. BYOA + BYOK · Motion.md · Images, Video, Music & Voice.

fix(studio): disable unavailable undo and redo actions

罗高9d190f71e71b
diff --git a/docs/editor-fork.md b/docs/editor-fork.md
index cf8d2d62..a6a29d20 100644
--- a/docs/editor-fork.md
+++ b/docs/editor-fork.md
@@ -16,6 +16,10 @@ OpenDesign 的 `WorkspaceFrame` 放在原生 App 外,负责通用导航和会
「版本历史」Tab 是本地新增的 UI,所调用的历史、撤销/重做、保留与恢复服务来自 Hyperframes;没有另建版本数据存储。
+Undo/redo availability is filtered by the workspace host using history metadata and readable native blob/aside files, without loading media contents. Missing contents, pruned steps and known later file conflicts disable the matching timeline button; keyboard shortcuts do not dispatch an unavailable step. Adding media can still be undone and redone through the native aside store. Native execution retains its final validation for concurrent changes and I/O failures. This does not change history budgets, pin behavior or MCP retained-version storage.
+
+Hosts passing a custom `editHistory` handle to `useEditHistoryActions` must supply `canUndo` and `canRedo` from their history view, alongside the step functions. `usePersistentEditHistory` already supplies these flags.
+
The sidebar language menu offers English, Simplified Chinese, Japanese, Korean, German, French, Russian, Spanish, Brazilian Portuguese, Italian and Turkish. The first launch still defaults to Simplified Chinese; `motion.studio.locale` stores the preference in browser localStorage and synchronizes it between same-origin windows. Unsupported or removed preferences fall back to Chinese. `studio/src/i18n/messages.ts` owns the supported languages, English message keys, dictionaries, interpolation and locale-aware plural forms; `I18n.tsx` provides the React context and Intl date/number formatting. Missing messages fall back to the English source.
Localization covers editor labels, tooltips, placeholders, empty/error states and the embedded MCP/template dialog. The DOM fragment updates bound labels in place, preserving the selected client, searches and live media. Switching language does not remount the editor, change Dock layout, modify property values or translate authored text, project/template titles, source paths and protocol identifiers. Property sections receive English source titles and translate them only for display, so duplicate translations cannot change their internal IDs. README/Skill/installer translations, third-party template descriptions, copied Agent instructions and long connection guides are outside this interface change. New locale dictionaries include machine-translated text; automated key/placeholder checks do not replace native-speaker review.
diff --git a/docs/product/architecture.md b/docs/product/architecture.md
index a2b9ba6b..4c9dff80 100644
--- a/docs/product/architecture.md
+++ b/docs/product/architecture.md
@@ -151,7 +151,7 @@ flowchart LR
| 导出快照与验证 | 固定 revision、预期规格、真实 MP4、校验报告 | 证明该次导出的结果;后续编辑不能沿用旧文件的验证结论 |
- **工程真源:** HTML、CSS、JS、媒体和 Studio manifest 位于各自工程目录。新会话 ID、产物 ID 和工程 ID 分离;`projects.json` 原子保存两个索引、产物归属和当前选择。旧工程按原 ID 兼容为会话,需求继续在 `sessions/<sessionId>.json`,通过会话 HTTP 接口及一期 `motion_get_project` 暴露(旧 design_get_session 为内部兼容),独立于视频内容 revision。Agent 每次写入前读取当前工程与 revision。一个原生服务进程按 projectId 分发多个工程;页面固定自己的工程,其他会话的打开操作不会替换它。工程状态请求也携带 projectId;未知工程和冲突身份拒绝处理。
-- **历史真源:** Studio 原生历史服务记录版本、checkpoint、pin 与 restore,宿主只呈现 UI,不另建版本库。恢复前等待保存并创建 checkpoint,完成后重新加载编辑会话;后续历史保留,恢复操作可以撤销。
+- **History authority:** Native Studio history owns file revisions, checkpoints, pins and restores; the host does not create a parallel Studio history store. The workspace host only offers undo/redo steps whose required contents are readable and whose recorded files have no known later conflict. Unavailable steps disable the matching toolbar button and do not dispatch a shortcut mutation. Native execution still validates current files before writing, since files can change after the availability check. Restores wait for pending saves and create a checkpoint before reloading the editing session; subsequent history remains available subject to native retention and content availability.
- **界面状态:** 浏览器 Tabs、左右面板与宽度按会话保存;关闭 Tab 不删除产物。原生 Dock 按工程保存,主题沿用 Studio 偏好;语言单独保存为 `motion.studio.locale`,均不写入影片源文件。
- **参考数据:** 模板原始目录、封面和热度快照与用户工程分开。热度按模板 ID、视频地址和原帖身份匹配;同源片段不累加查看量。
- **导出输入:** 后台任务使用不可变快照并记录期望规格;后续编辑不改变该任务的本地输入。远程媒体需要稳定复现时先导入本地。
diff --git a/shared/studio-history-availability.ts b/shared/studio-history-availability.ts
new file mode 100644
index 00000000..8001857c
--- /dev/null
+++ b/shared/studio-history-availability.ts
@@ -0,0 +1,35 @@
+import { accessSync, constants, statSync } from 'node:fs';
+import path from 'node:path';
+import { DEFAULT_HISTORY_ROOT, HISTORY_START } from '@hyperframes/studio-server';
+import type { ProjectHistory } from '@hyperframes/studio-server';
+
+/** Filter the offered steps; native undo/redo still validates files immediately before writing. */
+export function withAvailableHistorySteps(history: ProjectHistory, historyRoot = DEFAULT_HISTORY_ROOT): ProjectHistory {
+ const home = path.join(historyRoot, history.projectId);
+ // shortcut: the pinned 0.9.7 API has no blob-existence probe; replace this when upstream exposes one.
+ const readable = (hash: string) => /^[a-f0-9]{64}$/.test(hash) && ['blobs', 'aside'].some(directory => {
+ try {
+ const file = path.join(home, directory, hash.slice(0, 2), hash);
+ accessSync(file, constants.R_OK);
+ return statSync(file).isFile();
+ } catch { return false; }
+ });
+ return {
+ ...history,
+ next(direction, who) {
+ const entry = history.next(direction, who);
+ if (!entry) return undefined;
+ const entries = history.list();
+ const current: Record<string, string | null> = history.peek(entries.at(-1)?.id ?? HISTORY_START) ?? {};
+ // A pending step is not in the log yet, but its after hashes describe the observed files.
+ if (!entries.some(saved => saved.id === entry.id)) {
+ for (const file of entry.files) current[file.path] = file.after;
+ }
+ if (entry.files.some(file => (current[file.path] ?? null) !== file.after)) return undefined;
+ const deletedFirst = new Set(entry.files.filter(file => file.before === null).map(file => file.after));
+ // Native history moves deleted media into aside before restoring another path with those bytes.
+ return entry.files.every(file => file.before === null || deletedFirst.has(file.before) || readable(file.before))
+ ? entry : undefined;
+ },
+ };
+}
diff --git a/shared/workspace-studio.ts b/shared/workspace-studio.ts
index 06cc7d73..c8830c70 100644
--- a/shared/workspace-studio.ts
+++ b/shared/workspace-studio.ts
@@ -6,6 +6,7 @@ import { pathToFileURL } from 'node:url';
import { WorkspaceStore } from '../workspace.ts';
import { HYPERFRAMES_VERSION, repairGeneratedRegistry } from '../hyperframes.ts';
import { isMain } from './entry.ts';
+import { withAvailableHistorySteps } from './studio-history-availability.ts';
export async function startWorkspaceStudio(runtimeRoot: string, dataDirectory: string, initialDirectory: string, port: number) {
const require = createRequire(path.join(runtimeRoot, 'package.json'));
@@ -30,8 +31,14 @@ export async function startWorkspaceStudio(runtimeRoot: string, dataDirectory: s
await scoped.safePath('index.html');
await repairGeneratedRegistry(scoped.projectDirectory);
if (closing) throw new Error('Studio is stopping');
- return createStudioServer({ projectDir: scoped.projectDirectory, projectName: id,
+ const host = createStudioServer({ projectDir: scoped.projectDirectory, projectName: id,
origin: () => origin, historyRoot: process.env.HYPERFRAMES_HISTORY_ROOT });
+ const openHistory = host.adapter.history;
+ host.adapter.history = async () => {
+ const history = await openHistory();
+ return history && withAvailableHistorySteps(history, process.env.HYPERFRAMES_HISTORY_ROOT);
+ };
+ return host;
})().catch(error => { hosts.delete(id); throw error; });
hosts.set(id, opening);
}
diff --git a/studio/src/hooks/useAppHotkeys.previewForwarding.test.tsx b/studio/src/hooks/useAppHotkeys.previewForwarding.test.tsx
index 139c6fbb..87f3c45a 100644
--- a/studio/src/hooks/useAppHotkeys.previewForwarding.test.tsx
+++ b/studio/src/hooks/useAppHotkeys.previewForwarding.test.tsx
@@ -41,6 +41,8 @@ function Harness() {
domEditSelectionRef: selectionRef,
clearDomSelectionRef: useRef<() => void>(() => undefined),
editHistory: {
+ canUndo: true,
+ canRedo: true,
undo: historyUndo,
redo: historyRedo,
state: { undo: [], redo: [] },
diff --git a/studio/src/hooks/useAppHotkeys.textEditing.test.tsx b/studio/src/hooks/useAppHotkeys.textEditing.test.tsx
index cee5bb8e..a5fde755 100644
--- a/studio/src/hooks/useAppHotkeys.textEditing.test.tsx
+++ b/studio/src/hooks/useAppHotkeys.textEditing.test.tsx
@@ -77,6 +77,8 @@ function Harness() {
domEditSelectionRef: selectionRef,
clearDomSelectionRef: clearSelectionRef,
editHistory: {
+ canUndo: true,
+ canRedo: true,
undo: vi.fn(async () => ({ ok: false })),
redo: vi.fn(async () => ({ ok: false })),
state: { undo: [], redo: [] },
diff --git a/studio/src/hooks/useEditHistoryActions.test.tsx b/studio/src/hooks/useEditHistoryActions.test.tsx
index 518bef85..e09d6b43 100644
--- a/studio/src/hooks/useEditHistoryActions.test.tsx
+++ b/studio/src/hooks/useEditHistoryActions.test.tsx
@@ -40,6 +40,8 @@ function mount(
claims: () => number = () => 7,
) {
const editHistory = {
+ canUndo: true,
+ canRedo: true,
undo: vi.fn<EditHistoryHandle["undo"]>(async () => result),
redo: vi.fn<EditHistoryHandle["redo"]>(async () => result),
predict: () => predicted ?? null,
@@ -74,6 +76,28 @@ const PREDICTED = { id: "e1", files: { "index.html": { previous: "B", restored:
const SERVER_FILES = { "index.html": { previous: "B", restored: "A2" } };
describe("useEditHistoryActions", () => {
+ it("ignores unavailable undo and redo before calling history or reading files", async () => {
+ const { deps, actions } = mount({ ok: false, reason: "empty" });
+ deps.editHistory.canUndo = false;
+ deps.editHistory.canRedo = false;
+ await act(() => actions.undo());
+ await act(() => actions.redo());
+ expect(deps.editHistory.undo).not.toHaveBeenCalled();
+ expect(deps.editHistory.redo).not.toHaveBeenCalled();
+ expect(deps.waitForPendingDomEditSaves).not.toHaveBeenCalled();
+ expect(deps.readProjectFile).not.toHaveBeenCalled();
+ expect(deps.showToast).not.toHaveBeenCalled();
+ });
+ it("can still take back an edit saving before its history step is available", async () => {
+ const { deps, actions } = mount({ ok: false, reason: "empty" });
+ deps.editHistory.canUndo = false;
+ const revert = vi.fn(() => () => {});
+ const saving = beginStudioPendingEdit(revert);
+ try {
+ await act(() => actions.undo());
+ expect(revert).toHaveBeenCalledTimes(1);
+ } finally { saving.settle(); }
+ });
it("counts an undo as a preview change from its key until its preview update is applied", async () => {
const files = { "index.html": { previous: "B", restored: "A" } };
const stepped = { ok: true, label: "Undid: Move", paths: ["index.html"], files };
diff --git a/studio/src/hooks/useEditHistoryActions.ts b/studio/src/hooks/useEditHistoryActions.ts
index 5c34ae3f..f5cf9279 100644
--- a/studio/src/hooks/useEditHistoryActions.ts
+++ b/studio/src/hooks/useEditHistoryActions.ts
@@ -1,5 +1,5 @@
// fallow-ignore-file complexity
-import { useCallback, useMemo } from "react";
+import { useCallback, useMemo, useRef } from "react";
import { STUDIO_MOTION_PATH } from "../components/editor/studioMotion";
import { serializeStudioFileMutations } from "../utils/studioFileMutationCoordinator";
import type { RestoreFiles } from "../utils/gsapUndoRestore";
@@ -27,6 +27,8 @@ interface HistoryFileCallbacks {
claimedAfter?: number;
}
export interface EditHistoryHandle {
+ canUndo: boolean;
+ canRedo: boolean;
undo: (cb: HistoryFileCallbacks) => Promise<HistoryResult>;
redo: (cb: HistoryFileCallbacks) => Promise<HistoryResult>;
predict?: (direction: "undo" | "redo") => { id: string; files: RestoreFiles } | null;
@@ -38,7 +40,7 @@ export interface EditHistoryHandle {
}
export interface UseEditHistoryActionsOptions {
- editHistory: Pick<EditHistoryHandle, "undo" | "redo" | "predict" | "claims">;
+ editHistory: Pick<EditHistoryHandle, "undo" | "redo" | "predict" | "claims" | "canUndo" | "canRedo">;
readOptionalProjectFile: (path: string) => Promise<string>;
readProjectFile: (path: string) => Promise<string>;
writeProjectFile: (path: string, content: string) => Promise<void>;
@@ -67,6 +69,8 @@ export function useEditHistoryActions({
activeCompPath,
forceReloadSdkSession,
}: UseEditHistoryActionsOptions) {
+ const historyRef = useRef(editHistory);
+ historyRef.current = editHistory;
const readHistoryFile = useCallback(
(path: string): Promise<string> =>
path === STUDIO_MOTION_PATH ? readOptionalProjectFile(path) : readProjectFile(path),
@@ -82,6 +86,8 @@ export function useEditHistoryActions({
async (direction: "undo" | "redo") => {
const noun = direction === "undo" ? "Undo" : "Redo";
if (direction === "undo" && cancelNewestStudioWaitingPress()) return;
+ const available = direction === "undo" ? historyRef.current.canUndo : historyRef.current.canRedo;
+ if (!available && !(direction === "undo" && hasStudioPendingEdits())) return;
// An edit still saving is newer than any step this tab predicts, so it paints back first.
const pendingEditShown = direction === "undo" ? paintBackNewestStudioPendingEdit() : null;
const predicted = pendingEditShown ? null : (editHistory.predict?.(direction) ?? null);
diff --git a/studio/src/hooks/usePersistentEditHistory.test.ts b/studio/src/hooks/usePersistentEditHistory.test.ts
index da36d4ea..f1fd6fc6 100644
--- a/studio/src/hooks/usePersistentEditHistory.test.ts
+++ b/studio/src/hooks/usePersistentEditHistory.test.ts
@@ -19,6 +19,7 @@ import {
paintBackNewestStudioPendingEdit,
} from "../utils/studioPendingEdits";
import { usePersistentEditHistory } from "./usePersistentEditHistory";
+import { withAvailableHistorySteps } from "../../../shared/studio-history-availability";
const cleanup: Array<() => unknown> = [];
@@ -34,19 +35,21 @@ function tempDir(prefix: string): string {
}
/** The hook over the real history routes and engine, on a project whose index.html reads "A". */
-async function studio({ withHistory = true } = {}) {
+async function studio({ withHistory = true, initialFiles = {} as Record<string, string> } = {}) {
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
const dir = tempDir("hf-studio-history-");
writeFileSync(join(dir, "index.html"), "A");
+ for (const [name, content] of Object.entries(initialFiles)) writeFileSync(join(dir, name), content);
+ const historyRoot = tempDir("hf-studio-history-root-");
const history = await openProjectHistory({
projectDir: dir,
- historyRoot: tempDir("hf-studio-history-root-"),
+ historyRoot,
});
cleanup.push(() => history.close());
const api = createStudioApi({
listProjects: () => [],
resolveProject: (id: string) => (id === "demo" ? { id, dir } : null),
- ...(withHistory && { history: () => history }),
+ ...(withHistory && { history: () => withAvailableHistorySteps(history, historyRoot) }),
} as unknown as StudioApiAdapter);
vi.stubGlobal("fetch", (url: string, init?: RequestInit) =>
api.request(url.replace(/^\/api/, ""), init),
@@ -65,6 +68,21 @@ async function studio({ withHistory = true } = {}) {
return { dir, history, hook: () => hook, file, save, readFile };
}
+it("an undo whose media bytes are missing has the same disabled flags as empty history", async () => {
+ const { dir, history, hook } = await studio({ initialFiles: { "clip.mp4": "original" } });
+ expect(hook().canUndo).toBe(false);
+ expect(hook().canRedo).toBe(false);
+ const window = await history.beginWindow({ kind: "person", name: "You" }, "Overwrite media");
+ writeFileSync(join(dir, "clip.mp4"), "replacement");
+ await window.close();
+ expect(history.next("back", { kind: "person", name: "You" })).toBeDefined();
+ await act(() => hook().noteOutsideChange());
+ await vi.waitFor(() => expect(hook().undoLabel).toBeUndefined());
+ expect(hook().canUndo).toBe(false);
+ expect(hook().canRedo).toBe(false);
+ expect(readFileSync(join(dir, "clip.mp4"), "utf8")).toBe("replacement");
+});
+
it("an edit Studio saved is undone and redone by the project's history, with the preview's before and after", async () => {
const { hook, file, save, readFile } = await studio();
save("B");
diff --git a/studio/src/player/components/useAutomationLanes.save.test.tsx b/studio/src/player/components/useAutomationLanes.save.test.tsx
index 93df77d7..daa6094c 100644
--- a/studio/src/player/components/useAutomationLanes.save.test.tsx
+++ b/studio/src/player/components/useAutomationLanes.save.test.tsx
@@ -97,6 +97,8 @@ function mountLanes(target: TimelineElement, canEdit?: CanEdit, recording = fals
let binding: AutomationLaneBinding | null = null;
let history: ReturnType<typeof useEditHistoryActions> | null = null;
const editHistory = {
+ canUndo: true,
+ canRedo: false,
// In the file queue, like the real step, so saves started meanwhile queue behind it.
undo: async ({ serialize }: Parameters<EditHistoryHandle["undo"]>[0]) => {
const path = undoPath ?? composition;
diff --git a/tests/history.test.ts b/tests/history.test.ts
index a27fa818..19670879 100644
--- a/tests/history.test.ts
+++ b/tests/history.test.ts
@@ -1,8 +1,32 @@
import test from 'node:test';
import assert from 'node:assert/strict';
+import { readFile, writeFile } from 'node:fs/promises';
+import path from 'node:path';
import { startServer } from '../server.ts';
import { fixture } from './fixtures.ts';
+test('the workspace Studio host hides an unrecoverable media step and retains native write validation', { timeout: 60_000 }, () => fixture(async store => {
+ const file = path.join(store.projectDirectory, 'clip.mp4');
+ await writeFile(file, 'original media');
+ const running = await startServer(store, 0);
+ const address = running.server.address(); assert.ok(address && typeof address !== 'string');
+ const base = `http://127.0.0.1:${address.port}`;
+ const request = (action = '', body?: object) => fetch(`${base}/api/projects/project/history${action}`, {
+ ...(body ? { method: 'POST', headers: { 'Content-Type': 'application/json', Origin: base }, body: JSON.stringify(body) } : {}),
+ });
+ try {
+ assert.equal((await request()).status, 200);
+ await writeFile(file, 'replacement media');
+ assert.equal((await request('/checkpoint', {})).status, 200);
+ const view = await (await request()).json();
+ assert.ok(view.entries.some(entry => entry.files.some(file => file.path === 'clip.mp4')));
+ assert.equal(view.back, null);
+ assert.equal(view.forward, null);
+ assert.equal((await request('/step', { direction: 'back' })).status, 409);
+ assert.equal(await readFile(file, 'utf8'), 'replacement media');
+ } finally { await running.close(); }
+}));
+
test('native history retains pinned versions across restart and restores without losing later edits', { timeout: 60_000 }, () => fixture(async store => {
let running = await startServer(store, 0);
let base = '';
diff --git a/tests/studio-history-availability.test.ts b/tests/studio-history-availability.test.ts
new file mode 100644
index 00000000..e41fe108
--- /dev/null
+++ b/tests/studio-history-availability.test.ts
@@ -0,0 +1,104 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtemp, mkdir, writeFile, readFile, rename, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { createStudioApi, openProjectHistory } from '@hyperframes/studio-server';
+import type { ProjectHistory, StudioApiAdapter } from '@hyperframes/studio-server';
+import { withAvailableHistorySteps } from '../shared/studio-history-availability.ts';
+
+const who = { kind: 'person' as const, name: 'You' };
+
+async function fixture(run: (context: {
+ dir: string; root: string; history: ProjectHistory; offered: ProjectHistory; api: ReturnType<typeof createStudioApi>;
+}) => Promise<void>, budgetBytes?: number) {
+ const root = await mkdtemp(path.join(tmpdir(), 'motion-history-availability-'));
+ const dir = path.join(root, 'project');
+ await mkdir(dir);
+ await writeFile(path.join(dir, 'index.html'), 'A');
+ await writeFile(path.join(dir, 'clip.mp4'), 'original media');
+ const history = await openProjectHistory({ projectDir: dir, historyRoot: root, budgetBytes });
+ try {
+ await history.flush();
+ const offered = withAvailableHistorySteps(history, root);
+ const api = createStudioApi({ listProjects: () => [], resolveProject: () => ({ id: 'demo', dir }),
+ history: () => offered } as unknown as StudioApiAdapter);
+ await run({ dir, root, history, offered, api });
+ } finally {
+ await history.close();
+ await rm(root, { recursive: true, force: true });
+ }
+}
+
+test('an unavailable media undo is omitted from the native view while execution still refuses it safely', () => fixture(async ({ dir, history, api }) => {
+ const window = await history.beginWindow(who, 'Overwrite media');
+ await writeFile(path.join(dir, 'clip.mp4'), 'replacement media');
+ const entry = await window.close();
+ assert.ok(entry);
+ assert.equal(history.next('back', who)?.id, entry.id);
+ const view = await (await api.request('/projects/demo/history')).json();
+ assert.equal(view.back, null);
+ assert.equal(view.entries.at(-1).id, entry.id, 'unavailable entries remain visible in version history');
+ const response = await api.request('/projects/demo/history/step', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ direction: 'back' }) });
+ assert.equal(response.status, 409);
+ assert.match((await response.json()).error, /earlier version.*not kept/);
+ assert.equal(await readFile(path.join(dir, 'clip.mp4'), 'utf8'), 'replacement media');
+}));
+
+test('text edits, pending edits and media-reference changes remain undoable and redoable', () => fixture(async ({ dir, history, offered }) => {
+ await writeFile(path.join(dir, 'index.html'), '<video src="clip.mp4"></video>');
+ await history.claim(who, 'Switch reference', ['index.html'], { coalesceKey: 'pending', idleMs: 60_000 });
+ assert.equal(history.list().length, 0);
+ assert.ok(offered.next('back', who));
+ await history.checkpoint();
+ assert.ok((await offered.step('back', who)).ok);
+ assert.ok(offered.next('forward', who));
+ assert.ok((await offered.step('forward', who)).ok);
+ assert.equal(await readFile(path.join(dir, 'index.html'), 'utf8'), '<video src="clip.mp4"></video>');
+}));
+
+test('undoing a newly added media file preserves its redo through aside, and missing redo bytes disable it', () => fixture(async ({ dir, root, history, offered }) => {
+ const window = await history.beginWindow(who, 'Add media');
+ await writeFile(path.join(dir, 'new.mp4'), 'new media');
+ const entry = await window.close();
+ assert.ok(entry);
+ assert.ok(offered.next('back', who));
+ assert.ok((await offered.step('back', who)).ok);
+ assert.ok(offered.next('forward', who));
+ assert.ok((await offered.step('forward', who)).ok);
+ assert.equal(await readFile(path.join(dir, 'new.mp4'), 'utf8'), 'new media');
+ await offered.step('back', who);
+ const hash = entry.files.find(file => file.path === 'new.mp4')!.after!;
+ await rm(path.join(root, history.projectId, 'aside', hash.slice(0, 2), hash));
+ assert.ok(history.next('forward', who));
+ assert.equal(offered.next('forward', who), undefined);
+}));
+
+test('a later writer changing the same file disables the conflicting step', () => fixture(async ({ dir, history, offered }) => {
+ const first = await history.beginWindow(who, 'Person edit');
+ await writeFile(path.join(dir, 'index.html'), 'B'); await first.close();
+ const agent = await history.beginWindow({ kind: 'agent', name: 'Agent' }, 'Agent edit');
+ await writeFile(path.join(dir, 'index.html'), 'C'); await agent.close();
+ assert.ok(history.next('back', who));
+ assert.equal(offered.next('back', who), undefined);
+}));
+
+test('media renames remain available because undo and redo can set the moved file aside first', () => fixture(async ({ dir, history, offered }) => {
+ const window = await history.beginWindow(who, 'Rename media');
+ await rename(path.join(dir, 'clip.mp4'), path.join(dir, 'renamed.mp4'));
+ await window.close();
+ assert.ok(offered.next('back', who));
+ await offered.step('back', who);
+ assert.equal(await readFile(path.join(dir, 'clip.mp4'), 'utf8'), 'original media');
+ assert.ok(offered.next('forward', who));
+ await offered.step('forward', who);
+ assert.equal(await readFile(path.join(dir, 'renamed.mp4'), 'utf8'), 'original media');
+}));
+
+test('a pruned history has no offered undo or redo', () => fixture(async ({ dir, history, offered }) => {
+ const window = await history.beginWindow(who, 'Oversized edit');
+ await writeFile(path.join(dir, 'index.html'), 'B'); await window.close();
+ assert.equal(history.list().length, 0);
+ assert.equal(offered.next('back', who), undefined);
+ assert.equal(offered.next('forward', who), undefined);
+}, 0));