Skip to content

Commit 9d0a295

Browse files
# Conflicts: # skills-manifest.json
2 parents 0f80cdd + 618c486 commit 9d0a295

15 files changed

Lines changed: 199 additions & 19 deletions

File tree

‎packages/cli/src/cli.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ import {
8888
markCommandDelivered,
8989
} from "./utils/render-success-state.js";
9090
import { resolveCommandUsage, type ResolvedCommandUsage } from "./utils/commandUsageResolution.js";
91-
import { closestMatch, synonymMatch } from "./utils/didYouMean.js";
91+
import { closestMatch, fileHint, synonymMatch } from "./utils/didYouMean.js";
9292
import { jsonErrorBody, watchOutput, writeJsonFailure } from "./utils/jsonError.js";
9393
import { isDevMode } from "./utils/env.js";
9494
import {
@@ -546,14 +546,15 @@ async function unknownCommandError(requested: ResolvedCommandUsage): Promise<Cli
546546
const match =
547547
(requested.path.length === 0 ? synonymMatch(word, names) : undefined) ??
548548
closestMatch(word, names);
549+
const hint = match ? `Did you mean '${group} ${match}'?` : fileHint(word, requested.path, names);
549550
console.error(`Unknown command: ${word}`);
550-
if (match) console.error(`Did you mean '${group} ${match}'?`);
551+
if (hint) console.error(hint);
551552
console.error("");
552553
await showUsage(requested.command, requested.parent, console.error);
553554
return new CliUsageError(`Unknown command: ${word}`, {
554555
presented: true,
555556
code: "unknown_command",
556-
hint: match ? `Did you mean '${group} ${match}'?` : undefined,
557+
hint,
557558
});
558559
}
559560

‎packages/cli/src/commands/diff.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ export default defineCommand({
255255
if (json)
256256
console.log(formatJson(withMeta({ ok: false, error: message, ...(fix ? { fix } : {}) })));
257257
else console.error(`${c.error("✗")} ${message}${fix ? `\n Fix: ${fix}` : ""}`);
258-
failCommand();
258+
failCommand(1, err);
259259
} finally {
260260
scheduleCliExit(exitCode);
261261
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { describe, expect, it, vi } from "vitest";
2+
import { runMeasure } from "./command.js";
3+
4+
describe("runMeasure", () => {
5+
it("keeps the real error as the failure's cause, so telemetry reports it", async () => {
6+
const log = vi.spyOn(console, "log").mockImplementation(() => {});
7+
const real = new Error("ffmpeg: no video stream");
8+
const thrown = await runMeasure(() => {
9+
throw real;
10+
}).catch((err: unknown) => err);
11+
log.mockRestore();
12+
expect(thrown).toBeInstanceOf(Error);
13+
expect(thrown instanceof Error && thrown.cause).toBe(real);
14+
});
15+
});

‎packages/cli/src/measure/command.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ export async function runMeasure(work: () => object | Promise<object>): Promise<
2525
),
2626
);
2727
if (process.stdout.isTTY) console.error(`${c.error("✗")} ${normalizeErrorMessage(err)}`);
28-
failCommand();
28+
failCommand(1, err);
2929
}
3030
}
3131

‎packages/cli/src/utils/didYouMean.test.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { describe, expect, it } from "vitest";
2-
import { closestMatch } from "./didYouMean.js";
2+
import { closestMatch, fileHint } from "./didYouMean.js";
33

44
describe("closestMatch", () => {
55
const commands = ["render", "preview", "publish", "lint", "check", "help"];
@@ -22,3 +22,19 @@ describe("closestMatch", () => {
2222
expect(closestMatch("out", ["output", "fps", "quality"])).toBe("output");
2323
});
2424
});
25+
26+
describe("fileHint", () => {
27+
const ops = ["probe", "cuts"];
28+
29+
it("names the commands to put before a file given to a group", () => {
30+
expect(fileHint("package.json", ["measure"], ops)).toBe(
31+
"'package.json' is a file; name a command first: 'hyperframes measure <probe|cuts> package.json'.",
32+
);
33+
});
34+
35+
it("stays quiet at the root, for a missing file, and for a group with no commands", () => {
36+
expect(fileHint("package.json", [], ops)).toBeUndefined();
37+
expect(fileHint("no-such-file.mp4", ["measure"], ops)).toBeUndefined();
38+
expect(fileHint("package.json", ["measure"], [])).toBeUndefined();
39+
});
40+
});

‎packages/cli/src/utils/didYouMean.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { existsSync } from "node:fs";
2+
13
function editDistance(a: string, b: string): number {
24
let previous = Array.from({ length: b.length + 1 }, (_, i) => i);
35
for (let i = 1; i <= a.length; i++) {
@@ -56,3 +58,9 @@ export function synonymMatch(input: string, candidates: Iterable<string>): strin
5658
const target = COMMAND_SYNONYMS[input];
5759
return target !== undefined && [...candidates].includes(target) ? target : undefined;
5860
}
61+
62+
export function fileHint(word: string, path: string[], names: string[]): string | undefined {
63+
if (path.length === 0 || names.length === 0 || !existsSync(word)) return undefined;
64+
const group = ["hyperframes", ...path].join(" ");
65+
return `'${word}' is a file; name a command first: '${group} <${names.join("|")}> ${word}'.`;
66+
}

‎packages/studio/src/player/hooks/useShadowPreviewReload.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import {
2020
} from "./useTimelineSyncCallbacks";
2121
import type { IframeWindow, PlaybackAdapter } from "../lib/playbackTypes";
2222
import { setPreviewReloading } from "../previewReloading";
23+
import { studioFileRevision } from "../../utils/studioFileVersion";
2324
import { announcePreviewPromoted } from "../sceneSwap";
2425
import { afterStudioPendingEdits, isStudioEditSaving } from "../../utils/studioPendingEdits";
2526
import { usePlayerStore } from "../store/playerStore";
@@ -117,6 +118,7 @@ export function useShadowPreviewReload({
117118
const stopHoldRef = useRef<() => void>(() => {});
118119
const shadowUrlRef = useRef("");
119120
const savesAtRequestRef = useRef(0);
121+
const revisionAtRequestRef = useRef(0);
120122
const beginShadowReloadRef = useRef<(url: string) => void>(() => {});
121123
const retry = useShadowReloadRetry(shadowGenRef, shadowUrlRef, beginShadowReloadRef);
122124
const promoteWhenReadyRef = useRef<(gen: number) => void>(() => {});
@@ -179,16 +181,20 @@ export function useShadowPreviewReload({
179181
[],
180182
);
181183

182-
// Nothing replaces the preview under a gesture, and a shadow requested before a gesture's save
183-
// shows the file before it: once that save has landed, a fresh one loads instead.
184+
// Nothing replaces the preview under a gesture, and a shadow requested before a write
185+
// shows the file before it: once that write has landed, a fresh one loads instead.
184186
const heldOrStale = useCallback(
185187
(gen: number) => {
186188
const liveDoc = iframeRef.current?.contentDocument;
187189
if (liveDoc && isStudioManualEditGestureLiveIn(liveDoc))
188190
return waitThenRetry(gen, "gesture", (retry) =>
189191
afterStudioManualEditGestures(liveDoc, retry),
190192
);
191-
if (gestureSavesOnScreen() === savesAtRequestRef.current) return false;
193+
if (
194+
gestureSavesOnScreen() === savesAtRequestRef.current &&
195+
studioFileRevision() === revisionAtRequestRef.current
196+
)
197+
return false;
192198
if (isStudioEditSaving()) return waitThenRetry(gen, "save", afterStudioPendingEdits);
193199
logReload("shadow-reloaded-after-gesture-save", { gen });
194200
const url = new URL(shadowUrlRef.current, window.location.origin);
@@ -335,6 +341,7 @@ export function useShadowPreviewReload({
335341
budgetsSpentRef.current = 0;
336342
shadowUrlRef.current = url;
337343
savesAtRequestRef.current = gestureSavesOnScreen();
344+
revisionAtRequestRef.current = studioFileRevision();
338345
armReadyTimer(gen);
339346
setPreviewSlots((prev) => planShadowReload(prev, gen, url));
340347
// Thumbnails of the edit wait for the new preview instead of competing with it.

‎packages/studio/src/player/hooks/useTimelinePlayer.shadowReload.test.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { SHADOW_READY_BUDGETS, SHADOW_READY_TIMEOUT_MS } from "./useShadowPrevie
88
import { refusedPreviewMessage } from "@hyperframes/core/studio-preview-mark";
99
import { usePlayerStore } from "../store/playerStore";
1010
import { isPreviewChanging } from "../previewReloading";
11+
import { studioWriteHeaders } from "../../utils/studioFileVersion";
1112
import { NLEProvider, useNLEContext, type NLEContextValue } from "../../components/nle/NLEContext";
1213
import {
1314
makeAdapterWindow,
@@ -939,6 +940,32 @@ function stubVisibility(initial: DocumentVisibilityState) {
939940
};
940941
}
941942

943+
describe("a shadow reload loading while a write lands", () => {
944+
it("loads the file again instead of promoting the one it asked for", () => {
945+
const { getApi, root } = renderTimelinePlayerHarness();
946+
const liveIframe = makeLiveIframe();
947+
act(() => {
948+
getApi().iframeRef.current = liveIframe;
949+
getApi().onIframeLoad();
950+
});
951+
act(() => getApi().refreshPlayer());
952+
const asked = getApi().previewSlots.find((slot) => slot.role === "shadow")!;
953+
act(() => getApi().setShadowIframeNode(makeLiveIframe()));
954+
955+
// An undo writes while that shadow is still loading.
956+
studioWriteHeaders();
957+
act(() => {
958+
getApi().onShadowIframeLoad(asked.gen);
959+
getApi().onShadowReadyChange(asked.gen, true);
960+
});
961+
962+
expect(getApi().iframeRef.current).toBe(liveIframe);
963+
const loading = getApi().previewSlots.find((slot) => slot.role === "shadow")!;
964+
expect(loading.gen).not.toBe(asked.gen);
965+
unmount(root);
966+
});
967+
});
968+
942969
describe("useTimelinePlayer scene swap", () => {
943970
function liveFilm(swap?: (html: string) => Promise<void>) {
944971
const { adapter, win } = makeAdapterWindow();
@@ -985,6 +1012,46 @@ describe("useTimelinePlayer scene swap", () => {
9851012
expect(isPreviewChanging()).toBe(false);
9861013
});
9871014

1015+
it("swaps the composition as it is now when a write lands while the HTML is loading", async () => {
1016+
const swap = vi.fn(async () => {});
1017+
const replies: Array<(r: Response) => void> = [];
1018+
const bodies = ["<html>undone-once</html>", "<html>undone-twice</html>"];
1019+
vi.spyOn(globalThis, "fetch").mockImplementation(
1020+
() => new Promise<Response>((resolve) => replies.push(resolve)),
1021+
);
1022+
const { getApi } = liveFilm(swap);
1023+
1024+
act(() => getApi().refreshPlayer());
1025+
// A second undo writes while the first one's preview HTML is still loading.
1026+
studioWriteHeaders();
1027+
replies[0]!(new Response(bodies[0]));
1028+
await settle();
1029+
1030+
expect(swap).not.toHaveBeenCalledWith(bodies[0], expect.anything());
1031+
expect(replies).toHaveLength(2);
1032+
replies[1]!(new Response(bodies[1]));
1033+
await settle();
1034+
expect(swap).toHaveBeenCalledWith(bodies[1], expect.anything());
1035+
});
1036+
1037+
it("gives up refetching and swaps what it has when writes never stop", async () => {
1038+
const swap = vi.fn(async () => {});
1039+
let fetches = 0;
1040+
// The project stops moving well past the bound, so a swap that never gave up still ends.
1041+
vi.spyOn(globalThis, "fetch").mockImplementation(async () => {
1042+
fetches += 1;
1043+
if (fetches < 20) studioWriteHeaders();
1044+
return new Response("<html>vN</html>");
1045+
});
1046+
const { getApi } = liveFilm(swap);
1047+
1048+
act(() => getApi().refreshPlayer());
1049+
await settle();
1050+
1051+
expect(fetches).toBe(6);
1052+
expect(swap).toHaveBeenCalledWith("<html>vN</html>", expect.anything());
1053+
});
1054+
9881055
it("falls back to the full reload when the preview refuses the swap", async () => {
9891056
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("<html>v2</html>"));
9901057
const { getApi } = liveFilm(async () => {

‎packages/studio/src/player/hooks/useTimelinePlayer.ts‎

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,7 @@ import { createPreviewMessageHandler } from "./previewMessageRouter";
4343
import { usePreviewQualityForwarding } from "./usePreviewQualityForwarding";
4444
import { timelineElementsChanged } from "./timelinePlayerSync";
4545
import { safeContentDocument } from "./timelineSyncHydration";
46-
import { sceneSwapFor, supersededByNewerEdit } from "../sceneSwap";
47-
import { whileScriptWrites } from "../previewReloading";
46+
import { sceneSwapFor, supersededByNewerEdit, swapFreshly } from "../sceneSwap";
4847

4948
export interface UseTimelinePlayerOptions {
5049
/** Runs right after a reloaded preview becomes the live iframe. */
@@ -506,13 +505,7 @@ export function useTimelinePlayer({
506505
!!iframe.contentDocument && isStudioManualEditGestureLiveIn(iframe.contentDocument);
507506
if (!swap || isRefreshingRef.current || swapWouldReplaceGestureNode)
508507
return reloadWholeFilm(url.toString());
509-
whileScriptWrites(() => swap(url.toString(), isCurrent, cancel.signal)).catch(
510-
(error: unknown) => {
511-
if (!isCurrent()) return;
512-
logReload("scene-swap-refused", { reason: String(error) });
513-
reloadWholeFilm(url.toString());
514-
},
515-
);
508+
swapFreshly(swap, url, isCurrent, cancel.signal, reloadWholeFilm);
516509
}, [reloadWholeFilm, previewGeneration]);
517510
const pauseRef = useRef(pause);
518511
pauseRef.current = pause;

‎packages/studio/src/player/sceneSwap.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
11
import { studioApiFetch } from "../utils/studioApiFetch";
2+
import { studioFileRevision } from "../utils/studioFileVersion";
3+
import { logReload } from "../utils/reloadDebug";
4+
import { whileScriptWrites } from "./previewReloading";
5+
26
type SwapWindow = Window & {
37
__hfSwapScenes?: (html: string, signal?: AbortSignal) => Promise<void>;
48
};
@@ -74,6 +78,38 @@ export function markScenesStale(iframe: HTMLIFrameElement | null, files: readonl
7478
export const supersededByNewerEdit = () =>
7579
new DOMException("superseded by a newer edit", "AbortError");
7680

81+
const SWAP_REFETCHES_BEFORE_THE_COPY_IN_HAND_WINS = 5;
82+
83+
type SceneSwap = (url: string, isCurrent: () => boolean, cancel?: AbortSignal) => Promise<void>;
84+
85+
export function swapFreshly(
86+
swap: SceneSwap,
87+
url: URL,
88+
isCurrent: () => boolean,
89+
cancel: AbortSignal,
90+
reloadWholeFilm: (url: string) => void,
91+
attempt = 0,
92+
): void {
93+
const at = studioFileRevision();
94+
const fresh = () => studioFileRevision() === at;
95+
const again = () => {
96+
url.searchParams.set("_t", String(Date.now()));
97+
swapFreshly(swap, url, isCurrent, cancel, reloadWholeFilm, attempt + 1);
98+
};
99+
const retries = attempt < SWAP_REFETCHES_BEFORE_THE_COPY_IN_HAND_WINS;
100+
const gate = retries ? () => isCurrent() && fresh() : isCurrent;
101+
whileScriptWrites(() => swap(url.toString(), gate, cancel))
102+
.then(() => {
103+
if (isCurrent() && !fresh() && retries) again();
104+
})
105+
.catch((error: unknown) => {
106+
if (!isCurrent()) return;
107+
if (!fresh() && retries) return again();
108+
logReload("scene-swap-refused", { reason: String(error) });
109+
reloadWholeFilm(url.toString());
110+
});
111+
}
112+
77113
/** Null when the preview cannot swap; rejects when superseded, cancelled or a full reload is needed. */
78114
export function sceneSwapFor(
79115
iframe: HTMLIFrameElement,

0 commit comments

Comments
 (0)