@hyperframes/studio 0.8.75 → 0.8.76

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/dist/assets/hyperframes-player-BkDxgSKG.js +464 -0
  2. package/dist/assets/{index-BiFKcNjs.js → index-COX0scwJ.js} +1 -1
  3. package/dist/assets/{index-BlUYw1MB.js → index-DeHir1up.js} +156 -156
  4. package/dist/assets/{index-HjexPsny.js → index-FmKUmYhC.js} +1 -1
  5. package/dist/{chunk-7BP32G62.js → chunk-IYDE66BY.js} +6 -1
  6. package/dist/chunk-IYDE66BY.js.map +1 -0
  7. package/dist/{domEditingLayers-UKMVYXT6.js → domEditingLayers-2XBFXXSW.js} +4 -2
  8. package/dist/index.d.ts +34 -69
  9. package/dist/index.html +1 -1
  10. package/dist/index.js +4147 -4253
  11. package/dist/index.js.map +1 -1
  12. package/package.json +7 -7
  13. package/src/components/StudioRightPanels.types.ts +0 -2
  14. package/src/components/editor/DomEditOverlay.test.ts +5 -0
  15. package/src/components/editor/LayersPanel.tsx +3 -14
  16. package/src/components/editor/PreviewOverlayProvider.test.tsx +6 -1
  17. package/src/components/editor/domEditing.ts +1 -0
  18. package/src/components/editor/domEditingLayers.test.ts +27 -0
  19. package/src/components/editor/domEditingLayers.ts +9 -0
  20. package/src/components/editor/offCanvasIndicatorRefresh.test.tsx +57 -35
  21. package/src/components/editor/overlayFrameLoop.test.ts +16 -0
  22. package/src/components/editor/overlayFrameLoop.ts +11 -0
  23. package/src/components/editor/usePreviewCompositionRect.test.tsx +6 -1
  24. package/src/components/nle/NLEPreview.test.ts +94 -17
  25. package/src/components/nle/NLEPreview.tsx +14 -0
  26. package/src/components/nle/PreviewPoster.tsx +99 -0
  27. package/src/components/nle/useCanvasZOrderTimelineMirror.test.tsx +30 -49
  28. package/src/components/panels/VariablesPanel.tsx +0 -2
  29. package/src/components/sidebar/CompositionsTab.drag.test.tsx +5 -1
  30. package/src/components/sidebar/CompositionsTab.rootBadge.test.tsx +14 -0
  31. package/src/components/sidebar/CompositionsTab.test.ts +4 -6
  32. package/src/components/sidebar/CompositionsTab.tsx +28 -21
  33. package/src/components/studioColorGradingScope.ts +0 -3
  34. package/src/hooks/domEditDeleteMembers.ts +0 -2
  35. package/src/hooks/gsapScriptCommitTypes.ts +0 -2
  36. package/src/hooks/keyframeCacheAstLoad.test.ts +31 -1
  37. package/src/hooks/keyframeCacheAstLoad.ts +2 -1
  38. package/src/hooks/timelineAudioGroupCreate.ts +0 -1
  39. package/src/hooks/timelineEditingHelpers.ts +0 -3
  40. package/src/hooks/timelineTimingSync.ts +0 -1
  41. package/src/hooks/timelineTrackVisibility.ts +0 -1
  42. package/src/hooks/useBlockHandlers.ts +0 -2
  43. package/src/hooks/useClipboard.test.ts +69 -10
  44. package/src/hooks/useClipboard.ts +28 -19
  45. package/src/hooks/useDomEditCommits.test.tsx +0 -1
  46. package/src/hooks/useDomEditCommits.ts +0 -4
  47. package/src/hooks/useEditHistoryActions.test.tsx +31 -14
  48. package/src/hooks/useEditHistoryActions.ts +12 -7
  49. package/src/hooks/useEditorSave.ts +0 -3
  50. package/src/hooks/useElementLifecycleOps.ts +0 -1
  51. package/src/hooks/useEnableKeyframes.test.ts +9 -1
  52. package/src/hooks/useFileManager.ts +0 -2
  53. package/src/hooks/useGroupCommits.ts +0 -1
  54. package/src/hooks/useGsapScriptCommits.ts +0 -1
  55. package/src/hooks/useLintModal.test.tsx +34 -1
  56. package/src/hooks/useLintModal.ts +32 -30
  57. package/src/hooks/usePersistentEditHistory.test.ts +221 -315
  58. package/src/hooks/usePersistentEditHistory.ts +155 -342
  59. package/src/hooks/usePopulateKeyframeCacheForFile.test.tsx +2 -0
  60. package/src/hooks/usePreviewPersistence.ts +0 -2
  61. package/src/hooks/useProjectCompositionVariables.ts +1 -3
  62. package/src/hooks/useRazorSplit.history.test.tsx +46 -67
  63. package/src/hooks/useRazorSplit.test.ts +17 -47
  64. package/src/hooks/useRenderClipContent.test.ts +29 -0
  65. package/src/hooks/useRenderClipContent.ts +6 -3
  66. package/src/hooks/useSdkSession.lifecycle.test.tsx +34 -4
  67. package/src/hooks/useSdkSession.ts +8 -2
  68. package/src/hooks/useSlideshowPersist.ts +0 -2
  69. package/src/hooks/useStudioContextValue.ts +6 -1
  70. package/src/hooks/useTimelineAssetDropOps.ts +0 -1
  71. package/src/hooks/useTimelineDeleteOps.ts +0 -1
  72. package/src/hooks/useTimelineEditing.test.tsx +0 -1
  73. package/src/hooks/useTimelineEditingTypes.ts +0 -2
  74. package/src/hostMount.test.tsx +53 -22
  75. package/src/main.tsx +3 -0
  76. package/src/player/components/CompositionThumbnail.tsx +14 -0
  77. package/src/player/components/Player.test.ts +49 -0
  78. package/src/player/components/Player.tsx +21 -7
  79. package/src/player/components/timelineClipDragCommit.test.ts +7 -39
  80. package/src/player/hooks/timelineDomBinding.test.ts +50 -0
  81. package/src/player/hooks/timelineSyncHydration.test.ts +25 -1
  82. package/src/player/hooks/timelineSyncHydration.ts +3 -3
  83. package/src/player/hooks/useShadowPreviewReload.ts +1 -0
  84. package/src/player/hooks/useTimelinePlayer.play.test.ts +120 -0
  85. package/src/player/hooks/useTimelinePlayer.ts +1 -0
  86. package/src/player/hooks/useTimelineSyncCallbacks.ts +2 -0
  87. package/src/player/lib/timelineElementHelpers.ts +45 -9
  88. package/src/player/store/playerStore.test.ts +35 -1
  89. package/src/player/store/playerStore.ts +29 -0
  90. package/src/player/store/readinessSlice.ts +34 -6
  91. package/src/utils/blockInstaller.ts +0 -3
  92. package/src/utils/previewPrefetch.test.ts +22 -0
  93. package/src/utils/previewPrefetch.ts +14 -0
  94. package/src/utils/razorSplitTransaction.test.ts +0 -1
  95. package/src/utils/razorSplitTransaction.ts +1 -1
  96. package/src/utils/sdkEditTransaction.ts +0 -3
  97. package/src/utils/studioFileHistory.test.ts +0 -9
  98. package/src/utils/studioFileHistory.ts +1 -5
  99. package/src/utils/timelineCompositionInsert.ts +0 -1
  100. package/dist/assets/hyperframes-player-WbBVbWuO.js +0 -464
  101. package/dist/chunk-7BP32G62.js.map +0 -1
  102. package/src/hooks/usePersistentEditHistory.projectOwnership.test.tsx +0 -60
  103. package/src/utils/editHistory.test.ts +0 -534
  104. package/src/utils/editHistory.ts +0 -236
  105. package/src/utils/editHistoryStorage.test.ts +0 -37
  106. package/src/utils/editHistoryStorage.ts +0 -99
  107. /package/dist/{domEditingLayers-UKMVYXT6.js.map → domEditingLayers-2XBFXXSW.js.map} +0 -0
@@ -2,6 +2,7 @@ import { buildProjectApiPath } from "../utils/projectRouting";
2
2
  import { useState, useCallback, useEffect, useRef, useMemo } from "react";
3
3
  import type { LintFinding } from "../components/LintModal";
4
4
  import { usePlayerStore } from "../player";
5
+ import { isPreviewBooted, whenPreviewBooted } from "../player/store/playerStore";
5
6
 
6
7
  interface RawFinding {
7
8
  severity?: string;
@@ -23,6 +24,12 @@ function parseFinding(f: RawFinding): LintFinding & { elementId?: string; file?:
23
24
  };
24
25
  }
25
26
 
27
+ async function fetchLintFindings(projectId: string) {
28
+ const res = await fetch(buildProjectApiPath(projectId, `/lint`));
29
+ const data = await res.json();
30
+ return ((data.findings ?? []) as RawFinding[]).map(parseFinding);
31
+ }
32
+
26
33
  export function useLintModal(projectId: string | null, refreshKey?: number) {
27
34
  const [lintModal, setLintModal] = useState<LintFinding[] | null>(null);
28
35
  const [linting, setLinting] = useState(false);
@@ -31,33 +38,28 @@ export function useLintModal(projectId: string | null, refreshKey?: number) {
31
38
  >([]);
32
39
  const autoLintRanRef = useRef(false);
33
40
 
34
- const runLint = useCallback(
35
- async (opts?: { background?: boolean }) => {
36
- if (!projectId) return;
37
- if (!opts?.background) setLinting(true);
38
- try {
39
- const res = await fetch(buildProjectApiPath(projectId, `/lint`));
40
- const data = await res.json();
41
- const parsed = ((data.findings ?? []) as RawFinding[]).map(parseFinding);
42
- if (opts?.background) {
43
- setBackgroundFindings(parsed);
44
- } else {
45
- setLintModal(parsed);
46
- setBackgroundFindings(parsed);
47
- }
48
- } catch (err) {
49
- if (!opts?.background) {
50
- const msg = err instanceof Error ? err.message : String(err);
51
- setLintModal([{ severity: "error", message: `Failed to run lint: ${msg}` }]);
52
- }
53
- } finally {
54
- if (!opts?.background) setLinting(false);
55
- }
56
- },
57
- [projectId],
58
- );
41
+ const runBackgroundLint = useCallback(async () => {
42
+ if (!projectId) return;
43
+ if (!isPreviewBooted(projectId) && !(await whenPreviewBooted(projectId))) return;
44
+ try {
45
+ setBackgroundFindings(await fetchLintFindings(projectId));
46
+ } catch {}
47
+ }, [projectId]);
59
48
 
60
- const handleLint = useCallback(() => runLint(), [runLint]);
49
+ const handleLint = useCallback(async () => {
50
+ if (!projectId) return;
51
+ setLinting(true);
52
+ try {
53
+ const parsed = await fetchLintFindings(projectId);
54
+ setLintModal(parsed);
55
+ setBackgroundFindings(parsed);
56
+ } catch (err) {
57
+ const msg = err instanceof Error ? err.message : String(err);
58
+ setLintModal([{ severity: "error", message: `Failed to run lint: ${msg}` }]);
59
+ } finally {
60
+ setLinting(false);
61
+ }
62
+ }, [projectId]);
61
63
 
62
64
  const prevProjectIdRef = useRef(projectId);
63
65
  useEffect(() => {
@@ -67,14 +69,14 @@ export function useLintModal(projectId: string | null, refreshKey?: number) {
67
69
  }
68
70
  if (!projectId || autoLintRanRef.current) return;
69
71
  autoLintRanRef.current = true;
70
- void runLint({ background: true });
71
- }, [projectId, runLint]);
72
+ void runBackgroundLint();
73
+ }, [projectId, runBackgroundLint]);
72
74
 
73
75
  useEffect(() => {
74
76
  if (!projectId || !refreshKey) return;
75
- const timer = setTimeout(() => void runLint({ background: true }), 1000);
77
+ const timer = setTimeout(() => void runBackgroundLint(), 1000);
76
78
  return () => clearTimeout(timer);
77
- }, [projectId, refreshKey, runLint]);
79
+ }, [projectId, refreshKey, runBackgroundLint]);
78
80
 
79
81
  const closeLintModal = useCallback(() => setLintModal(null), []);
80
82
 
@@ -1,337 +1,243 @@
1
- import { describe, expect, it, vi } from "vitest";
2
- import { createEmptyEditHistory } from "../utils/editHistory";
3
- import type { EditHistoryStorageAdapter } from "../utils/editHistoryStorage";
4
- import { createMemoryEditHistoryStorage } from "../utils/editHistoryStorage";
1
+ // @vitest-environment happy-dom
2
+ import { act, createElement } from "react";
3
+ import { createRoot } from "react-dom/client";
4
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { afterEach, expect, it, vi } from "vitest";
5
8
  import {
6
- serializeStudioFileMutation,
7
- serializeStudioFileMutations,
8
- } from "../utils/studioFileMutationCoordinator";
9
- import {
10
- createPersistentEditHistoryController,
11
- createPersistentEditHistoryStore,
12
- } from "./usePersistentEditHistory";
13
-
14
- describe("createPersistentEditHistoryController", () => {
15
- it("records history and reloads it for the same project", async () => {
16
- const storage = createMemoryEditHistoryStorage();
17
- const first = await createPersistentEditHistoryController({
18
- projectId: "project-1",
19
- storage,
20
- now: () => 100,
21
- onChange: () => {},
22
- });
23
-
24
- await first.recordEdit({
25
- label: "Move layer",
26
- kind: "manual",
27
- files: { "index.html": { before: "a", after: "b" } },
28
- });
29
-
30
- const second = await createPersistentEditHistoryController({
31
- projectId: "project-1",
32
- storage,
33
- now: () => 200,
34
- onChange: () => {},
35
- });
9
+ createStudioApi,
10
+ fileContentVersion,
11
+ identifyFileWrite,
12
+ openProjectHistory,
13
+ type StudioApiAdapter,
14
+ } from "@hyperframes/studio-server";
15
+ import { consumeStudioWriteToken } from "../utils/studioFileVersion";
16
+ import { usePersistentEditHistory } from "./usePersistentEditHistory";
17
+
18
+ const cleanup: Array<() => unknown> = [];
19
+
20
+ afterEach(async () => {
21
+ for (const step of cleanup.splice(0).reverse()) await step();
22
+ vi.unstubAllGlobals();
23
+ });
36
24
 
37
- expect(second.snapshot().canUndo).toBe(true);
38
- expect(second.snapshot().undoLabel).toBe("Move layer");
39
- expect(second.snapshot().undoPaths).toEqual(["index.html"]);
25
+ function tempDir(prefix: string): string {
26
+ const dir = mkdtempSync(join(tmpdir(), prefix));
27
+ cleanup.push(() => rmSync(dir, { recursive: true, force: true }));
28
+ return dir;
29
+ }
30
+
31
+ /** The hook over the real history routes and engine, on a project whose index.html reads "A". */
32
+ async function studio({ withHistory = true } = {}) {
33
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
34
+ const dir = tempDir("hf-studio-history-");
35
+ writeFileSync(join(dir, "index.html"), "A");
36
+ const history = await openProjectHistory({
37
+ projectDir: dir,
38
+ historyRoot: tempDir("hf-studio-history-root-"),
40
39
  });
41
-
42
- it("undo applies files through the provided callback and persists redo state", async () => {
43
- const storage = createMemoryEditHistoryStorage();
44
- const controller = await createPersistentEditHistoryController({
45
- projectId: "project-1",
46
- storage,
47
- now: () => 100,
48
- onChange: () => {},
49
- });
50
- await controller.recordEdit({
51
- label: "Move layer",
52
- kind: "manual",
53
- files: { "index.html": { before: "a", after: "b" } },
54
- });
55
-
56
- const result = await controller.undo({
57
- readFile: async (path) => {
58
- expect(path).toBe("index.html");
59
- return "b";
60
- },
61
- writeFile: async (path, content) => {
62
- expect(path).toBe("index.html");
63
- expect(content).toBe("a");
64
- },
65
- });
66
- expect(result.ok).toBe(true);
67
- expect(result.paths).toEqual(["index.html"]);
68
-
69
- expect(controller.snapshot().canUndo).toBe(false);
70
- expect(controller.snapshot().canRedo).toBe(true);
71
- expect(controller.snapshot().redoPaths).toEqual(["index.html"]);
40
+ cleanup.push(() => history.close());
41
+ const api = createStudioApi({
42
+ listProjects: () => [],
43
+ resolveProject: (id: string) => (id === "demo" ? { id, dir } : null),
44
+ ...(withHistory && { history: () => history }),
45
+ } as unknown as StudioApiAdapter);
46
+ vi.stubGlobal("fetch", (url: string, init?: RequestInit) =>
47
+ api.request(url.replace(/^\/api/, ""), init),
48
+ );
49
+ let hook!: ReturnType<typeof usePersistentEditHistory>;
50
+ function Harness() {
51
+ hook = usePersistentEditHistory({ projectId: "demo" });
52
+ return null;
53
+ }
54
+ const root = createRoot(document.createElement("div"));
55
+ await act(async () => root.render(createElement(Harness)));
56
+ cleanup.push(() => act(() => root.unmount()));
57
+ const file = () => readFileSync(join(dir, "index.html"), "utf8");
58
+ const save = (content: string) => writeFileSync(join(dir, "index.html"), content);
59
+ const readFile = async (path: string) => readFileSync(join(dir, path), "utf8");
60
+ return { dir, hook: () => hook, file, save, readFile };
61
+ }
62
+
63
+ it("an edit Studio saved is undone and redone by the project's history, with the preview's before and after", async () => {
64
+ const { hook, file, save, readFile } = await studio();
65
+ save("B");
66
+ await act(() =>
67
+ hook().recordEdit({
68
+ label: "Moved Title",
69
+ files: { "index.html": { before: "A", after: "B" } },
70
+ }),
71
+ );
72
+ await vi.waitFor(() => expect(hook().undoLabel).toBe("Moved Title"));
73
+
74
+ const undone = await act(() => hook().undo({ readFile }));
75
+ expect(undone).toEqual({
76
+ ok: true,
77
+ label: "Undid: Moved Title",
78
+ paths: ["index.html"],
79
+ files: { "index.html": { previous: "B", restored: "A" } },
72
80
  });
81
+ expect(file()).toBe("A");
73
82
 
74
- it("keeps in-memory history when storage saves fail", async () => {
75
- const storage: EditHistoryStorageAdapter = {
76
- async get() {
77
- return null;
78
- },
79
- async set() {
80
- throw new Error("IndexedDB unavailable");
81
- },
82
- async delete() {},
83
- };
84
- const controller = await createPersistentEditHistoryController({
85
- projectId: "project-1",
86
- storage,
87
- now: () => 100,
88
- onChange: () => {},
89
- });
83
+ await vi.waitFor(() => expect(hook().canRedo).toBe(true));
84
+ const redone = await act(() => hook().redo({ readFile }));
85
+ expect(redone).toMatchObject({ ok: true, label: "Redid: Moved Title" });
86
+ expect(file()).toBe("B");
87
+ });
90
88
 
91
- await expect(
92
- controller.recordEdit({
93
- label: "Move layer",
94
- kind: "manual",
95
- files: { "index.html": { before: "a", after: "b" } },
89
+ it("a drag's edits under one key undo as one step, even before the drag goes idle", async () => {
90
+ const { hook, file, save, readFile } = await studio();
91
+ const writes: Array<[before: string, after: string]> = [
92
+ ["A", "B"],
93
+ ["B", "C"],
94
+ ];
95
+ for (const [before, after] of writes) {
96
+ save(after);
97
+ await act(() =>
98
+ hook().recordEdit({
99
+ label: "Dragged Title",
100
+ coalesceKey: "drag",
101
+ coalesceMs: 60_000,
102
+ files: { "index.html": { before, after } },
96
103
  }),
97
- ).resolves.toBeUndefined();
98
-
99
- expect(controller.snapshot().canUndo).toBe(true);
104
+ );
105
+ }
106
+ // The held drag is not in the history's list yet: only its own paths say what to read before the step.
107
+ expect(hook().undoLabel).toBeUndefined();
108
+ const undone = await act(() => hook().undo({ readFile }));
109
+ expect(undone).toMatchObject({
110
+ ok: true,
111
+ label: "Undid: Dragged Title",
112
+ files: { "index.html": { previous: "C", restored: "A" } },
100
113
  });
114
+ expect(file()).toBe("A");
115
+ });
101
116
 
102
- it("serializes concurrent record edits against the latest state", async () => {
103
- const storage = createMemoryEditHistoryStorage();
104
- let timestamp = 100;
105
- const store = createPersistentEditHistoryStore({
106
- projectId: "project-1",
107
- storage,
108
- initialState: createEmptyEditHistory(),
109
- now: () => timestamp++,
110
- onChange: () => {},
111
- });
112
-
113
- await Promise.all([
114
- store.recordEdit({
115
- label: "Move layer",
116
- kind: "manual",
117
- files: { "index.html": { before: "a", after: "b" } },
118
- }),
119
- store.recordEdit({
120
- label: "Resize layer",
121
- kind: "manual",
122
- files: { "index.html": { before: "b", after: "c" } },
123
- }),
124
- ]);
125
-
126
- expect(store.snapshot().state.undo.map((entry) => entry.label)).toEqual([
127
- "Move layer",
128
- "Resize layer",
129
- ]);
130
- });
117
+ it("an agent's edit made seconds before Studio's stays the agent's: Cmd+Z undoes only Studio's", async () => {
118
+ const { hook, file, save, readFile } = await studio();
119
+ save("B");
120
+ await act(() => hook().recordEdit({ label: "sweep", files: {} }));
121
+ save("C");
122
+ await act(() =>
123
+ hook().recordEdit({
124
+ label: "Moved Title",
125
+ files: { "index.html": { before: "B", after: "C" } },
126
+ }),
127
+ );
128
+ expect(await act(() => hook().undo({ readFile }))).toMatchObject({ label: "Undid: Moved Title" });
129
+ expect(file()).toBe("B");
130
+ });
131
131
 
132
- it("still coalesces concurrent source edits that share a coalesce key", async () => {
133
- const storage = createMemoryEditHistoryStorage();
134
- let timestamp = 100;
135
- const store = createPersistentEditHistoryStore({
136
- projectId: "project-1",
137
- storage,
138
- initialState: createEmptyEditHistory(),
139
- now: () => timestamp++,
140
- onChange: () => {},
141
- });
132
+ it("an undo's writes carry the write token Studio marked, so their echo is not read as an outside edit", async () => {
133
+ const { dir, hook, save, readFile } = await studio();
134
+ save("B");
135
+ await act(() =>
136
+ hook().recordEdit({
137
+ label: "Moved Title",
138
+ files: { "index.html": { before: "A", after: "B" } },
139
+ }),
140
+ );
141
+ await act(() => hook().undo({ readFile }));
142
+ const receipt = identifyFileWrite(join(dir, "index.html"), fileContentVersion("A"));
143
+ expect(consumeStudioWriteToken(receipt?.writeToken ?? null)).toBe(true);
144
+ });
142
145
 
143
- await Promise.all([
144
- store.recordEdit({
145
- label: "Edit source",
146
- kind: "source",
147
- coalesceKey: "source:index.html",
148
- files: { "index.html": { before: "a", after: "b" } },
149
- }),
150
- store.recordEdit({
151
- label: "Edit source",
152
- kind: "source",
153
- coalesceKey: "source:index.html",
154
- files: { "index.html": { before: "b", after: "c" } },
155
- }),
156
- ]);
146
+ it("without a history on the server an edit still saves, and there is nothing to undo", async () => {
147
+ const { hook, file, save, readFile } = await studio({ withHistory: false });
148
+ save("B");
149
+ await act(() =>
150
+ hook().recordEdit({
151
+ label: "Moved Title",
152
+ files: { "index.html": { before: "A", after: "B" } },
153
+ }),
154
+ );
155
+ expect(hook().canUndo).toBe(false);
156
+ expect(await act(() => hook().undo({ readFile }))).toEqual({ ok: false, reason: "empty" });
157
+ expect(file()).toBe("B");
158
+ });
157
159
 
158
- expect(store.snapshot().state.undo).toHaveLength(1);
159
- expect(store.snapshot().state.undo[0].files["index.html"].before).toBe("a");
160
- expect(store.snapshot().state.undo[0].files["index.html"].after).toBe("c");
160
+ /** Answers requests to `route` with `reply` instead of the engine, every other request as before; returns the undo. */
161
+ function answer(route: "/history/step" | "/history/claim", status: number, reply: object | string) {
162
+ const real = globalThis.fetch;
163
+ vi.stubGlobal("fetch", (url: string, init?: RequestInit) =>
164
+ url.endsWith(route)
165
+ ? Promise.resolve(
166
+ new Response(typeof reply === "string" ? reply : JSON.stringify(reply), { status }),
167
+ )
168
+ : real(url, init),
169
+ );
170
+ return () => vi.stubGlobal("fetch", real);
171
+ }
172
+
173
+ it("a step the server could not take says why, instead of reading as nothing to undo", async () => {
174
+ const { hook, readFile } = await studio();
175
+ answer("/history/step", 500, { error: "disk full" });
176
+ expect(await act(() => hook().undo({ readFile }))).toEqual({
177
+ ok: false,
178
+ reason: "failed",
179
+ message: "disk full",
161
180
  });
181
+ });
162
182
 
163
- it("reads undo hashes from the live top entry during queued undo calls", async () => {
164
- const storage = createMemoryEditHistoryStorage();
165
- let timestamp = 100;
166
- const store = createPersistentEditHistoryStore({
167
- projectId: "project-1",
168
- storage,
169
- initialState: createEmptyEditHistory(),
170
- now: () => timestamp++,
171
- onChange: () => {},
172
- });
173
- await store.recordEdit({
174
- label: "Edit first file",
175
- kind: "manual",
176
- files: { "first.html": { before: "first-before", after: "first-after" } },
177
- });
178
- await store.recordEdit({
179
- label: "Edit second file",
180
- kind: "manual",
181
- files: { "second.html": { before: "second-before", after: "second-after" } },
182
- });
183
-
184
- const files: Record<string, string> = {
185
- "first.html": "first-after",
186
- "second.html": "second-after",
187
- };
188
- const readPaths: string[] = [];
189
-
190
- await Promise.all([
191
- store.undo({
192
- readFile: async (path) => {
193
- readPaths.push(path);
194
- return files[path];
195
- },
196
- writeFile: async (path, content) => {
197
- files[path] = content;
198
- },
199
- }),
200
- store.undo({
201
- readFile: async (path) => {
202
- readPaths.push(path);
203
- return files[path];
204
- },
205
- writeFile: async (path, content) => {
206
- files[path] = content;
207
- },
208
- }),
209
- ]);
210
-
211
- expect(readPaths).toEqual(["second.html", "first.html"]);
212
- expect(files).toEqual({
213
- "first.html": "first-before",
214
- "second.html": "second-before",
215
- });
216
- expect(store.snapshot().canUndo).toBe(false);
217
- expect(store.snapshot().canRedo).toBe(true);
183
+ it("a refused step names the files that changed since its edit", async () => {
184
+ const { hook, save, readFile } = await studio();
185
+ save("B");
186
+ await act(() =>
187
+ hook().recordEdit({
188
+ label: "Moved Title",
189
+ files: { "index.html": { before: "A", after: "B" } },
190
+ }),
191
+ );
192
+ await vi.waitFor(() => expect(hook().undoLabel).toBe("Moved Title"));
193
+ answer("/history/step", 200, { ok: false, conflict: { files: ["index.html"], newer: [] } });
194
+ expect(await act(() => hook().undo({ readFile }))).toEqual({
195
+ ok: false,
196
+ reason: "content-mismatch",
197
+ paths: ["index.html"],
218
198
  });
199
+ });
219
200
 
220
- it("waits for same-file mutations before checking an undo hash", async () => {
221
- const storage = createMemoryEditHistoryStorage();
222
- const store = createPersistentEditHistoryStore({
223
- projectId: "project-1",
224
- storage,
225
- initialState: createEmptyEditHistory(),
226
- now: () => 100,
227
- onChange: () => {},
228
- });
229
- await store.recordEdit({
230
- label: "Edit source",
231
- kind: "source",
232
- files: { "index.html": { before: "before", after: "after" } },
233
- });
234
-
235
- let disk = "after";
236
- let release!: () => void;
237
- const blocked = new Promise<void>((resolve) => {
238
- release = resolve;
239
- });
240
- const writeFile = vi.fn(async (_path: string, content: string) => {
241
- disk = content;
242
- });
243
- const priorMutation = serializeStudioFileMutation(writeFile, "index.html", async () => {
244
- await blocked;
245
- disk = "newer-edit";
246
- });
247
- const readFile = vi.fn(async () => disk);
248
- const undo = store.undo({
249
- readFile,
250
- writeFile,
251
- serialize: (paths, task) => serializeStudioFileMutations(writeFile, paths, task),
252
- });
253
-
254
- await Promise.resolve();
255
- expect(readFile).not.toHaveBeenCalled();
256
- release();
257
- await priorMutation;
258
- await expect(undo).resolves.toMatchObject({ ok: false, reason: "content-mismatch" });
259
- expect(disk).toBe("newer-edit");
260
- expect(writeFile).not.toHaveBeenCalled();
261
- expect(store.snapshot().canUndo).toBe(true);
201
+ it("a claim the server refused is logged, and the write stays undoable as a change made outside", async () => {
202
+ const { hook, file, save, readFile } = await studio();
203
+ const logged = vi.spyOn(console, "error").mockImplementation(() => {});
204
+ cleanup.push(() => logged.mockRestore());
205
+ const restoreFetch = answer("/history/claim", 500, { error: "disk full" });
206
+ save("B");
207
+ await act(() =>
208
+ hook().recordEdit({
209
+ label: "Moved Title",
210
+ files: { "index.html": { before: "A", after: "B" } },
211
+ }),
212
+ );
213
+ expect(logged).toHaveBeenCalledWith('"Moved Title" was not recorded as your edit: disk full');
214
+ restoreFetch();
215
+ expect(await act(() => hook().undo({ readFile }))).toMatchObject({
216
+ ok: true,
217
+ label: "Undid: Changed outside the app",
262
218
  });
219
+ expect(file()).toBe("A");
220
+ });
263
221
 
264
- it("returns per-file restored/previous content so the preview can soft-apply", async () => {
265
- const storage = createMemoryEditHistoryStorage();
266
- const store = createPersistentEditHistoryStore({
267
- projectId: "project-1",
268
- storage,
269
- initialState: createEmptyEditHistory(),
270
- now: () => 100,
271
- onChange: () => {},
272
- });
273
- await store.recordEdit({
274
- label: "Move layer",
275
- kind: "manual",
276
- files: { "index.html": { before: "OLD", after: "NEW" } },
277
- });
278
- const disk: Record<string, string> = { "index.html": "NEW" };
279
- const undo = await store.undo({
280
- readFile: async (p) => disk[p],
281
- writeFile: async (p, c) => {
282
- disk[p] = c;
283
- },
284
- });
285
- // `restored` = bytes written (the undo target), `previous` = the current live bytes.
286
- expect(undo.files).toEqual({ "index.html": { previous: "NEW", restored: "OLD" } });
287
-
288
- const redo = await store.redo({
289
- readFile: async (p) => disk[p],
290
- writeFile: async (p, c) => {
291
- disk[p] = c;
292
- },
293
- });
294
- expect(redo.files).toEqual({ "index.html": { previous: "OLD", restored: "NEW" } });
222
+ it("a step whose reply cannot be read says so, instead of throwing", async () => {
223
+ const { hook, readFile } = await studio();
224
+ answer("/history/step", 200, "<html>");
225
+ expect(await act(() => hook().undo({ readFile }))).toEqual({
226
+ ok: false,
227
+ reason: "failed",
228
+ message: "The history's reply was unreadable.",
295
229
  });
230
+ });
296
231
 
297
- it("rolls back files when an undo write fails partway through", async () => {
298
- const storage = createMemoryEditHistoryStorage();
299
- const store = createPersistentEditHistoryStore({
300
- projectId: "project-1",
301
- storage,
302
- initialState: createEmptyEditHistory(),
303
- now: () => 100,
304
- onChange: () => {},
305
- });
306
- await store.recordEdit({
307
- label: "Edit files",
308
- kind: "manual",
309
- files: {
310
- "first.html": { before: "first-before", after: "first-after" },
311
- "second.html": { before: "second-before", after: "second-after" },
312
- },
313
- });
314
-
315
- const files: Record<string, string> = {
316
- "first.html": "first-after",
317
- "second.html": "second-after",
318
- };
319
- const result = store.undo({
320
- readFile: async (path) => files[path],
321
- writeFile: async (path, content) => {
322
- if (path === "second.html" && content === "second-before") {
323
- throw new Error("write failed");
324
- }
325
- files[path] = content;
326
- },
327
- });
328
-
329
- await expect(result).rejects.toThrow("write failed");
330
- expect(files).toEqual({
331
- "first.html": "first-after",
332
- "second.html": "second-after",
333
- });
334
- expect(store.snapshot().undoLabel).toBe("Edit files");
335
- expect(store.snapshot().canRedo).toBe(false);
232
+ it("a step that cannot reach the server says so", async () => {
233
+ const { hook, readFile } = await studio();
234
+ const real = globalThis.fetch;
235
+ vi.stubGlobal("fetch", (url: string, init?: RequestInit) =>
236
+ url.endsWith("/history/step") ? Promise.reject(new TypeError("fetch failed")) : real(url, init),
237
+ );
238
+ expect(await act(() => hook().undo({ readFile }))).toEqual({
239
+ ok: false,
240
+ reason: "failed",
241
+ message: "Studio could not reach its server.",
336
242
  });
337
243
  });